package examples; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * CS401 Example 36c * * Demonstrates the use of a JComboBox GUI component. A combo box can work much * like a group of radio buttons in that it displays a set of options from which * the user can select only one at a time. It, however, can take up far less * screen space since the available options are only displayed when the user * clicks a downward pointing arrow to show a popup list containing the options. * * Additionally, the JComboBox can provide the means for the user to enter a new * value for the list. The setEditable() method enables this functionality. * This program would through * * @author PJ Dillon */ public class ex36c implements ActionListener { private int[] styles = {Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD+Font.ITALIC}; private JLabel label; private JComboBox box; public ex36c() { JFrame window = new JFrame("Example 36c"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container c = window.getContentPane(); c.setLayout(new FlowLayout()); label = new JLabel("Text To Change"); label.setFont(new Font("TimesRoman", Font.PLAIN, 72)); c.add(label); /* * The combobox maintains an internal group of items it's currently storing, * typicially called the component's model, which renders as the list * displayed when the user clicks the drop down button. One of the JComboBox * constructors accepts an array of objects that initialize this group, * meaning the array is the list of Objects displayed. */ String[] names = {"Plain", "Bold", "Italics", "Bold/Italics"}; box = new JComboBox(names); box.addActionListener(this); c.add(box); /* * By setting the combo box to be editable, we give the user the ability to * enter new values into the combo box area on the screen. These values are * automatically added to the list in the combo box. */ //box.setEditable(true); /* * The setMaximumRowCount() method limits the size of the drop down list to * only display the number of items specified here. If there are more items * in the list, a scroll bar is automatically shown for the user. Setting * this value can give your code a nicer feel. */ box.setMaximumRowCount(3); window.setSize(520, 200); window.setVisible(true); } public void actionPerformed(ActionEvent e) { /* * If the combobox is set to editable and the user enters a new value into * it, this line will throw an exception because the new value is not * automatically added to combo box list, making the call to * getSelectedIndex() return -1. */ label.setFont(new Font("TimesRoman", styles[box.getSelectedIndex()], 72)); } public static void main(String[] args) { new ex36c(); } }