1Graphical User InterfacesContainers and Components• Frame - OS-managed container used todisplay GUI-based java apps• Panel - Container used to organized otherGUI components (buttons, labels, etc)• Label - Component used to display text//Similar to Authority.java from Lewis/Loftusimport java.awt.*;import javax.swing.*;public class GUI { public static void main(String[] args) {JFrame frame = new JFrame("First GUI"); //takes title for windowframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);JPanel panel = new JPanel();panel.setBackground(Color.red);panel.setPreferredSize(new Dimension(250, 75));JLabel label = new JLabel("My first GUI");panel.add(label); //add label to panelframe.getContentPane().add(panel); //add panel to content pane of frameframe.pack(); //size to the preferred sizeframe.setVisible(true); //make visible }}Exercises1. Experiment with class GUI1. Change the color of the panel2. Change the size of the panel3. See what happens if you do not “pack”4. See what happens if you do not make visible5. Add a second label of a different colorMore Components• Buttons - Component that can be “pushed”– must invoke addActionListener in order toenable the program to respond to a buttonpush– program waits for an event and the performsthe appropriate actionpublic class GUIWButton { public GUIWButton() { JFrame frame = new JFrame("First GUI"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setBackground(Color.red); panel.setPreferredSize(new Dimension(250, 75)); JLabel label = new JLabel("Count is 0"); JButton button = new JButton("Push Me!"); button.addActionListener(new ButtonListener(label)); panel.add(label); panel.add(button); frame.getContentPane().add(panel); frame.pack(); //size to the preferred size frame.setVisible(true); }2 private class ButtonListener implements ActionListener { JLabel label; int count; public ButtonListener(JLabel label) { this.label = label; this.count = 0; } public void actionPerformed(ActionEvent event) { count++; label.setText("Count is " + count); } } public static void main(String[] args) { GUIWButton mygui = new GUIWButton(); System.out.println("running..."); }}Exercises1. Compile and run GUIWButton.2. Create a GUI with a label and text field. Allowthe user to enter text in the text field. Whenthe user presses enter, update the text of thelabel to be the text contained in the text field.3. Add a button to the program you wrote forexercise 2. When the user presses the buttonOR presses enter, update the text of the labelto be the text contained in the text field.4. Modify your program from exercise 3 to keepa count of the number of times you havechanged the
View Full Document