【问题标题】:how do i change the size of Jbuttons without changing the size of the Jpanel its sitting on?如何在不改变其所在的 Jpanel 大小的情况下更改 Jbuttons 的大小?
【发布时间】:2014-05-30 13:04:08
【问题描述】:

所以我在屏幕上有 2 个面板。一个设置为 WES​​T,另一个设置为 CENTER 以占据屏幕的其余部分。 我遇到的问题:

  1. 当我改变按钮的大小时,它要么改变面板的大小,要么什么都不做。注释掉的行是我试图这样做的地方。如何在不改变面板大小的情况下使按钮变小?
  2. 就调整大小而言,2 个按钮是否总是会做同样的事情?或者有没有一种方法可以使不同大小的不同按钮之间有不同的空间,而不必将它们分配到不同的面板?

 public MainPanel() {
        super();

        this.setLayout(new BorderLayout());
        buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(5, 1));
        buttonPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        this.add(buttonPanel, BorderLayout.WEST);

                centerPanel = new JPanel();
        centerPanel.setBackground(Color.black);
        centerPanel.setOpaque(true);
        centerPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        this.add(centerPanel, BorderLayout.CENTER);

        JButton options = new JButton("Options");
        //options.setPreferredSize(new Dimension(100, 100));
        buttonPanel.add(options);
        options.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                RichardDemo.this.switchPanel(MainPanel.this);
            }
        });     

        JButton start = new JButton("Start Game");
        buttonPanel.add(start);
        start.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

            }
        });
    }
}

【问题讨论】:

  • 您的预期输出是什么?可以发图吗?

标签: java swing jpanel jbutton layout-manager


【解决方案1】:

当我改变按钮的大小时,它要么改变面板的大小,要么什么都不做?

您不需要更改组件的大小。只需将其留给 Layout Manager 来调整组件的大小。

就调整大小而言,这两个按钮总是做同样的事情吗?

它不是必需的。这取决于您使用的布局。

有没有一种方法可以使不同大小的不同按钮之间有不同的空间,而不必将它们分配给不同的面板?

是的,您可以使用 GridBagLayout 来实现。

【讨论】:

    猜你喜欢
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2014-10-07
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    相关资源
    最近更新 更多