Unit 3
Unit 3
It is part of Sun Microsystems' Java Foundation Classes (JFC) an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit. It has more powerful and flexible components than AWT. In addition to familiar components such as buttons, check box and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees, tables and lists
Swing is a platform-independent, Model-View-Controller GUI framework for Java. Advantage Foundations Extensible Customizable Configurable Loosely-Coupled and MVC
Top-level
windows is called frame in java. The most common way of creating a frame is, using single argument constructor of the JFrame class. import javax.swing.*; public class Swing_Create_Frame{ public static void main(String[] args){ JFrame frame = new JFrame("Frame in Java Swing"); frame.setSize(400, 400); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CL OSE); } }
The most important methods related to positioning a Frame are: The setLocation and setBounds methods for setting the position of the frame The setIconImage method, which tells the windowing system which icon to display in the title bar, task switcher window etc The setTitle method for changing the text in the title bar The setResizable method, which takes a boolean to determine if a frame will be resizeable by the user. setLocation(x, y) setBounds method in Component lets you resize and relocate a component in one step. setBounds(x, y, width, height)
property has a name and a type. The name is obtained by changing the first letter after the get or set to lowercase. Title is a property of the frame, set this property such that the title changes on the users screen private String title; public String getTitle() public void setTitle(String title)
To find out the screen size, use the following steps: 1. Call the static getDefaultToolkit method of the Toolkit class to get the Toolkit object. (The Toolkit class is a dumping ground for a variety of methods that interface with the native windowing system.) 2. Then call the getScreenSize method, which returns the screen size as a Dimension object. Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; position the frame as follows: setSize(screenWidth / 2, screenHeight / 2); setLocationByPlatform(true);
add a component to a frame is: Container contentPane = f rame.getContentPane(); Component c = . . .; contentPane.add(c); Or, simply use the call frame.add(c); To draw on a component, define a class that extends JComponent and override the paintComponent method in that class To make a component onto which draw/write by: class MyComponent extends JComponent { public void paintComponent(Graphics g) { //code for drawing } }
Displaying text is a special kind of drawing. The Graphics class has a drawString method that has the following syntax: g.drawString(text, x, y) paintComponent method will look like this class TestPaintComponent extends JComponent { public void paintComponent(Graphics g) { g.drawString("Welcome to Java Swings Tutorial!!!", MESSAGE_X, MESSAGE_Y); } public static final int MESSAGE_X = 75; public static final int MESSAGE_Y = 100; }
Drawing 2 Dimensional Shapes Graphics2D class is a subclass of the Graphics class. Methods such as paintComponent automatically receive an object of the Graphics2D class. public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; ... } there are classes to represent lines, rectangles, and ellipses: Line2D Rectangle2D Ellipse2D
create
an object of a class that implements the Shape interface and then call the draw method of the Graphics2D class. Rectangle2D rect = . . .; g2.draw(rect); The Rectangle2D class is an abstract class with two concrete subclasses Rectangle2D.Float Rectangle2D.Double Rectangle2D.Float floatRect = new Rectangle2D.Float(10.0F, 25.0F, 22.5F, 20.0F);
Rectangle2D.Double doubleRect = new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0); Parameters denote the top-left corner, width, and height of the rectangle
Point2D class with subclasses Point2D.Float and Point2D.Double Point2D p = new Point2D.Double(10, 20);
Drawing Ellipses
The
classes Rectangle2D and Ellipse2D both inherit from the common superclass RectangularShape.
Specify the following to construct Rectangle2D and Ellipse2D objects The x- and y-coordinates of the top-left corner; and The width and height. Ellipse2D e = new Ellipse2D.Double(150, 200, 100, 50);
Drawing Lines
To construct a line, the start and end points Line2D line = new Line2D.Double(start, end); or Line2D line = new Line2D.Double(startX, startY, endX, endY);
The
setPaint method of the Graphics2D class is used to select a color. For example: g2.setPaint(Color.RED); g2.drawString("Caution!", 100, 100); Fill the interiors of closed shapes (such as rectangles or ellipses) with a color calling fill, instead of draw: Rectangle2D rect = . . .; g2.setPaint(Color.RED); g2.fill(rect); // fills the rect object with red color The java.awt.Color class offers predefined constants for the following 13 standard colors: BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW invoke the Color constructor like below g2.setPaint(new Color(0, 128, 128)); MyComponent p = new MyComponent(); p.setBackground(Color.MAGENTA);
To
find out the fonts that are available on a particular computer, call the getAvailableFontFamilyNames method of the GraphicsEnvironment class.
To
obtain an instance of the GraphicsEnvironment class that describes the graphics environment of the users system, use the static getLocalGraphicsEnvironment method. import java.awt.*; public class ListAllFontsInMyPC { public static void main(String[] args) { String[] fontNames = GraphicsEnvironment .getLocalGraphicsEnvironment() . getAvailableFontFamilyNames(); for (String fontName : fontNames) System.out.println(fontName); } }
To
draw characters in a font, first create an object of the class Font. Then specify the font face name, the font style, and the point size. Font sansbold14 = new Font("SansSerif", Font.BOLD, 14); The third argument indicate the size of a font. There are 72 points per inch. Specify the style Font.PLAIN Font.BOLD Font.ITALIC Font.BOLD + Font.ITALIC To read font files, an input stream for the font is needed typically from a file or URL. call the static Font.createFont method URL url = new URL("http://www.fonts.com/Wingbats.ttf"); InputStream in = url.openStream(); Font f1 = Font.createFont(Font.TRUETYPE_FONT, in);
Using a Font
The width and height of the string in pixels depends on three factors: The font used (in our case, sans serif, bold, 14 point); The string (in our case, Hey Buddy!!!); and The device on which the font is drawn (in our case, the users screen)
Obtain string width, height, and ascent as follows: double stringWidth = bounds.getWidth(); double stringHeight = bounds.getHeight(); double ascent = -bounds.getY();
If
the image is stored in a local file: String filename = "..."; Image image = ImageIO.read(new File(filename)); Display the image with the drawImage method of the Graphics class. public void paintComponent(Graphics g) { ... g.drawImage(image, x, y, null); } To tile an image across a components, first draw one copy of the image in the top-left corner and then use the copyArea call to copy it into the entire window using the code below: for (int i = 0; i * imageWidth <= getWidth(); i++) for (int j = 0; j * imageHeight <= getHeight(); j++) if (i + j > 0) g.copyArea(0, 0, imageWidth, imageHeight, i * imageWidth, j * imageHeight);
All
event objects ultimately derive from the class java.util.EventObject. there are subclasses for each event type, such as ActionEvent and WindowEvent.
Events
are handled in AWT: A listener object is an instance of a class that implements a special interface called a listener interface. An event source is an object that can register listener objects and send them event objects. The event source sends out event objects to all registered listeners when that event occurs. The listener objects will then use the information in the event object to determine their reaction to the event Each button requires 1.Construct the button with a label string. 2. Add the button to the panel. 3. Construct an action listener with the appropriate color. 4. Add that action listener
To
specify a listener to a component, say a Button. ActionListener listener = . . .; JButton button = new JButton("Ok"); button.addActionListener(listener); the listener class must have a method called actionPerformed that receives an ActionEvent object as a parameter class MyListener implements ActionListener { ... public void actionPerformed(ActionEvent event) { // code to handle button click goes here ... } }
Designate
any object of a class that implements the ActionListener interface as a button listener, add an actionPerformed method to an existing class and turn the ButtonPanel into an action listener by class ButtonPanel extends Jpanel implements ActionListener { ... public void actionPerformed(ActionEvent event) { // set background color ... } } The actionPerformed method can then check which of the buttons was the source: if (source == yellowButton) . . . else if (source == blueButton) . . . else if (source == redButton ) . . .
adapter
class that implements all the methods in the interface but does nothing with them. For window adapter, extend the WindowAdapter class, inherit six of the do-nothing methods, and override the windowClosing method: class Terminator extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } Register an object of type Terminator as the event listener: WindowListener listener = new Terminator(); frame.addWindowListener(listener);
A window listener
An
action is an object that encapsulates the following A description of the command Parameters that are necessary to carry out the command The Action interface has the following methods void actionPerformed(ActionEvent event) void setEnabled(boolean b), boolean isEnabled() void putValue(String key, Object value), Object getValue(String key) Example: storing action names and icons into an action object: action.putValue(Action.NAME, "Blue"); action.putValue(Action.SMALL_ICON, new ImageIcon("blue-ball.gif"));
When
the user clicks a mouse button, three listener methods are called: mousePressed when the mouse is first pressed, mouseReleased when the mouse is released, And, finally, mouseClicked. Handler for the control + shift + triple click command public void mouseClicked(MouseEvent event) { int x = event.getX(); int y = event.getY(); int clickCount = event.getClickCount(); if (event.isShiftDown() && event.isControlDown() && clickCount >= 3) { Graphics g = getGraphics(); g.drawString("Yikes", x, y); g.dispose(); } }
Constant DEFAULT_CURSOR
CROSSHAIR_CURSOR
HAND_CURSOR The mouseMoved method of the MouseMotionListener public void mouseMoved(MouseEvent event) { if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor()); else setCursor(Cursor.getPredefinedCursor (Cursor.CROSSHAIR_CURSOR)); }
If
the user presses a mouse button while the mouse is in motion, mouseDragged calls are generated public void mouseDragged(MouseEvent event) { if (current >= 0) { int x = event.getX(); int y = event.getY(); current.setFrame( x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH); repaint(); } } There are two other mouse event methods: mouseEntered and mouseExited
list of those AWT event types that are actually passed to listeners are, ActionEvent ItemEvent AdjustmentEvent KeyEvent ComponentEvent MouseEvent ContainerEvent TextEvent FocusEvent WindowEvent
There
are eleven listener interfaces altogether in the java.awt.event package: ActionListener KeyListener AdjustmentListener MouseListener ComponentListener MouseMotionListener ContainerListener TextListener FocusListener WindowListener ItemListener
semantic event is one that expresses what the user is doing, such as clicking that button; hence, an ActionEvent is a semantic event. Low-level events are those events that make this possible like a keystroke, which happens if the user selects the button with the tab key and then activates it with the space bar There are four semantic event classes in the java.awt.event package ActionEvent AdjustmentEvent ItemEvent TextEvent There are six low-level event classes: ComponentEvent (the component was resized, moved, shown, or hidden); also is the base class for all low-level events KeyEvent (a key was pressed or released) MouseEvent (the mouse button was pressed, released, moved, or dragged) FocusEvent (a component got focus, or lost focus) WindowEvent (the window was activated, deactivated, iconified, deiconified, or closed) ContainerEvent (a component has been added or removed)
INTRODUCTION TO SWING
The Model-View-Controller Design Pattern Design Patterns Design patterns are a method for presenting the expertise in a structured way. Example: Window Place the comfortable places in the room where one want to sitare away from the windows, there is no way of overcoming this conflict Therefore: In every room where one spend any length of time during the day, make at least one window into a window place.
Model-View-Controller Pattern
Every component such as a button, a check box, a text field, has three characteristics: Its contents, such as the state of a button (pushed in or not), or the text in a text field; Its visual appearance (color, size, and so on); Its behavior (reaction to events). Implement three separate classes: The model, which stores the contents; The view, which displays the contents; The controller, which handles user input.
Advantage
A model can have multiple views
The
Swing library contains a single class, called DefaultButtonModel, that implements ButtonModel The accessor methods of the ButtonModel interface getActionCommand() getMnemonic() isArmed() isEnabled() isPressed() isRollover() isSelected() Each JButton object stores a button model object, which can be retrieved. JButton button = new JButton("Blue"); ButtonModel model = button.getModel();
To
align them to the left or to the right of the container setLayout(new FlowLayout(FlowLayout.LEFT));
the layout manager for a container setLayout(LayoutManager m) a new FlowLayout with the specified alignment FlowLayout(int align) a new FlowLayout with the specified alignment FlowLayout(int align, int hgap, int vgap)
Set
Construct
Construct
Border Layout
Code fragment that adds a panel containing three buttons in the south end of a container. Container contentPane = getContentPane(); JPanel panel = new JPanel(); panel.add(yellowButton); panel.add(blueButton); panel.add(redButton); contentPane.add(panel, BorderLayout.SOUTH);
Grid Layout
Specify how many rows and columns are needed by panel.setLayout(new GridLayout(5, 4));
Specify the vertical and horizontal gaps by panel.setLayout(new GridLayout(5, 4, 3, 3)); Add the components panel.add(new JButton("1")); panel.add(new JButton("2"));
Text Input
Two components are used to get text input: text fields and text areas. The classes are called JTextField for single-line input and JTextArea for multiple lines of text. Both of these classes inherit from a class called JTextComponent change the text of a text component by void setText(String t) where t- new string Return the text contained in a text component by String getText()
Determine whether the user can edit the contents of the JTextComponent by void setEditable(boolean b)
Text Fields
Add a text field to a window is to add it to a panel or other container using the code JPanel panel = new JPanel(); JTextField textField = new JTextField("Default input", 20); panel.add(textField ); To make a blank text field JTextField textField = new JTextField(20); Change the contents of the text field textField.setText("Hello!");
To
label a component, 1. Construct a JLabel component with the correct text. 2. Place it close enough to the component you want to identify so that the user can see that the label identifies the correct component The JLabel class is one of several Swing classes that implements the interface Specify a left-aligned label either as: JLabel label = new JLabel("Text", SwingConstants.LEFT); or JLabel label = new JLabel("Text", JLabel.LEFT); The setText and setIcon methods are used to set the text and icon of the label at run time Constructs a label with both text and an icon, icon is to the left of the text JLabel(String text, Icon icon, int align)
Password
fields are a special kind of text field; the characters that the user entered are not actually displayed, each typed character is represented by an echo character,an asterisk (*). The Swing set supplies a JPasswordField class that implements such a text field. Construct a new password field by JPasswordField(String text, int columns) Set the echo character for the password field by void setEchoChar(char echo) Return the text contained in the password field by char[] getPassword()
The
JTextArea component is used to collect user input that is more than one line long. Specify the number of rows and columns for the text area by: textArea = new JTextArea(8, 40); // 8 lines of 40 columns each contentPane.add(textArea);
Use
the setColumns method to change the number of columns, and the setRows method to change the number of rows. If there is more text than the text area can display, then the remaining text is simply clipped. Avoid clipping long lines by turning on line-wrapping by: textArea.setLineWrap(true); // long lines are wrapped
To
have scroll bars in text area, insert the text area inside a scroll pane, then, insert the scroll pane inside the content pane. textArea = new JTextArea(8, 40); JScrollPane scrollPane = new JScrollPane(textArea); contentPane.add(scrollPane, BorderLayout.CENTER);
The
scroll pane manages the view of the text area, Scroll bars automatically appear if there is more text than the text area can display
Choice components
check boxes, radio buttons, lists of choices, and sliders Check Boxes To collect just a yes or no input, use a check box component
Give the label text in the constructor by bold = new JCheckBox("Bold"); Use the setSelected method to turn a check box on or off by bold.setSelected(true); When the user clicks on a check box, this triggers an action event ActionListener listener = . . . bold.addActionListener(listener); italic.addActionListener(listener);
Radio Buttons
Radio button group allows to check only one of several boxes where another box is checked, the previous box is automatically unchecked
ButtonGroup group = new ButtonGroup(); JRadioButton smallButton= new JRadioButton("Small", false); group.add(smallButton); JRadioButton mediumButton= new JRadioButton("Medium", true); group.add(mediumButton); ...
Combo Boxes
When the user clicks on the component, a list of choices drops down, and the user can then select one of them.
If the drop-down list box is set to be editable using setEditable method. The JComboBox class provides a combo box component. Add the choice items with the addItem method by faceCombo = new JComboBox(); faceCombo.setEditable(true); faceCombo.addItem("Serif"); faceCombo.addItem("SansSerif");
Sliders
Sliders offer a choice from a continuum of values, for example, any number between 1 and 100. Constructing a slider is as follows: JSlider slider = new JSlider(min, max, initialValue); By default the minimum, maximum, and initial values are initialized with 0, 100, and 50. The slider to be vertical, then use JSlider slider = new JSlider(SwingConstants.VERTICAL, min, max, initialValue);
Menus
A menu bar on top of the window contains the names of the pull-down menus. Clicking on a name opens the menu containing menu items and submenus
Create a menu bar by JMenuBar menuBar = new JMenuBar(); Add menubar in a frame with the setJMenuBar method by frame.setJMenuBar(menuBar); For each menu, create a menu object by: JMenu editMenu = new JMenu("Edit");
Add
the top-level menus to the menu bar by: menuBar.addMenu(editMenu); Add menu items, separators, and submenus to the menu object by: JMenuItem pasteItem = new JMenuItem("Paste"); editMenu.add(pasteItem); editMenu.addSeparator(); JMenu optionsMenu = . . .; // a submenu editMenu.add(optionsMenu); When the user selects a menu, an action event is triggered ActionListener listener = . . .; pasteItem.addActionListener(listener); Add the action to the menu by: JMenuItem exitItem = fileMenu.add(exitAction);
Check Box and Radio Button Menu Items Construct the check box menu item with the given label by JCheckBoxMenuItem(String label) Construct the check box menu item with the given label and the given initial state(true is checked) JCheckBoxMenuItem(String label, boolean state)
Constructs the radio button menu item with the given label and the given initial state JRadioButtonMenuItem(String label, boolean state)
Pop-up Menus
A pop-up menu is a menu that is not attached to a menu bar but that floats somewhere.
Create a pop-up menu by JPopupMenu popup = new JPopupMenu(); Add menu items by JMenuItem item = new JMenuItem("Cut"); item.addActionListener(listener); popup.add(item);
The keyboard mnemonic is used to select a submenu or menu item from the currently open menu which is displayed automatically in the menu, by underlining the mnemonic letter
Accelerators are keyboard shortcuts that let you select menu items without ever opening a menu.
Attach the accelerator ctrl+o to the openItem menu item by openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.V K_O, InputEvent.CTRL_MASK));
To enable or disable a menu item, use the setEnabled method: saveItem.setEnabled(false); The javax.swing.event package defines a MenuListener interface with three methods: void menuSelected(MenuEvent evt) void menuDeselected(MenuEvent evt) void menuCanceled(MenuEvent evt)
Tool Bars
A tool bar is a button bar that gives quick access to the most commonly used commands in a Program.
Add the tool bar to the container by contentPane.add(bar, BorderLayout.NORTH); Specify a title for the toolbar that appears when the toolbar is undocked by: bar = new JToolBar(titleString); Toolbars are initially horizontal, to have a toolbar start out as vertical, use bar = new JToolBar(SwingConstants.VERTICAL) Add tool tips to any JComponent exitButton.setToolTipText("Exit");
Dialog Boxes
Dialog boxes are used to pop up to give information to or get information from the user. Types: modal dialog boxes modeless dialog boxes
Option Dialogs The JOptionPane has four static methods showMessageDialog showConfirmDialog showOptionDialog
showInputDialog
The dialog has the following components: An icon; A message; One or more option buttons.
There are five message types: ERROR_MESSAGE INFORMATION_MESSAGE WARNING_MESSAGE QUESTION_MESSAGE PLAIN_MESSAGE - no icon