Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JComboBox width

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 adding the code here:

import javax.swing.*;
import java.awt.BorderLayout;

public class Window8  {

    JFrame frame;
    JPanel panel;
    JComboBox combo;
    public void go(){

    String[] option = { "STUDENT", "TEACHER" };

    combo.setPreferredSize(new Dimension(1,25));
    combo = new JComboBox(option);
    menu.setSelectedIndex(0);

    frame = new JFrame("DELETION"); 
    frame.setLocationRelativeTo(null);
    frame.setSize(400, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

    panel = new JPanel();
    panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));

    frame.getContentPane().add(BorderLayout.NORTH,panel);
    panel.add(combo);   
}
like image 621
Suman.hassan95 Avatar asked Jan 07 '11 18:01

Suman.hassan95


People also ask

What is the difference between JList and JComboBox?

A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items.

Which is the superclass for JComboBox?

Other methods you are most likely to invoke on a JComboBox object are those it inherits from its superclasses, such as setPreferredSize . See The JComponent API for tables of commonly used inherited methods.


2 Answers

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.

like image 168
camickr Avatar answered Nov 15 '22 15:11

camickr


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

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

like image 22
Romain Hippeau Avatar answered Nov 15 '22 16:11

Romain Hippeau