I want select item in list by mouse. I found this code but it didn't work.
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = list.locationToIndex(e.getPoint());
System.out.println("Double clicked on Item " + index);
}
}
};
list.addMouseListener(mouseListener);
try this code, Sample Application it works fine !!!!!!
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class calc {
public static void main(String args[]) {
String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H" };
JFrame frame = new JFrame("Selecting JList");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JList jlist = new JList(labels);
JScrollPane scrollPane1 = new JScrollPane(jlist);
frame.add(scrollPane1, BorderLayout.CENTER);
MouseListener mouseListener = new MouseAdapter() {
public void mouseClicked(MouseEvent mouseEvent) {
JList theList = (JList) mouseEvent.getSource();
if (mouseEvent.getClickCount() == 2) {
int index = theList.locationToIndex(mouseEvent.getPoint());
if (index >= 0) {
Object o = theList.getModel().getElementAt(index);
System.out.println("Double-clicked on: " + o.toString());
}
}
}
};
jlist.addMouseListener(mouseListener);
frame.setSize(350, 200);
frame.setVisible(true);
}
}
Related
I have a SortedListModel called comandaDescriptionListModel:
private SortedListModel comandaDescriptionListModel;
I have other SortedListModels within my application, but this one fails to add items after 1 element. Just 1 element gets added, and it makes no sense.
btnAddComanda.addActionListener(new ActionListener() {
#SuppressWarnings("unchecked")
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel addPanel = new JPanel();
addPanel.add(new JLabel("Descrição:"));
JTextField comandaDescriptionField = new JTextField();
comandaDescriptionField.setPreferredSize(new Dimension(200, 24));
addPanel.add(comandaDescriptionField);
comandaDescriptionField.requestFocusInWindow();
String comandaName = "C" + Integer.toString(comandaListModel.getSize()+1);
int result = JOptionPane.showConfirmDialog(null, addPanel, "Adicionar comanda",
JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
if (comandaListModel.getSize() == 0) {
productComboBox.setEnabled(true);
btnAddProduct.setEnabled(true);
}
String comandaDescription = comandaDescriptionField.getText();
getCurrentCashRegister().addComanda(comandaName, comandaDescription);
// Comanda description model not adding items,
// Need to fix it
comandaListModel.addElement(comandaName);
comandaDescriptionListModel.addElement(comandaDescription); // HERE <<<
comandaList.setSelectedIndex(comandaList.getLastVisibleIndex());
clearProductComboBox();
updateProductComboBox();
}
}
});
Here's a screenshot:
Under "descrição", it should continue to "b" and "c". I can only think it's a bug. Is there some swing bug that causes problems when appending to more than one list at the same time?
When I deal with multi JList components, I do it in own way and also play with all given facilities.
why not, I use this below source code?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MultiListExample extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField textField;
private JButton addBtn, removeBtn;
private JList<String> list1, list2, list3;
private DefaultListModel<String> dlm1, dlm2, dlm3;
public MultiListExample() {
init();
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException ex) {
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MultiListExample();
}
});
}
private void init() {
setTitle("Multi List Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 100, 300, 300);
textField = new JTextField();
textField.setFont(new Font("Dialog", Font.PLAIN, 15));
add(textField, BorderLayout.PAGE_START);
JPanel panel = new JPanel(new BorderLayout());
add(panel, BorderLayout.CENTER);
addBtn = new JButton("Add Element");
addBtn.setFocusPainted(false);
addBtn.setFont(textField.getFont());
panel.add(addBtn, BorderLayout.PAGE_START);
JPanel innerPanel = new JPanel(new GridLayout(1, 3));
panel.add(innerPanel, BorderLayout.CENTER);
dlm1 = new DefaultListModel<String>();
dlm1.addElement("Apple");
dlm1.addElement("Avocado");
dlm1.addElement("Banana");
dlm1.addElement("Jambul");
list1 = new JList<String>(dlm1);
list1.setFont(textField.getFont());
innerPanel.add(list1);
dlm2 = new DefaultListModel<String>();
dlm2.addElement("Currant");
dlm2.addElement("Cherry");
dlm2.addElement("Cloudberry");
dlm2.addElement("Raisin");
list2 = new JList<String>(dlm2);
list2.setFont(textField.getFont());
list2.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 1, Color.BLACK));
innerPanel.add(list2);
dlm3 = new DefaultListModel<String>();
dlm3.addElement("Dragonfruit");
dlm3.addElement("Durian");
dlm3.addElement("Feijoa");
dlm3.addElement("Fig");
dlm3.addElement("Grape");
list3 = new JList<String>(dlm3);
list3.setFont(textField.getFont());
innerPanel.add(list3);
removeBtn = new JButton("Remove Element");
removeBtn.setFocusPainted(false);
removeBtn.setFont(textField.getFont());
add(removeBtn, BorderLayout.PAGE_END);
list1.setSelectedIndex(dlm1.getSize() - 1);
list2.setSelectedIndex(dlm2.getSize() - 1);
list3.setSelectedIndex(dlm3.getSize() - 1);
textField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
addElementListener();
}
});
addBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
addElementListener();
}
});
removeBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (dlm1.getSize() > 0)
dlm1.remove(list1.getSelectedIndex());
if (dlm2.getSize() > 0)
dlm2.remove(list2.getSelectedIndex());
if (dlm3.getSize() > 0)
dlm3.remove(list3.getSelectedIndex());
if (dlm1.getSize() > 0)
list1.setSelectedIndex(0);
if (dlm2.getSize() > 0)
list2.setSelectedIndex(0);
if (dlm3.getSize() > 0)
list3.setSelectedIndex(0);
}
});
setVisible(true);
}
private void addElementListener() {
if (textField.getText().length() > 2) {
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list1, dlm1);
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list2, dlm2);
addSortAndRemoveDuplicates(firstLetterCapWord(textField.getText()), list3, dlm3);
}
}
private void addSortAndRemoveDuplicates(String element, JList<String> list, DefaultListModel<String> model) {
// Here doing all DefaultListModel operations explicitly.
if (!model.contains(element)) {
model.addElement(element);
int size = model.getSize();
String[] elements = new String[size];
for (int i = 0; i < size; i++)
elements[i] = (String) model.getElementAt(i);
Arrays.sort(elements);
model.removeAllElements();
for (int i = 0; i < size; i++)
model.addElement(elements[i]);
list.setSelectedIndex(model.getSize() - 1);
}
}
private String firstLetterCapWord(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
}
The appropiate way to remove all rows from a table is to use:
DefaultTableModel tableModel = (DefaultTableModel) tablaPedidos.getModel();
if (tableModel.getRowCount() > 0) {
for (int i = tableModel.getRowCount() - 1; i > -1; i--) {
tableModel.removeRow(i);
}
}
However in my application I have a series of tabbedPanes for example tabbedPane 1 and tabbedPane 2, the tabbedPane 2 contains a JTable. My goal is to clean the JTable when I switch between panes.
However I am getting a strange functionality, it works fine only when none of the rows of the JTable are selected, when one row was left selected in the table and then I switch between tabbedPanes after I enter in tabbedPane 2 I get an exception in the ListSelectionListener.
//If a row in the table was left selected when I switched between tabbedPanes I get a ArrayIndexOutOfBoundsException exception when running this code
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
if(!event.getValueIsAdjusting()) {
String numeroPedido = table.getValueAt(table.getSelectedRow(), 0).toString();
}
}
});
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.Vector.elementData(Vector.java:730)
at java.util.Vector.elementAt(Vector.java:473)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:649)
I just don't get it what's the influence of having a row selected to get this exception.
Example code:
Container.java, that contains both of the TabbedPanes
package testClearTable;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JTabbedPane;
public class Container extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Container frame = new Container();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Container() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 926, 556);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
contentPane.add(tabbedPane, BorderLayout.CENTER);
TabbedPane1 tabbedPane1 = new TabbedPane1();
tabbedPane.addTab("TabbedPane1", null, tabbedPane1, null);
TabbedPane2 tabbedPane2 = new TabbedPane2();
tabbedPane.addTab("TabbedPane2", null, tabbedPane2, null);
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
JTabbedPane sourceTabbedPane = (JTabbedPane) changeEvent.getSource();
int index = sourceTabbedPane.getSelectedIndex();
if(sourceTabbedPane.getTitleAt(index).equals("TabbedPane2")) {
Random r = new Random();
int randomNumber = r.nextInt(101);
TabbedPane2.updateTable(randomNumber);
System.out.println("Update table.");
}
System.out.println("Tab changed to: " + sourceTabbedPane.getTitleAt(index));
}
};
tabbedPane.addChangeListener(changeListener);
}
}
TabbedPane1.java
package testClearTable;
import javax.swing.JPanel;
public class TabbedPane1 extends JPanel {
/**
* Create the panel.
*/
public TabbedPane1() {
}
}
TabbedPane2.java
package testClearTable;
import java.util.ArrayList;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
public class TabbedPane2 extends JPanel {
private static JTable table;
/**
* Create the panel.
*/
public TabbedPane2() {
setLayout(new MigLayout("", "[][grow]", "[][grow]"));
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, "cell 1 1,grow");
table = new JTable();
scrollPane.setViewportView(table);
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Col 1", "Col 2", "Col 3"
}
));
addDummyData();
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
if(!event.getValueIsAdjusting()) {
String numeroPedido = table.getValueAt(table.getSelectedRow(), 0).toString();
}
}
});
}
public void addDummyData() {
for(int i = 0 ; i < 10; i++) {
Object [] fila = new Object[table.getModel().getColumnCount()];
fila[0] = String.valueOf(i);
fila[1] = String.valueOf(i);
fila[2] = String.valueOf(i);
((DefaultTableModel) table.getModel()).addRow(fila);
}
}
public static void addDummyData2(int k) {
for(int i = 0 ; i < k; i++) {
Object [] fila = new Object[table.getModel().getColumnCount()];
fila[0] = String.valueOf(i);
fila[1] = String.valueOf(i);
fila[2] = String.valueOf(i);
((DefaultTableModel) table.getModel()).addRow(fila);
}
}
private static void clearTable() {
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
if (tableModel.getRowCount() > 0) {
for (int i = tableModel.getRowCount() - 1; i > -1; i--) {
tableModel.removeRow(i);
}
}
}
public static void updateTable(int i) {
clearTable();
addDummyData2(i);
}
}
Maybe call JTable.clearSelection() before removing all the data?
The problem comes from the addListSelectionListener . The ListSelectionEvent has been triggered and after cleaning the table and writing again there is no row selected.
public void valueChanged(ListSelectionEvent event) {
if(!event.getValueIsAdjusting()) {
if(tablaPedidos.getSelectedRow() > -1) {
When adding the verification to only perform an action when there is an actual row selected I dont get the exception.
What I don't understand why clearing and writing again is triggering the ListSelectionEvent.
I was wondering if there is a way, by selecting an item with a JList, to let the program perform some code. This code should run every time a new item is selected.
Previously, I had added a listener. Here is a minimal example I made.
public class Driver {
public static void main(String[] args) {
JFrame frame = new ListFrame();
frame.setVisible(true);
frame.setSize(200,100);
}
}
public class ListFrame extends JFrame {
private JList<String> list;
private JScrollPane scrollPane;
private String[] data = {"A","B","C"};
private JButton addButton = new JButton("Add");
public ListFrame() {
setLayout(new BorderLayout());
list = new JList<String>(data);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane = new JScrollPane(list);
add(scrollPane, BorderLayout.CENTER);
add(addButton, BorderLayout.SOUTH);
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
String newEntry = JOptionPane.showInputDialog("Add new entry.");
String[] tempData = new String[data.length + 1];
for(int i = 0; i < data.length; i++)
tempData[i] = data[i];
tempData[data.length] = newEntry;
data = tempData;
list = new JList<String>(data);
scrollPane.setViewportView(list);
}
});
list.addListSelectionListener(
new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
System.out.println("Hi");
}
});
}
}
However, when I click an item on the Jlist, nothing is printed.
Your example uses getSelectionModel() to get the the list's ListSelectionModel, and it adds your listener directly to the selection model. This bypasses the ListSelectionHandler, used internally by JList, which never gets a chance to fireSelectionValueChanged(). Instead, let JList add your listener:
list.addListSelectionListener(new ListSelectionListener() {...}
when I click an item on the JList, nothing is printed.
Your new example prints "Hi" when I click an item, but I see some problems:
Be sure to run on the event dispatch thread.
Check the ListSelectionEvent for details of what happened.
To add elements to the list, don't create a new JList; update the list's ListModel instead.
See How to Write a List Selection Listener for more; here's the example I tested.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Driver {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new ListFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
});
}
private static class ListFrame extends JFrame {
private final String[] data = {"A", "B", "C"};
private final DefaultListModel model = new DefaultListModel();
private final JList<String> list = new JList<>(model);
private final JButton addButton = new JButton("Add");
public ListFrame() {
for (String s : data) {
model.addElement(s);
}
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(list), BorderLayout.CENTER);
add(addButton, BorderLayout.SOUTH);
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
String newEntry = JOptionPane.showInputDialog("Add new entry.");
model.addElement(newEntry);
}
});
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println(e.getFirstIndex() + " " + e.getLastIndex());
}
}
});
}
}
}
I have a list in which I display elements. I want each time I select an element from the list to display its index inside another JPanel.
The code:
leftPanel.setLayout(new BoxLayout(leftPanel,BoxLayout.PAGE_AXIS));
leftList = new JList(listModel);
leftList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listScrollPane = new JScrollPane(leftList);
listScrollPane.setBorder(BorderFactory.createTitledBorder("Proteins"));
rightPanel.setBackground(Color.magenta);
rightPanel.setLayout(new FlowLayout());
for (String name : allNames) {
listModel.addElement(name);
}
leftList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent event) {
int nameIndex = leftList.getSelectedIndex();
JLabel msglabel = new JLabel("index = " + nameIndex, JLabel.CENTER);
rightPanel.add(msglabel);
}
});
This doesn't display anything in the JPanel
In this code when a element is selected it can be moved to another list by pressing a button check this code it will help you
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class Exp extends JFrame {
private JList rl;
private JList ll;
private JButton b;
private static String[] foods = { "asd", "asd", "dfg", "wer", "tyu" };
public Exp() {
super("Title");
setLayout(new FlowLayout());
ll = new JList(foods);
ll.setVisibleRowCount(3);
ll.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
ll.setFixedCellHeight(15);
ll.setFixedCellWidth(100);
add(new JScrollPane(ll));
b = new JButton("Move -->");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rl.setListData(ll.getSelectedValues());
}
});
add(b);
rl = new JList();
rl.setVisibleRowCount(3);
rl.setFixedCellHeight(15);
rl.setFixedCellWidth(100);
rl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(rl));
}
}
This question already has answers here:
How can I change the width of a JComboBox dropdown list?
(7 answers)
Closed 8 years ago.
How can I set a fixed width of a JComboboxs popup-menu that is using GridBagLayout and fill=HORIZONTAL?
One of the things I tried is to just override the getSize() method but dose not work.
public class ComboBoxSize extends JFrame {
public static void main(String args[]) {
// THE COMBOBOX
String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
JComboBox<String> comboBox = new JComboBox<String>(labels) {
public Dimension getSize() {
Dimension d = getPreferredSize();
d.width = 50;
return d;
}
};
comboBox.setMaximumRowCount(comboBox.getModel().getSize());
// ADD COMBOBOX TO PANEL
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(comboBox, c);
// ADD PANEL TO FRAME
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Here is the solution, this worked for me, add this PopupMenuListener to your JComboBox:
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.ComboPopup;
public class CustomComboBoxPopupMenuListener implements PopupMenuListener {
// ==============================================================================
// Members
// ==============================================================================
private int bgTop = 0;
private int bgLeft = 0;
private int bgRight = 0;
private int bgBottom = 0;
// ==============================================================================
// Constructors
// ==============================================================================
public CustomComboBoxPopupMenuListener() {
super();
}
// ==============================================================================
// Methods
// ==============================================================================
public void popupMenuCanceled(PopupMenuEvent e) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
final JComboBox box = (JComboBox) e.getSource();
final Object comp = box.getUI().getAccessibleChild(box, 0);
if (!(comp instanceof JPopupMenu)) {
return;
}
final JPopupMenu popupMenu = (JPopupMenu) comp;
popupMenu.setBorder(null);
if (popupMenu.getComponent(0) instanceof JScrollPane) {
final JScrollPane scrollPane = (JScrollPane) popupMenu
.getComponent(0);
scrollPane.setBorder(BorderFactory.createEmptyBorder(bgTop, bgLeft,
bgBottom, bgRight));
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
if (popupMenu instanceof ComboPopup) {
final ComboPopup popup = (ComboPopup) popupMenu;
final JList list = popup.getList();
list.setBorder(null);
final Dimension size = list.getPreferredSize();
size.width = Math.max(box.getPreferredSize().width + bgLeft
+ bgRight, box.getWidth());
size.height = Math.min(scrollPane.getPreferredSize().height
+ bgTop + bgBottom, size.height + bgTop + bgBottom);
scrollPane.setPreferredSize(size);
scrollPane.setMaximumSize(size);
}
}
}
}
Example in your code:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ComboBoxSize extends JFrame {
public static void main(String args[]) {
// THE COMBOBOX
String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
JComboBox<String> comboBox = new JComboBox<String>(labels);
comboBox.setMaximumRowCount(comboBox.getModel().getSize());
comboBox.addPopupMenuListener(new CustomComboBoxPopupMenuListener());
// ADD COMBOBOX TO PANEL
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(comboBox, c);
// ADD PANEL TO FRAME
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Source: click here