// This demo shows only a few variations of the "Swing" graphical objects // used in this program; there are many more, especially involving the // 'JList' class import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class JFrameJMenuJSliderJComboJList extends JFrame implements ActionListener, ChangeListener, ListSelectionListener { // Objects that need to be referenced from outside the constructor // must be defined here (so that they are global to the class) private JSlider slider; private JComboBox combo; private JList list; private DefaultListModel listModel; private JScrollPane listScrollPane; private JTextField textList, textCombo; private JButton buttonAddToCombo, buttonRemoveFromCombo, buttonClearCombo; private JButton buttonAddToList, buttonRemoveFromList, buttonClearList; static final int SLIDER_MIN = 0; static final int SLIDER_MAX = 30; static final int SLIDER_INIT = 15; boolean editInProgress = false; public static void main(String[] args) { new JFrameJMenuJSliderJComboJList(); } // Constructor public JFrameJMenuJSliderJComboJList() { // Note that it is NOT necessary to explicitly create a 'JFrame' object // here, since extending the 'JFrame' class does that automatically // Allow objects to be placed anywhere on the JFrame setLayout(null); // Don't let the JFrame be resized setResizable(false); // Allow the JFrame to be closed via the "X" setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set the size, title, and background color of the JFrame setSize(440, 460); setTitle("Demo #4: JFrame, JMenuBar, JSlider, JComboBox, & JList"); getContentPane().setBackground(Color.BLACK); // Position the JFrame in the center of the screen setLocationRelativeTo(null); //=============================================================================// // Create a JMenuBar JMenuBar menuBar = new JMenuBar(); // Create two (top level) JMenus JMenu fileMenu = new JMenu("File"); JMenu helpMenu = new JMenu("Help"); // Create three JCheckBoxMenuItems and two JMenuItems and allow them to // respond to user actions JCheckBoxMenuItem sliderMenuItem = new JCheckBoxMenuItem("Show JSlider"); sliderMenuItem.setActionCommand("slider"); sliderMenuItem.addActionListener(this); JCheckBoxMenuItem comboBoxMenuItem = new JCheckBoxMenuItem("Show JComboBox"); comboBoxMenuItem.setActionCommand("combo"); comboBoxMenuItem.addActionListener(this); JCheckBoxMenuItem listMenuItem = new JCheckBoxMenuItem("Show JList"); listMenuItem.setActionCommand("list"); listMenuItem.addActionListener(this); JMenuItem exitMenuItem = new JMenuItem("Exit"); exitMenuItem.setActionCommand("exit"); exitMenuItem.addActionListener(this); JMenuItem aboutMenuItem = new JMenuItem("About..."); aboutMenuItem.setActionCommand("about"); aboutMenuItem.addActionListener(this); // Add the above JMenuItems, and separators, to the two JMenus fileMenu.add(sliderMenuItem); fileMenu.addSeparator(); fileMenu.add(comboBoxMenuItem); fileMenu.add(listMenuItem); fileMenu.addSeparator(); fileMenu.add(exitMenuItem); helpMenu.add(aboutMenuItem); // Add the two JMenus to the JMenuBar menuBar.add(fileMenu); menuBar.add(helpMenu); // Add the JMenuBar to the JFrame setJMenuBar(menuBar); //=============================================================================// // Create and set up a JSlider slider = new JSlider(JSlider.HORIZONTAL, SLIDER_MIN, SLIDER_MAX, SLIDER_INIT); slider.setLocation(27, 25); slider.setSize(380, 50); slider.setMinorTickSpacing(1); slider.setMajorTickSpacing(3); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.setVisible(false); // Allow the JSlider to respond to actions and add it to the JFrame slider.addChangeListener(this); add(slider); //=============================================================================// // Create and set up a JComboBox String[] comboData = {"cat", "dog", "fish", "ant", "bee", "shark", "zebra", "elephant"}; combo = new JComboBox(comboData); combo.setLocation(27, 100); combo.setSize(90, 20); combo.setVisible(false); // Set the index of the JComboBox item that should be initially highlighted; to // start off with NO element highlighted, use the value of -1 combo.setSelectedIndex(0); // Allow the JComboBox to respond to actions and add it to the JFrame combo.addActionListener(this); add(combo); //=============================================================================// textCombo = new JTextField(); textCombo.setLocation(256, 100); textCombo.setSize(150, 20); textCombo.setHorizontalAlignment(JTextField.CENTER); textCombo.setVisible(false); add(textCombo); buttonAddToCombo = new JButton("Add Element"); buttonAddToCombo.setLocation(256, 125); buttonAddToCombo.setSize(150, 20); buttonAddToCombo.setVisible(false); add(buttonAddToCombo); buttonRemoveFromCombo = new JButton("Remove Element"); buttonRemoveFromCombo.setLocation(256, 150); buttonRemoveFromCombo.setSize(150, 20); buttonRemoveFromCombo.setVisible(false); add(buttonRemoveFromCombo); buttonClearCombo = new JButton("Clear ComboBox"); buttonClearCombo.setLocation(256, 175); buttonClearCombo.setSize(150, 20); buttonClearCombo.setVisible(false); add(buttonClearCombo); buttonAddToCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (!textCombo.getText().trim().equals("")) combo.insertItemAt(textCombo.getText().trim(), combo.getSelectedIndex() + 1); // combo.addItem(textCombo.getText().trim()); <-- Use to always add at END of box } }); buttonRemoveFromCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { // Whenever an item is removed from the JComboBox, another item in // the JComboBox (usually the item immediately preceding the removed // item) is automatically selected; this, in turn, triggers the // 'actionPerformed' method; the variable 'editInProgress' is used // to prevent unwanted output from the 'actionPerformed' method editInProgress = true; if (combo.getSelectedIndex() > -1) combo.removeItemAt(combo.getSelectedIndex()); } }); buttonClearCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { combo.removeAllItems(); } }); //=============================================================================// // Create a JList and assign to it a DefaultListModel listModel = new DefaultListModel(); list = new JList(listModel); // Note that the JList is useful for displaying static data, but to add, // remove, or change elements, a DefaultListModel (or AbstractListModel or // ListModel) must be used, and the JList will automatically reflect any // changes made; while this approach may be confusing at first, its purpose // is to break the list management process into a read-only component and a // writable component, allowing the first to exist without the second String[] listData = {"cat", "dog", "fish", "ant", "bee", "shark", "zebra", "elephant", "whale", "aardvark", "goat", "porcupine", "walrus", "giraffe", "crocodile"}; for (String element : listData) listModel.addElement(element); // Set the number of JList columns to be used for displaying data (VERTICAL, // VERTICAL_WRAP, or HORIZONTAL_WRAP) list.setLayoutOrientation(JList.VERTICAL); // Set the number of rows in the JList that are visible without scrolling; // note that if the dimensions of the JScrollPane (below) are manually set // (if a 'null' layout manager is used), then this next line will have no // effect list.setVisibleRowCount(5); // Set the index of the JList item that should be initially highlighted; // the value of -1 is used to start off with NO element highlighted list.setSelectedIndex(-1); // Determine how many JList items the user is able to select (highlight) // at one time (SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, or // MULTIPLE_INTERVAL_SELECTION) list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Allow the JList to respond to actions list.addListSelectionListener(this); // Create and set up a JScrollPane, and add the JList to it; a JScrollPane // provides a scrollable view of a component, so using a JScrollPane here // allows the user to see and easily access large numbers of data items listScrollPane = new JScrollPane(list); listScrollPane.setLocation(27, 290); listScrollPane.setSize(90, 94); listScrollPane.setVisible(false); // Add the JScrollPane to the JFrame add(listScrollPane); //=============================================================================// textList = new JTextField(); textList.setLocation(256, 290); textList.setSize(150, 20); textList.setHorizontalAlignment(JTextField.CENTER); textList.setVisible(false); add(textList); buttonAddToList = new JButton("Add Element"); buttonAddToList.setLocation(256, 315); buttonAddToList.setSize(150, 20); buttonAddToList.setVisible(false); add(buttonAddToList); buttonRemoveFromList = new JButton("Remove Element"); buttonRemoveFromList.setLocation(256, 340); buttonRemoveFromList.setSize(150, 20); buttonRemoveFromList.setVisible(false); add(buttonRemoveFromList); buttonClearList = new JButton("Clear List"); buttonClearList.setLocation(256, 365); buttonClearList.setSize(150, 20); buttonClearList.setVisible(false); add(buttonClearList); buttonAddToList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (!textList.getText().trim().equals("")) listModel.insertElementAt(textList.getText().trim(), list.getSelectedIndex() + 1); // listModel.addElement(textList.getText().trim()); <-- Use to always add to END of list } }); buttonRemoveFromList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (list.getSelectedIndex() > -1) listModel.removeElementAt(list.getSelectedIndex()); } }); buttonClearList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { listModel.clear(); } }); //=============================================================================// // Make the JFrame (and everything on it) visible; note that this line // is executed AFTER the above objects have been added to the JFrame // to ensure that all of the above added objects appear on the JFrame setVisible(true); } //================================================================================// // This method is called whenever one of the JMenuItems is selected, as well // as when the selected item in the JComboBox has changed public void actionPerformed(ActionEvent event) { if (event.getActionCommand() == "slider") { slider.setVisible(!slider.isVisible()); return; } if (event.getActionCommand() == "combo") { combo.setVisible(!combo.isVisible()); textCombo.setVisible(!textCombo.isVisible()); buttonAddToCombo.setVisible(!buttonAddToCombo.isVisible()); buttonRemoveFromCombo.setVisible(!buttonRemoveFromCombo.isVisible()); buttonClearCombo.setVisible(!buttonClearCombo.isVisible()); textCombo.requestFocus(); return; } // If the JComboBox selected item has changed, display both the index of // the item and the item itself if (event.getActionCommand() == "comboBoxChanged") { // If a JComboBox item is not currently in the process of being // selected, display the newly selected value if (!editInProgress && combo.getSelectedIndex() > -1) { System.out.print("ComboBox Index: " + combo.getSelectedIndex() + " "); System.out.println("ComboBox Item: " + combo.getSelectedItem()); } editInProgress = false; } if (event.getActionCommand() == "list") { listScrollPane.setVisible(!listScrollPane.isVisible()); textList.setVisible(!textList.isVisible()); buttonAddToList.setVisible(!buttonAddToList.isVisible()); buttonRemoveFromList.setVisible(!buttonRemoveFromList.isVisible()); buttonClearList.setVisible(!buttonClearList.isVisible()); textList.requestFocus(); return; } if (event.getActionCommand() == "about") { System.out.println("Choose options from the 'File' pulldown menu to see more examples of \"Swing\" objects."); return; } if (event.getActionCommand() == "exit") System.exit(0); } //================================================================================// // This method is called whenever the value of the JSlider is changed public void stateChanged(ChangeEvent event) { // If the JSlider value is not currently in the process of being adjusted, // display the newly selected value JSlider sliderSource = (JSlider) event.getSource(); if (!sliderSource.getValueIsAdjusting()) System.out.println("Slider Value: " + sliderSource.getValue()); } //================================================================================// // This method is called whenever an item is selected from the JList public void valueChanged(ListSelectionEvent event) { // Since this method appears to be called when the user clicks on a JList // item, as well as when the data value is officially selected, make sure // the first occurrence of each click is ignored so that the newly selected // value is not displayed twice; also make sure no values are displayed // after an element is removed from the JList if (!list.getValueIsAdjusting() && list.getSelectedIndex() > -1) { System.out.print("List Index: " + list.getSelectedIndex() + " "); System.out.println("List Item: " + list.getSelectedValue()); } } }