/* InClassGUI2.java CIS 160 2014-10-28 David Klick Demonstration of GUI with radio buttons, check boxes, a combo box (drop down list), and a button group. */ import java.awt.Color; import java.awt.Container; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.SwingUtilities; public class InClassGUI2 extends JFrame { // Create an object out of ourself when program starts. public static void main(String[] args) { new InClassGUI2(); } // Create thread to setup GUI when the EDT has time. public InClassGUI2() { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } // This method sets up the GUI and displays it. public void createAndShowGUI() { // Create containers. Container c = getContentPane(); JPanel pnl1 = new JPanel(); JPanel pnl2 = new JPanel(); JPanel pnl3 = new JPanel(); JPanel pnl4 = new JPanel(); // Set layout managers. c.setLayout(new GridLayout(4, 1)); pnl1.setLayout(new GridLayout(1,2)); pnl2.setLayout(new GridLayout(1,2)); pnl3.setLayout(new GridLayout(1,2)); pnl4.setLayout(new GridLayout(1,2)); // Add borders to three panels. pnl1.setBorder(BorderFactory.createLineBorder(Color.BLACK)); pnl2.setBorder(BorderFactory.createLineBorder(Color.BLACK)); pnl3.setBorder(BorderFactory.createLineBorder(Color.BLACK)); // Create widgets. JCheckBox chk1 = new JCheckBox("Hot dogs", true); JCheckBox chk2 = new JCheckBox("Cheese Fries"); JRadioButton rdo1 = new JRadioButton("Plain", true); JRadioButton rdo2 = new JRadioButton("w/Salsa"); JRadioButton rdo3 = new JRadioButton("Dropped", true); JRadioButton rdo4 = new JRadioButton("Not dropped"); String[] seasonings = {"Mild", "Hot", "Insane", "Lethal"}; JComboBox cbo = new JComboBox(seasonings); // A button group lets radio buttons act properly. // Note: The first two radio buttons (rdo1 and rdo2) are not // in a button group so only rdo3 and rdo4 will act as // proper radio buttons. ButtonGroup grp = new ButtonGroup(); grp.add(rdo3); grp.add(rdo4); // Add widgets to containers. pnl1.add(chk1); pnl1.add(chk2); pnl2.add(rdo1); pnl2.add(rdo2); pnl3.add(rdo3); pnl3.add(rdo4); pnl4.add(cbo); // Add subcontainers to main container. c.add(pnl1); c.add(pnl2); c.add(pnl3); c.add(pnl4); // Set close operation and display GUI. setTitle("Here's the title"); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); setVisible(true); } }