520 likes | 634 Views
CS3340: Swing and Event handling. L. Grewe. Swing. Differences between Swing and AWT. Naming Conventions. All Swing components begin with a capital J -- JPanel, JButton, JScrollBar, JApplet , etc. Most Swing Components are “Lightweight”.
E N D
CS3340: Swing and Event handling L. Grewe
Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel, JButton, JScrollBar, JApplet, etc.. Most Swing Components are “Lightweight” • Use Java code rather than native code to draw in the underlying window. • The Exceptions are JFrame, JApplet, JWindow, andJDialog Use Content Pane for adding Components to “Heavyweight” Containers To add Components to a JApplet (in method init( )) use Container cp = new getContentPane( ); cp.add(new JButton(“Start”);
Swing Differences between Swing and AWT Components Use of paintComponent for Drawing public void paintComponent(Graphics g) { super.paintComponent(g); //always call super.paintComponent( ) before performing custom drawing // draw Shape on the Swing Component } Double Buffering In Swing a JPanel is used instead of a Canvas to be the target for drawing graphics objects. When drawing to a JPanel using paintComponent double buffering is automatically employed. There is an option to perform drawing directly to the screen using the paint method by using panel.getGraphics( );
Anatomy of a Java Swing GUI JFrame • JFrame • JPanel • Layout Manager • JComponents JPanel Layout Manager JButton
Build from bottom up Layout Listener • Create: • Frame • Panel • Layout manager • Components • Listeners • Add: (bottom up) • layout manager to panel • listeners to components • components to panel • panel to frame JButton JPanel JFrame
Code JFrame f = new JFrame(“title”) JPanel p = new JPanel( ); JButton b = new JButton(“press me”); p.add(b); // add button to panel f.setContentPane(p); // add panel to frame f.setVisible(true);
General-Purpose Containers • Intermediate containers which can be used under many different circumstances: • Panel (JPanel) • Scroll pane (JScrollPane) • Split pane • Tabbed pane • Tool bar
General Purpose Containers • Panel—most flexible and frequently used. Add almost no functionality beyond what all objects have. Often used to group components. • Scroll pane—provides scroll bars around a large or growable component. • Split pane—displays two components in a fixed amount of space, letting the user adjust the amount of space devoted to each component.
General Purpose Containers • Tabbed pane—contains multiple components but show only one at a time. The user can easily switch between components. • Tool bar—holds a group of components (usually buttons) in a row or column, optionally allowing the user to drag the tool bar into different locations.
General-Purpose Containers Panel Split pane Scroll Pane Tool bar Tabbed pane
Special-Purpose Containers • Intermediate containers that play specific roles in the use interface. • Internal frame— Able to display display a Frame-like window within another window. Usually, you add internal frames to a desktop pane. • Layered frame—Provides a third dimension for positioning components: depth, also known as Z order. • Root pane—Has 4 parts: glass pane, layered pane, content pane, and the (optional) menu bar.
Special-Purpose Containers Internal Frame Layered Pane Root Pane
Layout Managers • Review -layout managers: • null (no manager, programmer sets x,y,w,h) • Flowlayout • GridLayout • BorderLayout n c w e s
Code JFrame f = new JFrame(“title”) JPanel p = new JPanel( ); JButton b = new JButton(“press me”); b.setBounds(new Rectangle(10,10, 100,50)); p.setLayout(null); // x,y layout p.add(b); f.setContentPane(p);
An example nested layout • Container container = new JFrame() or JApplet();JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout());p1.add(new JButton("A"), BorderLayout.NORTH); // also add buttons B, C, D, EJPanel p2 = new JPanel();p2.setLayout(new GridLayout(3, 2));p2.add(new JButton("F")); // also add buttons G, H, I, J, KJPanel p3 = new JPanel();p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS));p3.add(new JButton("L")); // also add buttons M, N, O, Pcontainer.setLayout(new BorderLayout());container.add(p1, BorderLayout.CENTER);container.add(p2, BorderLayout.SOUTH);container.add(p3, BorderLayout.EAST);
Components • Buttons—can be square or round • Combo Box—can be uneditable and editable. • List—Presents the user with a group of items, displayed in a column, to choose from. • Menu—provides a space-saving way to let the user choose one of several options. • Slider—lets user enter a numeric value bounded by a minimum and maximum value. • Text Fields—basic text control that lets the user enter a small amount of text.
Basic Components List Buttons Combo Box Slider Text Fields Menu
More Components – not selectable • Atomic components that exist solely to give the user information. • Label—able to display unselectable text and images. • Progress Bar—displays the progress of a long-running task (also, ProgressMonitor and ProgressMonitorInputStream) • Tool tip—comes up when the user of the program pauses with the cursor over any of the program's buttons
Uneditable Information Displays Progress Bar Label Tool Tips
Editable Displays of Formatted Information • Atomic components that display highly formatted information that can be edited by the user. • Color chooser—provide users with a palette of colors to choose from. • File chooser—provide a GUI for navigating the file system, and then either choosing a file or directory from a list or entering a file name or directory name. • Table—displays tables of data, optionally allowing the user to edit the data. • Text—displays text and allows user to edit it • Tree—displays data in hierarchical way
Editable Displays of Formatted Information File Chooser Color Chooser Tree Table Text
Editable Displays of Formatted Information • Atomic components that display highly formatted information that can be edited by the user. • Color chooser—provide users with a palette of colors to choose from. • File chooser—provide a GUI for navigating the file system, and then either choosing a file or directory from a list or entering a file name or directory name. • Table—displays tables of data, optionally allowing the user to edit the data. • Text—displays text and allows user to edit it • Tree—displays data in hierarchical way
Editable Displays of Formatted Information File Chooser Color Chooser Tree Table Text
Events How to handle user events related to GUI components
Events • Register with a component to receive events • Give component a ref to a Listener object • ActionListener • KeyListener • MouseListener • WindowListener • … click JButton register ActionEvent Listener
Code myListener = new myListenClass; btn.addActionListener(myListener); Class myListenClass implements ActionListener { public void actionPerformed(ActionEvent e){ // button pressed, do stuff here } }
Simplifying: Inheritance Class myframeextendsJFrame{ public myframe(){ // create panel, buttons, … setContentPane(p); // I am a jframe } public static void main(){ JFrame f = new myframe(); } } • Myframe creates JFrame via inheritance
Simplifying: Inheritance Class myframe extends JFrame{ public myframe(){ // create panel, buttons, … } public static void main(){ JFrame f = new myframe(); } public void paint(Graphics g){ super.paint(g); //call overriden method // paint stuff here } } • Override JFrame methods to add functionality
Simplifying: Implements Class myframe extends JFrame implementsActionListener { public myframe(){ // create panel, buttons, … btn.addActionListener(this); } public void actionPerformed(ActionEvent e){ // button pressed, do stuff here } }
Simplifying: Anonymous classes Class myframe extends JFrame { public myframe(){ // create panel, buttons, … btn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e){ // button pressed, do stuff here } } ); } } Defining and instantiating a class on the fly
Components use various listeners • JButton, JMenuItem, JComboBox, JTextField: • addActionListener(ActionListener) • public void actionPerformed(ActionEvent event) • JCheckBox, JRadioButton: • addItemListener(ItemListener) • public void itemStateChanged(ItemEvent event) • JSlider • addChangeListener(ChangeListener) • public void stateChanged(ChangeEvent event) • JTextArea • getDocument().addDocumentListener(DocumentListener) • public void insertUpdate(DocumentEvent event) • public void removeUpdate(DocumentEvent event) • public void changedUpdate(DocumentEvent event)
Components- Getting values • Some user actions normally cause the program to do something: clicking a button, or selecting from a menu • Some user actions set values to be used later: entering text, setting a checkbox or a radio button • You can listen for events from these, but it’s not usually a good idea • Instead, read their values when you need them • String myText = myJTextField.getText(); • String myText = myJTextArea.getText(); • boolean checked = myJCheckBox.isSelected(); • boolean selected1 = myJRadioButton1.isSelected();
Components - Enabling and disabling • It is poor style to remove components you don’t want the user to be able to use • “Where did it go? It was here a minute ago!” • Exception – changing to new interface • It’s better to enable and disable controls • Disabled controls appear “grayed out” • The user may still wonder why?, but that’s still less confusing • anyComponent.setEnabled(enabled); • Parameter should be true to enable, false to disable
Applet Read Write Clear Example 1 – an applet with 3 buttons and 2 text fields Step1 – Design the interface Enter text Correct Entry? The JApplet will consist of 2 JPanels – The top one containing labels and text fields The bottom one containing three JButtons The browser will add a title bar when the applet is running
Enter text Correct Entry? Applet Read Write Clear Swing The top Panel will use a GridLayout with 2 rows and 2 columns (with a separation of 10 pixels)
Swing Example 1 Add components to the grid – left to right, top to bottom Construct the top panel – write a method makeJTextPanel( ) //(global) attributes of the class private MyJTextField source = new MyJTextField(25); private MyJTextField target = new MyJTextField(25); private JLabel edit = new JLabel("Enter text"); private JLabel verify = new JLabel("Correct Entry?"); private String inStr = new String(""); //method to construct the top panel private JPanel makeJTextPanel( ) { JPanel theText = new JPanel( ); theText.setLayout(newGridLayout(2,2, 10, 10)); theText.add(edit); theText.add(source); theText.add(verify); theText.add(target); return theText; }
Enter text Correct Entry? Applet Read Write Clear Swing Example 1 Top JPanel Bottom JPanel Construct the bottom Panel – Use FlowLayout (center adjusted)
Create the bottom panel Swing Example 1 Construct the bottom panel – with a method private MyJButton read; private MyJButton write; private MyJButton clear; //build the bottom panel with method makeJButtonPanel( ) private JPanel makeJButtonPanel() { read = new MyJButton ("Read", source); write = new MyJButton("Write", target); clear = new MyJButton("Clear", target); JPanel theButtons = new JPanel( ); theButtons.setLayout(new FlowLayout(FlowLayout.CENTER)); theButtons.add(read); theButtons.add(write); theButtons.add(clear); theButtons.setBackground(Color.blue); return theButtons; } Set its layout and color, and add the buttons to it (left to right)
For heavyweight component like JApplet components must be added to a ContentPane Swing Example 1 Place the panels into the applet in method init( ) public void init( ) { Container cp = getContentPane( ); theButtons = makeJButtonPanel( ); cp.add(BorderLayout.SOUTH, theButtons); theText = makeJTextPanel( ); cp.add(BorderLayout.CENTER, theText); } //add theButtons (a JPanel) to the ContentPane //the default LayoutManager of a JApplet is BorderLayout
JApplet JPanel JLabel MyJTextField MyJButton Swing Example 1 Design of the System A button event will cause a read, write, or clear of a text field. The applet is an aggregate of 2 JPanels 2 ActionListener JPanels contain JLabels and MyJTextField objects OR MyJButtons MyJButton objects interact with MyJTextField objects String response MyJTextField target 2 3 MyJTextField(int size) doButtonAct(MyJButton) MyJButton(String, MyJTextField) actionPerformed(ActionEvent) activates describes
Constructor receives handle to text field Hold handle to target text field Event causes message to be sent to the target to perform a read or write Swing Example 1 class MyJButton class MyJButton extends JButton implements ActionListener { privateMyJTextField target; public MyJButton(String name, MyJTextField targ) { Font buttonFont = new Font ("Times Roman", Font.BOLD, 12); setFont(buttonFont); setText(name); setBackground(Color.cyan); target = targ; addActionListener(this); } public void actionPerformed(ActionEvent e) { target.doButtonAct(this); } }
Swing Example 1 class MyJTextField extends JTextField { private String response = new String( ); public MyJTextField(int size) { super(size); } publicvoiddoButtonAct(MyJButton source) { response = source.getText( ); if (response.equals("Read") ) inStr = super.getText( ); else if (response.equals("Write") ) setText(inStr); else if (response.equals("Clear") ) setText(""); } } A MyJButton object notifies a MyJTextField of a button event and elicits an action
Now some more Classes Lets examine a few classes in more details
Swing And JScrollPane Adding scroll bars to a component such as a JTextArea Just wrap a JTextArea object inside a JScrollPane. JTextArea ta = new JTextArea(10, 25); JScrollPane sp = new JScrollPane(ta); The programmer can control which scrollbars are allowed – vertical, horizontal, both, or neither JScrollPane sp = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Dialogs • A dialog (small accessory window) can be modal or nonmodal • When your code opens a modal dialog, it waits for a result from the dialog before continuing • When your code opens a nonmodal dialog, it does so in a separate thread, and your code just keeps going • Sun supplies a few simple (but useful) modal dialogs for your use • You can create your own dialogs (with JDialog), but they are nonmodal by default
Message dialogs • JOptionPane.showMessageDialog(parentJFrame, "This is a JOptionPane \"message\" dialog."); • Notice that showMessageDialog is a static method of JOptionPane • The “parentJFrame” is typically your main GUI window (but it’s OK to use null if you don’t have a main GUI window)
Confirm dialogs • int yesNo = JOptionPane.showConfirmDialog(parentJFrame, "Is this what you wanted to see?"); • if (yesNo == JOptionPane.YES_OPTION) { ... }
Input dialogs • String userName = JOptionPane.showInputDialog(parentJFrame, "What is your name?")
Object[] options = new String[] {"English", "Chinese", "French", "German" };int option = JOptionPane.showOptionDialog(parentJFrame, "Choose an option:", "Option Dialog", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); // use as default Fourth argument could be JOptionPane.YES_NO_CANCEL_OPTION Fifth argument specifies which icon to use in the dialog; it could be one of ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, or PLAIN_MESSAGE Sixth argument (null above) can specify a custom icon Option dialogs