简体   繁体   English

将组件动态添加到JPanel中以更改组件大小

[英]Adding components dynamically to the JPanel changing components size

  1. I am trying to add combo box to the JPanel dynamically but the combo box occupying entire panel.According to the combo box count the size of the combo boxes are changing but I want fixed size of the combo box and I need to create the combo boxes one by one means below of another combo /in a new line. 我正在尝试将组合框动态添加到JPanel,但是组合框占据整个面板。根据组合框计数,组合框的大小正在更改,但是我想要固定的组合框尺寸,需要创建组合框在另一个组合下方/在新行中逐一表示。
  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM