Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
HANNIBAL T posted a comment on http://java-swing-tips.blogspot.com
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AddComboBoxTest {
@SuppressWarnings("unchecked")
public static JComboBox makeComboBox(String[] items) {
//public void addComboBox(String[] items, String label, int position) {
JComboBox comboBox = new JComboBox();
//comboBox.setBorder(new RoundedCornerBorder());
//for(int a=0; a<items.length; a++ ) {
// comboBox.insertItemAt(items[a], a);
//}
comboBox.setModel(new DefaultComboBoxModel(items));
return comboBox;
}
public static JPanel makeTitledPanel(JComponent comboBox, String label) {
JPanel panel_objetos = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel_objetos.setOpaque(false);
panel_objetos.add(new JLabel(label));
panel_objetos.add(comboBox);
return panel_objetos;
}
public JComponent makeUI() {
JPanel panel_filas_padre = new JPanel();
//de esta forma genero los Jcombobox:
String[] items_1 = new String[] {"A","B","C","D","F","G"};
JComboBox comboBox1 = makeComboBox(items_1);
JPanel p1 = makeTitledPanel(comboBox1, "letras");
panel_filas_padre.add(p1); //, position);
//addComboBox(items_1, "letras", 0);
//-------------------------------/
String[] items_2 = new String[] {"1","2","3","4","5","6"};
JComboBox comboBox2 = makeComboBox(items_2);
JPanel p2 = makeTitledPanel(comboBox2, "numeros");
panel_filas_padre.add(p2); //, position);
//addComboBox(items_2, "numeros", 1);
//----------------------------------/
comboBox1.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
JComboBox c = (JComboBox)e.getSource();
System.out.println("ITEM_1 = " + c.getSelectedItem());
}
});
comboBox2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox c = (JComboBox)e.getSource();
System.out.println("ITEM_2 = " + c.getSelectedItem());
}
});
JPanel p = new JPanel(new BorderLayout());
p.add(panel_filas_padre);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new AddComboBoxTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment