我在使用BoxLayout
时遇到了问题。
在我的示例中,我试图减小文本字段的高度并更改按钮的宽度(如下图底部的绿色标记所示)。我知道有关技术setPreferredSize()
和setMaximumSize()
的信息,但它没有像应该那样起作用。行add(Box.createHorizontalGlue())
也没有帮助。
感谢任何想法。
public class Testy extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
constructGUI();
}
});
}
private static void constructGUI() {
JFrame frame = new JFrame("Testy");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel centerPanel = new JPanel();
centerPanel.setBackground(Color.DARK_GRAY);
centerPanel.setPreferredSize(new Dimension(100, 400));
frame.add(centerPanel, BorderLayout.CENTER);
Testy eastPanel = new Testy();
frame.add(eastPanel, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
public Testy() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
JButton button = new JButton("Button ...... 1");
//button.setPreferredSize(...);
//button.setMaximumSize(...);
add(button);
button = new JButton("Button 2");
//button.setPreferredSize(...);
//button.setMaximumSize(...);
add(button);
button = new JButton("Button ........... 3");
//button.setPreferredSize(...);
//button.setMaximumSize(...);
add(button);
JLabel label = new JLabel("Label");
//label.setPreferredSize(...);
//label.setMaximumSize(...);
add(label);
JTextField textField = new JTextField();
//textField.setPreferredSize(...);
//textField.setMaximumSize(...);
add(textField);
button = new JButton("Button 4");
//button.setPreferredSize(...);
//button.setMaximumSize(...);
add(button);
//add(Box.createHorizontalGlue());
}
}
BorderLayout
的JPanel
,将一个JPanel
(称为centerPanel)放置在CENTER
位置,将一个JPanel
(称为buttonPanel)放置在PAGE_END
位置。现在,使用一个带有GridLayout
的新JPanel
(称为compPanel),并将所有组件放置在其中,然后将此compPanel
放置在centerPanel
中。将JButton(button4)
直接放置在buttonPanel
中。我想这会起作用 :-) - nIcE cOwmain
方法。 - Andrew Thompson