480 likes | 662 Views
CSE 501N Fall ‘09 18: Java GUI (Swing). 10 November 2009 Nick Leidenfrost. Lecture Outline. Lab 7 questions? Application Programming Interfaces (APIs) Java Graphical User Interface basic concepts Basic classes Layout management Java Components / Controls Labels Buttons Text boxes
E N D
CSE 501NFall ‘0918: Java GUI (Swing) 10 November 2009 Nick Leidenfrost
Lecture Outline • Lab 7 questions? • Application Programming Interfaces (APIs) • Java Graphical User Interface basic concepts • Basic classes • Layout management • Java Components / Controls • Labels • Buttons • Text boxes • Text areas • Others
Application Programming Interface • Most often referred to by its acronym, API • The set of public fields and methods a class makes available to a programmer • A.k.a. a class’s publishedinterface • The API encompasses any interaction that can be made with a module in a program • Simple but important concept • (I will probably* ask you to explain this on the final exam.) • (*and by probably, I mean definitely)
Graphical User Interface • A.k.a. GUI (goo – ee) • Most programs provide a graphical interface for the user to interact with • (duh.) • The benefits of using a GUI are numerous • More logical presentation of data • More intuitive interaction with the user • Without GUIs, we would have no way of displaying silly clip-art • (I can’t stand to see you cry, little orange man)
Java GUI • The Java Library provides two ways of creating Graphical User Interfaces (GUIs) • Abstract Windowing Toolkit (AWT) • Java asks the underlying operating system (OS) to supply the implementation for some graphical elements: buttons, text fields, etc. • Contained in the package java.awt • Swing • Graphical elements are implemented internally, with little dependency on OS support • Provides higher levels of functionality • Looks more standardized across platforms • Contained in the package javax.swing
Java GUI • The history of AWT and Swing can provide some insight when working with the libraries • AWT came first • Many classes which “support” GUIs, but do not themselves have graphical representation are contained in AWT • These classes are used by Swing classes and are not duplicated in Swing • Many Swing classes with graphical representation may seem like duplicates, or mirrors of their respective AWT classes
Java GUI java.awt Component Container Window Frame javax.swing JComponent JWindow JFrame What the ??? Why is there no Swing equivalent!?
Java GUI • JComponent • Extends Component • A basic graphical object, e.g., buttons, labels, images, etc. • Container • Something that you can place other graphical objects on • Is an abstract class. • In the most pure sense of a “Container”, most often we will be using a JPanel • A Container is-a Component • As the name suggests, a container contains additional graphical objects (components) • JWindow • Represents an application window on your desktop • A JWindow is-a JContainer • JFrame • A window with a title bar, and buttons to close, minimize and maximize • A JFrame is-a JWindow • Can put any content inside it Is-A (Generally)
JFrame • To create a GUI which creates a window, simply extend the JFrame class public class MyFrame extends JFrame { public MyFrame() { super(“My First Frame”); } // Other methods }
JContainer • The most common container is the JPanel • Think of it as a flat tray on which you can lay out other components (or containers) • You can add components by using the add method • You may also remove components from the panel public void addToPanel (Component c) { JPanel panel = new JPanel(); panel.add(c); }
JComponent • There are many types of JComponent • For example, a JButton is a JComponent public void addButtonToPanel() { JPanel panel = new JPanel(); JButton button = new JButton(“Click Me”); panel.add(button); }
Representing Choices in the GUI • Radio buttons • JRadioButton • Check boxes • JCheckBox • Combo boxes • JComboBox
Radio Buttons • For a small set of mutually exclusive choices, use radio buttons or a combo box • In a radio button set, only one button can be selected at a time • When a button is selected, previously selected button in set is automatically turned off
Radio Buttons • In previous figure, font sizes are mutually exclusive: JRadioButton smallButton = new JRadioButton("Small"); JRadioButton mediumButton = new JRadioButton("Medium"); JRadioButton largeButton = new JRadioButton("Large"); // Add radio buttons into a ButtonGroup so that // only one button in group is on at any time ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton);
Radio Buttons • Button group does not add buttons to the container for you • It only creates a mutually exclusive relationship between buttons • You still have to add buttons to the container ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton); container.add(smallButton); container.add(mediumButton); container.add(largeButton);
Radio Buttons • isSelected: called to find out if a button is currently selected or not if • To set a default, call setSelected(true) on a radio button in group before making the enclosing frame visible if (largeButton.isSelected()) size = LARGE_SIZE;
Check Boxes • Two states: checked and unchecked • Use one checkbox for a binary choice • (or a boolean choice: yes / no, on / off, true / false) • Use a group of check boxes when one selection does not exclude another • Example: "bold" and "italic" in previous figure
Check Boxes • Construct by giving the name in the constructor: • Don't place into a button group JCheckBox italicCheckBox = new JCheckBox("Italic");
Combo Boxes • For a large set of choices, use a combo box • Uses less space than radio buttons • "Combo": combination of a list and a text field • The text field displays the name of the current selection
Combo Boxes Figure 4:An Open Combo Box
Combo Boxes • If combo box is editable, user can type own selection • Specified with setEditable method • Add strings with addItem method: JComboBox fontCombo = new JComboBox(); fontCombo.addItem("Serif"); fontCombo.addItem("Sans Serif"); . . .
Combo Boxes • Get user selection with getSelectedItem (return type is Object) • Select an item programmatically with setSelectedItem String selectedString = (String) fontCombo.getSelectedItem();
Borders • Place a border around a panel to group its contents visually • EtchedBorder: three-dimensional etched effect • Can add a border to any component, but most commonly to panels: Jpanel panel = new JPanel ();panel.setBOrder(new EtchedBorder ()); Continued…
Borders • TitledBorder: a border with a title panel.setBorder(new TitledBorder(new EtchedBorder(), “Font Style”));
Menu Sub Menu (really just a Menu inside a Menu) Menu Bar New Menu Items Menu Items Close Open Open Recent Menus • A frame can contain a menu bar • The menu bar contains menus • A menu contains submenus and menu items File
JMenu JMenu JMenuBar File New JMenuItem JMenuItem Close Open Open Recent Menus • Create Menu Bars with the JMenuBar class • Create Menus with JMenu class • Create Menu Items with JMenuItem class
Text Areas • Use a JTextArea to show multiple lines of text • You can specify the number of rows and columns: • setText: to set the text of a text field or text area • append: to add text to the end of a text area final int ROWS = 10; final int COLUMNS = 30; JTextArea textArea = new JTextArea(ROWS, COLUMNS);
Text Areas • Use newline characters to separate lines: • To use for display purposes only: • (do not let users edit the Text Area) textArea.append(account.getBalance() + "\n"); textArea.setEditable(false);// program can call setText and append to change it
Scrolling with JScrollPane To add scroll bars to a text area, or any component: JTextArea textArea = new JTextArea(ROWS, COLUMNS); JScrollPane scrollPane = new JScrollPane(textArea);
My First GUI Submit Text Field • Input a single line of text • Can set it to be editable or not • Can obtain the text using the getText() method
What else? • Swing offers many more classes and options to tweak the look and feel • Explore using APIs in Javadoc online • Great tutorials • Anything in the javax.swing package is fair game
Layout Management • By default, we have had very limited control over how components are positioned • When we used a panel, it arranged the components from the left to the right
Layout Management • Each Container has a layout manager that directs the arrangement of its components • Three useful layout managers: • BorderLayout • GridLayout • GridBagLayout • Layout managers are part of the java.awt package • (although they affect display, they themselves have no graphical representation)
Layout Management • By default, JPanel places components from left to right and starts a new row when needed • Panel layout carried out by FlowLayout layout manager • Can set other layout managers panel.setLayout(new BorderLayout());
Border Layout • Border layout groups container into five areas: center, north, west, south and east
Border Layout • Default layout manager for a frame (technically, the frame's content pane) • When adding a component, specify the position like this: • Expands each component to fill the entire allotted area • If that is not desirable, place each component inside a panel panel.add(component, BorderLayout.NORTH);
Grid Layout • Arranges components in a grid with a fixed number of rows and columns • Resizes each component so that they all have same size • Expands each component to fill the entire allotted area
Grid Layout • Add the components, row by row, left to right: JPanel numberPanel = new JPanel(); numberPanel.setLayout(new GridLayout(4, 3)); numberPanel.add(button1); numberPanel.add(button2); numberPanel.add(button3); numberPanel.add(button4); . . .
Grid Bag Layout • Tabular arrangement of components • Columns can have different sizes • Components can span multiple columns • Quite complex to use • Will not cover or assign in labs • If you are a masochist, this is the layout manager for you!
Grid Bag Layout • Fortunately, you can create acceptable-looking layouts by nesting panels • Give each panel an appropriate layout manager • Panels don’t have visible borders • Use as many panels as needed to organize components
Example • Expanding the simple GUI • Next time: How do we make the GUI come alive?
Prompting a User for Input • A graphical application can obtain input by displaying a JOptionPane • The showInputDialog method displays a prompt and waits for user input • The showInputDialog method returns the string that the user typed String input = JOptionPane.showInputDialog("Enter x");double x = Double.parseDouble(input);
Colors • Standard colors Color.BLUE, Color.RED, Color.PINK etc. • Specify red, green, blue between 0.0F and 1.0F Colormagenta = newColor(1.0F, 0.0F, 1.0F); // F = float • Specify RGB values between 0 and 255 int Color c = new Color(255, 0, 0);
Conclusion • Questions? • I’ll be in lab now until 6:45