JComboBox width

后端 未结 5 960
南旧
南旧 2020-12-15 08:31

I have created a jComboBox but it takes the full width of the frame. how to set the width fixed.

yes borderlayout for the frame and box layout for the panel. i am

相关标签:
5条回答
  • 2020-12-15 08:42

    The width is automatically determined by the width of the largest item added to the combo box. You can control the display by using:

    comboBox.setPrototypeDisplayValue("text here");
    

    You might also consider using the Combo Box Popup to control the popup size.

    Edit:

    Since you added code that shows you are using a BoxLayout you can try the following:

    comboBox.setMaximumSize( comboBox.getPreferredSize() );
    

    Or you can do something like:

    JPanel wrapper = new JPanel();
    wrapper.add( comboBox );
    panel.add( wrapper );
    

    Read the section from the Swing tutorial on Using Layout Managers to understand how these suggestions work.

    0 讨论(0)
  • 2020-12-15 08:46

    Use a different LayoutManager. Try FlowLayout.

    0 讨论(0)
  • 2020-12-15 08:48

    You might want to use setSize() method.

    combo.setSize(200, combo.getPreferredSize().height);
    
    0 讨论(0)
  • 2020-12-15 08:51

    try comboBox.setPreferredWidth(200); or some other value to set the width

    jzd is right. The actual API is setPreferredSize(new Dimension(...));

    0 讨论(0)
  • 2020-12-15 08:58

    Here is something you can do with box layout.

    • Change axis to line axis, Add
    • horizontal glue, Add rigid area,
    • place the component

    . code snippet below:

    panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
    panel.add(Box.createHorizontalGlue());
    panel.add(Box.createRigidArea(new Dimension(10, 0)));
    panel.add(combo);
    frame.getContentPane().add(BorderLayout.NORTH, panel);
    
    0 讨论(0)
提交回复
热议问题