ComboBoxDemo.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ComboBoxDemo implements ActionListener { private JFrame frame; private JComboBox cb; private JLabel label; public ComboBoxDemo() { frame = new JFrame("A Simple Swing App"); //frame.setSize(600, 400); Toolkit tk = frame.getToolkit(); Dimension dim = tk.getScreenSize(); int width = (int)dim.getWidth(); int height = (int)dim.getHeight(); frame.setSize(width, height); frame.setLayout(new FlowLayout()); cb = new JComboBox(); cb.addItem("Banana"); cb.addItem("Apple"); cb.addItem("Orange"); cb.addItem("Grape"); cb.addItem("Mango"); cb.addItem("Pineapple"); cb.addActionListener(this); frame.add(cb); label = new JLabel("I show the selected item"); label.setFont(new Font("Verdana", Font.BOLD, 18)); label.setForeground(Color.RED); frame.add(label); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public void actionPerformed(ActionEvent ae) { label.setText((String)cb.getSelectedItem()); } public static void main(String[] args) { new ComboBoxDemo(); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter