[英]Adding components dynamically to the JPanel changing components size
How to set the location of the components in a panel. 如何在面板中设置组件的位置。
JComboBox startDate = new JComboBox(); startDate.setPreferredSize(new Dimension(80,25)); jPanelStartDate.add(startDate); jPanelStartDate.setLayout(new GridLayout(0, 3, 10, 10)); jPanelStartDate.revalidate();
Ok, you have more than one option. 好的,您有多个选择。 You can use a BoxLayout with a Y_Axis and a rigid area or you can use the more advanced, complex and dynamic GridBagLayout . 您可以使用具有Y_Axis和刚性区域的BoxLayout ,也可以使用更高级,复杂和动态的GridBagLayout 。 The following is an example with a BoxLayout and rigid areas. 以下是具有BoxLayout和刚性区域的示例。
JFrame frame = new JFrame("Test");
JPanel panel = new JPanel();
BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(boxLayout);
for(int index = 0; index < 5; ++index){
JComboBox<String> box = new JComboBox<>(new String[]{"a", "b", "c"});
box.setMaximumSize(new Dimension(50, 50));
box.setMinimumSize(new Dimension(50, 50));
panel.add(box);
panel.add(Box.createRigidArea(new Dimension(10, 10)));
}
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 300));
frame.setVisible(true);
You can change the dimensions, specially of the rigid area to adjust the spaces and the sizes of the components according to your needs. 您可以更改尺寸,特别是刚性区域的尺寸,以根据需要调整组件的空间和尺寸。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.