Introduction to GUI Programming in Java Elements of GUI Programming Components Visual objects that appear on the screen Layouts Control over the positioning of components within a container Events Responses to user actions
Graphics Lines, shapes, colors, fonts, etc. All are supported in Java library packages. Components/widgets Two categories of Java Component classes: AWT Abstract Windows Toolkit (java.awt package) The older version of the components Rely on peer architecturedrawing done by the OS platform on which the application/applet is running Platform-dependent look. Considered to be heavy-weight
Swing (javax.swing package) Newer version of the components No peer architecturecomponents draw themselves Most are considered to be lightweight Swing VS. AWT Never mix Swing and AWT components If you know AWT, put J in front of everything AWT: Button Swing: JButton Swing does all that AWT does, but better.
Using a GUI Component 1. 2. 3. 4. 5. Create it Configure it Add children (if container) Add to parent (if not JFrame) Listen to it
order important Containers Descendents of the java.awt.Container class Components that can contain other components. Use a layout manager to position and size the components contained in them. Components are added to a container using one of the various forms of its add method Depending on which layout manager is used by the container
Container Hierarchy Top-level container: place for other Swing components to paint themselves e.g., JFrame, JDialog, Japplet Intermediate container: simplify positioning of atomic components e.g., JPanel, JSplitPane, JTabbedPane Atomic components: self-sufficient components that present information to and get input from the user e.g., JButton, JLabel, JComboBox, JTextField, JTable
Hierarchy Sample Frame Panel Panel Panel Panel Label checkbox
RadioButton Text Field List Scrollbar Table Text Area ComboBox
Button Button Button Panel Top Level Containers Every program that presents a Swing GUI contains at least one top-level container. A Top level container provides the support that Swing
components need to perform their painting and eventhandling. Swing provides three top-level containers: JFrame (Main window) JDialog (Secondary window) JApplet (An applet display area within a browser window) JFrame A frame implemented as an instance of the JFrame class, is a window that has decorations such as a border, a title and buttons for closing and iconifying the window. The decorations on a frame are platform dependent. Applications with a GUI typically use at least one frame.
Some Jframe methods JFrame() - Constructs a new frame that is initially invisible. JFrame(String title) setSize(width, height); pack(); setLocation(x, y); setVisible(true); setResizable(false); getContentPane(); Content Pane When a frame is created, the content pane is created
with it To add a component to the content pane (and thus to the frame), use: frameName.getContentPane().add(component name); where frameName is the name of the frame Example 1 import javax.swing.*; public class HelloWorldSwing { public static void main(String[] args) { JFrame frame = new JFrame("HelloWorldSwing"); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label);
Title frame.setVisible(true); } } JFrame JLabel This gray area is the content pane of this frame. Example 2
In this example a custom frame is created import javax.swing.*; public class HelloWorldFrame extends JFrame { public HelloWorldFrame() { super(HelloWorldSwing); JLabel label = new JLabel("Hello World"); getContentPane().add(label); setVisible(true); } public static void main(String[] args) {
HelloWorldFrame frame = new HelloWorldFrame(); } } JComponents (also called widgets) JComponent is the base class for all Swing components except top-level containers. JLabel, JButton, JList, JPanel, JTable, ... To use a component that inherits from JComponent, it must be placed in a top-level container.
JPanels/Panes The terms pane and panel are used interchangeably in Java Intermediate Level Containers. Panes hold a windows GUI components Every frame has at least one pane, the default Content Pane Useful for layout If you want to group certain GUI components together, put them inside a pane, then add that pane to the frame Needed to add components to the frame Nothing can be added directly to the frame; instead, everything,
including other panes, is added to the frames content pane JPanel methods JPanel() - Creates a new JPanel with a double buffer and a flow layout. JPanel(boolean isDoubleBuffered) - Creates a new JPanel with FlowLayout and the specified buffering strategy. JPanel(LayoutManager layout) - Create a new buffered JPanel with the specified layout manager. JPanel(LayoutManager layout, boolean isDoubleBuffered) Creates a new JPanel with the specified layout manager and buffering strategy. JLabel
A display area for a short text string or an image, or both. A label does not react to input events. Methods: JLabel() - Creates a JLabel instance with no image and with an empty string for the title. JLabel(String text) - Creates a JLabel instance with the specified text. JLabel(String text, alignment) Alignemnt is eigher JLabel.LEFT, JLabel.CENTER, JLabel.RIGHT JLabel
JButton Java class that allows you to define a button Multiple constructors allow you to initialize a button with a predefined label and/or a predefined icon Although the buttons action can be defined in the constructor, defining a buttons action can take many lines of code and should be done separately JButton methods JButton() - Creates a button. JButton(String text) - Creates a button with text. JTextField A Java text field is essentially the same as a text area,
only limited to one line Very similar set of methods JPasswordField is the same as JTextField, only the contents are hidden Different constructors allow you to predefine the number of columns and/or the default text JLabel JTextField JTextField methods JTextField() - Constructs a new TextField.
JTextField(String text) - Constructs a new TextField initialized with the specified text. JTextField(String text, int columns) - Constructs a new TextField initialized with the specified text and columns. getText() - Return the text of this field as a string object void setHorizontalAlignment(int alignment)
JTextField.LEFT JTextField.CENTER JTextField.RIGHT JTextField.LEADING JTextField.TRAILING JTextAreas A text area is just a white space of variable size that can hold text If text goes out of the areas bounds, it will exist but some of it will not be seen Wrap the text area in a scrollable pane
JTextArea with Scroll Bars JTextarea Methods JTextArea() - Constructs a new TextArea. JTextArea(int rows, int columns) - Constructs a new empty TextArea with the specified number of rows and columns. JTextArea(String text) - Constructs a new TextArea with the specified text displayed. JTextArea(String text, int rows, int columns) - Constructs a new TextArea with the specified text and number of rows and columns. textarea.setText(String);
textarea.getText(String); textarea.append(String); textarea.setEditable(boolean); JScrollPane JScrollPane basically consists of JScrollBars, a JViewport, a column header and a row header. Methods JTextArea textArea = new JTextArea("Type here",5, 20); JScrollPane scrollPane = new JScrollPane(textArea); frame.setContentPane(scrollPane); JList
A simple GUI object design to hold lists of objects and allow users to make selections from the list Can be created from a ListModel, a Vector, or an array (all essentially lists themselves) Jlist methods JList() - Constructs a JList with an empty model. JList(Object[] listData) - Constructs a JList that displays the elements in the specified array. JComboBox Drop-down box Can be: User-editable:
allows user to type in a value in the field similar to a JTextField list.setEditable( true ); User-un-editable: user must select an entry from the drop-down list default JTable Usually created from a DefaultTableModel Can also be created from an array of arrays or a Vector of Vectors, or can have no initial data
Create a DefaultTableModel, then initialize a table from the DefaultTableModel Some methods Jtable() JTable(int numRows, int numColumns) JTable RadioButton
Come in groups only 1 selected per group Make radiobuttons Make group Add radiobuttons to group ActionListener JCheckBox A check box can be toggled checked or unchecked Can have one or more checkboxes selected (as opposed to radio buttons)
How to Layout Widgets? Two approaches Manually specify absolute positions Use layout managers Manually specify absolute positions Use component methods such as: public void setLocation(Point p) public void setSize(int width, int height) Layout Managers
Layout managers are AWT software components which have the ability to lay out widgets/components by their relative positions. Associated with containers. Automate the layout of elements When elements are added to the container When the window is resized automatically adjust the positions and sizes of the elements. Hierarchy of Layout Managers Using Layout Managers Method
setLayout(lm) Description Set lm as the layout manager add(comp) Add a component add(comp, cst) Add a component with constraint
setLayout(new FlowLayout()); add(new JButton(Increment")); add(new JButton(Decrement)); Layout Management When using the add method to put a component in a container, the containers layout manager must be taken into account. Relative position (BorderLayout) panel.add(component, BorderLayout.CENTER); Order of addition (BoxLayout, GridLayout, ...) panel.add(component);
FlowLayout Places components from left to right, starting new rows if necessary. Default LayoutManager of JPanel Left to right, Top to bottom FlowLayout example import javax.swing.*; import java.awt.*; public class flow { public static void main(String[] args) {
JFrame frm = new JFrame("Flow Layout Test"); Container contentPane = frm.getContentPane(); contentPane.setLayout(new FlowLayout()); for (int i=0; i<=9; ++i) contentPane.add(new JButton(""+i)); frm.pack(); frm.setSize(318,220); //frm.setResizable(false); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } }
BorderLayout Has five areas available to hold components north, south, east, west and center All extra space is placed in the center area Only the center area is affected when the container is resized. Default layout manager of content panes. n w c s
e BorderLayout example import javax.swing.*; import java.awt.*; public class border { public static void main(String[] args) { JFrame frm = new JFrame(Border Latout Test"); Container contentPane = frm.getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(new JButton(" 0 "), BorderLayout.NORTH); contentPane.add(new JButton(" 1 "), BorderLayout.SOUTH);
contentPane.add(new JButton(" 2 "), BorderLayout.EAST); contentPane.add(new JButton(" 3 "), BorderLayout.WEST); contentPane.add(new JButton(" 4 "), BorderLayout.CENTER); frm.pack(); frm.setSize(318,220); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } } BoxLayout The BoxLayout class puts components in a
single row or column. It respects the components' requested maximum sizes, and also lets you align components. GridLayout Places components in a requested number of rows and columns. Components are placed left-to-right and top-tobottom. Forces all components to be the same size as wide as the widest component's preferred width
as high as the highest components preferred height GridLayout example import javax.swing.*; import java.awt.*; public class grid { public static void main(String[] args) { JFrame frm = new JFrame(Grid Layout Test"); Container contentPane = frm.getContentPane(); contentPane.setLayout(new GridLayout(3, 4)); for (int i=0; i<=9; ++i) contentPane.add(new JButton(""+i)); frm.pack();
frm.setSize(318,220); //frm.setResizable(false); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } } CardLayout Components are organized as a deck of cards. Can only be shown one at a time. Methods: void add(String name, Component comp) void first(Container parent)
void show(Container parent, String name) One at a time CardLayout example public class card implements ActionListener { static CardLayout contentPaneLayout; static JButton B1 = new JButton("To Card 2"); static JButton B2 = new JButton("To Card 1"); static JPanel contentPane; public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source==B1) contentPaneLayout.show(contentPane, "Card 2");
if (source==B2) contentPaneLayout.show(contentPane, "Card 1"); } public static void main(String[] args) { JFrame frm = new JFrame("Card Layout Test"); contentPane = (JPanel) frm.getContentPane(); contentPane.setLayout(contentPaneLayout=new CardLayout()); JPanel card1 = new JPanel(); JPanel card2 = new JPanel(); card1.add(new Label("This is card 1")); card2.add(new JTextField("This is Crad 2", 20)); card1.add(B1); card2.add(B2); contentPane.add("Card 1", card1);
contentPane.add("Card 2", card2) ; contentPaneLayout. show(contentPane, "Card 1"); ActionListener AL = new card() ; B1.addActionListener(AL); B2.addActionListener(AL); frm.pack(); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } }