Serious Java
Serious Java
You can compile and run this program but it does not do anything useful. It shows an empty window with the title "My Empty Frame". A top-level window is a "frame". The AWT library has a peer-based class called Frame. In Swing, this is called JFrame. Indeed, most of the AWT components (Button, Panel, etc) has corresponding Swing counterparts named by prepending a "J" (JButton, JPanel, etc). JFrame is
one of the few Swing components that are not drawn on a canvas. A JFrame is a "container" meaning it can contain other components such as bottons and text fields. Question: what is the relation between f.show() and f.setVisible(true)? Ans: equivalent.
But it is tedious to write a class "Terminator" to implement WindowListener when most of these 7 methods turn out to be null. So AWT provides a default implementation called WindowAdapter(found in java.awt.event.*) where all these 7 methods are null! But you can just extend this class and write any non-null methods to override the default:
class Terminator extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } }
} ); }
public static void main(String[] args) { JFrame f = new EmptyFrame1(); f.show(); } //main } //class EmptyFrame1
Note that we did not declare the terminator class; instead we use an anonymous class:new WindowAdapter() { ... } . Remark: sometimes, you may also need to call dispose() before System.exit(0), to return any system resources. But dispose alone without System.exit(0) is not enough. [Previous Section] [Next Section]
Then add various components to it. In the present example, we add a JPanel:
contentPane.add( new MyPanel());
To use the font, call the setFont() method in the graphics object g: g.setFont(helvb14);You can also specify font styles such asFont.BOLD + Font.ITALIC. Use getAvailableFontFamilyNames of GraphicsEnvironment class to determine the fonts you can use. Instead of Font names, AWT defines 5 "logical font names":
which are always available. These concepts are illustrated below in our elaboratedpaintComponent method. The goal is ostensibly to print "Hello" in bold and "World!" in bold-italic fonts. To do this, we need to get the FontMetrics object which has methods to measure the length and height of a string, say.
/************************************************************* * @file: TextPanel.java * @source: adapted from Horstmann and Cornell, Core Java * @history: Visualization Course, Spring 2003, Chee Yap *************************************************************/ import java.awt.*; import java.awt.event.*; import javax.swing.*; /************************************************************* * TextPanel Class (with main method) *************************************************************/ class TextPanel extends JPanel { // override the paintComponent method // THE MAIN DEMO OF THIS EXAMPLE: public void paintComponent(Graphics g) { super.paintComponent(g); Font f = new Font("SansSerif", Font.BOLD, 14); Font fi = new Font("SansSerif", Font.BOLD + Font.ITALIC, 14); FontMetrics fm = g.getFontMetrics(f); FontMetrics fim = g.getFontMetrics(fi); int cx = 75; int cy = 100; g.setFont(f); g.drawString("Hello, ", cx, cy); cx += fm.stringWidth("Hello, "); g.setFont(fi); g.drawString("World!", cx, cy); } //paintComponent //============================================= ///////////// main //////////////////////////// public static void main(String[] args) { JFrame f = new MyFrame("My Hello World Frame"); f.show(); } //main } //class TextPanel /************************************************************* MyFrame Class *************************************************************/ class MyFrame extends JFrame { public MyFrame(String s) { // Frame Parameters
setTitle(s); setSize(300,200); // default size is 0,0 setLocation(10,200); // default is 0,0 (top left corner) // Window Listeners addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } //windowClosing }); //addWindowLister // Add Panels Container contentPane = getContentPane(); contentPane.add(new TextPanel()); } //constructor MyFrame } //class MyFrame
NOTE: The java.awt.FontMetrics.* class also has methods to get other properties of the font: its ascent, descent, leading, height, etc. [Previous Section] [Next Section]
(1) Implement the listener interface using ANY reasonable class. In our example, the class will be an extension of JPanel. To implement the ActionListener, you need to supply the method actionPerformed(ActionEvent) (the only method of this interface). The class for implementing Actionlistener here is "MyPanel":
public class MyPanel extends JPanel implements ActionListener { public void actionPerformed(ActionEvent e){ // reaction to button click goes here ... } // actionPerformed } // class MyPanel
What is the action "..." above? This is explained below. (2) Create a listener object:
Listener lis = new MyPanel();
In our present demo, we will have two buttons (redButton and blueButton) in a panel. When redButton is pressed, the background of the panel changes to Red, and similarly when the blueButton is pressed. Thus, these buttons serve as event detectors. To use buttons, we need to create them:
private JButton redButton; redButton = new JButton("RED"); // "RED" is label on button
Next, you add the buttons to a panel (called ButtonPanel here). We also register the listener object with the buttons - but the listener object will be "this" (i.e., current object)!
class ButtonPanel extends JPanel { // members: private JButton redButton; private JButton blueButton; // constructors: public ButtonPanel() { // create buttons redButton = new JButton("RED"); blueButton = new JButton("BLUE"); // add buttons to current panel add(redButton); // add button to current panel
add(blueButton); // add button to current panel // register the current panel as listener for the buttons redButton.addActionListener(this); blueButton.addActionListener(this); } // ButtonPanel constructor } // ButtonPanel class
We now return the details needed in the ctionPerformed(ActionEvent)" method from the ActionListener interface. First, you need to find out which Button caused this event. There are 2 ways to find out. First, the getSource() method from EventObject can be used:
Color color = getBackground(); // color will be set Object source = e.getSource(); if (source == redButton) color = Color.red else if (source == blueButton) color = Color.blue setBackground(color); repaint(); // when do we need this??
The second method, specific to ActionEvents, is to use the getActionCommand() method, which returns a "command string", which defaults to the button label. Thus,
String com = e.getActionCommand(); if (com.equals("RED")) ...; // "RED" is the label of redButton else if (com.equals("BLUE")) ...;
But the command string need not be the label of the button. That can be independently set:
redButton.setActionCommand("RED ACTION");
The ActionListener interface is also used when (a) when an item is selected from a list box with a double click, (b) when a menu item is selected (c) when an enter key is clicked in the text field (d) when a specific time has elapsed for a "Timer" component. In our present example of the red and blue buttons, the ActionListener interface is implemented by MyPanel for a good reason: the action of changing the background of the panel to red or blue ought to reside with the panel! [Previous Section] [Next Section]
Recall that we already had a brief introduction to this interface, when we extended the "WindowAdapter" class to provide default empty implementations for all but the windowClosing method, which we implement by a call to "System.exit(0)". In Step 2 above, the extension of WindowAdapter was called Terminator. In general, all the AWT listener interfaces with more than one method comes with such an adapter class. Finally, we we create an instance of the Terminator class and register it with the JFrame using the ddWindowListener(WindowListener wl)" method:
class MyFrame extends JFrame { // Constructor: public MyFrame() { addWindowListener(new Terminator()); ... } // MyFrame Constructor ... } // MyFrame Class
where XXXclass is the class name. Inner classes are also extremely useful, because the inner class can automatically get access to all the methods and fields of its parent class. In Component design, you often want a new class to subclass two different classes. But Java does not allow this. You get around this restriction by subclassing a subclass - an inner class is one way of doing this. An example where you want to program the "windowDeactivated", "windowActivated", "windowIconified" and "windowDeiconified" is when your window displays an animation. You would want to stop or start the animations when these events occur. [Previous Section] [Next Section]
| ItemEvent* | TextEvent*
| PaintEvent | WindowEvent*
| MouseEv.*
In this hierarchy, only 10 event classes, those indicated with asterisks (*) are actually passed to listeners. The 10 event classes are classified into 4 emantic" events and 6 "low-level" events. Intuitively, semantic events correspond to what the user intends (e.g., button click), while lowlevel events correspond to physical events. Semantic Events 1) ActionEvent: button click, menu selection, selecting item in list, typing ENTER in text field 2) AdjustmentEvent: the user adjusted a scroll bar. 3) ItemEvent: the use made a selection from a set of checkbox or list items 4) TextEvent: the contents of a text field or area were changed. Low-Level Events 1) ComponentEvent: component is resized, moved, shown, hidden. It is the base class for all low-level events. 2) KeyEvent: a key was pressed or released. 3) MouseEvent: the mouse button was depressed, released, moved, dragged. 4) FocusEvent: a component got focus, lost focus. 5) WindowEvent: window was (de)activated, (de)iconified, or closed. 6) ContainerEvent: a component has been added or removed. Usually, you don't have to worry about this class of event, as these events are (usually) not generated dynamically, but in your program. All low-level events is derived from ComponentEvent. They all have a method "getComponent" (it is similar to the "getSource" method but the result is already cast as a component). There are 11 listener interfaces in java.awt.event:
ActionListener, ContainerListener*, MouseMotionListener*, ItemListener, AdjustmentListener, KeyListener*, TextListener, WindowListener*. ComponentListener* MouseListener* FocusListener*
The listeners with asterisks (*) have a corresponding adaptor class implementing it because they each have more than one method. There is a 1-1 correspondence between listeners and event types, with one exception: MouseEvents are sent to both MouseListeners and MouseMotionListener. The split into two types of listeners for MouseEvents is done for efficiency - so we can ignore an entire class of mouse events (such as mouse motion which can generate frequent events). [Previous Section] [Next Section]
not "focusable" by default. You can make any component "focusable" or not by overriding the sFocusTraversable" method to return TRUE or FALSE. You can use the "requestFocus" method to move the focus to any specific component at run time, or you can use "transferFocus" method to move to the next component. The notion of "next" component can be changed. (C) The FocusListener interface has 2 methods: focusGained and focusLost. Each takes the "FocusEvent" object as parameter. Two useful methods for implementing this interface are "getComponent" and sTemporary". The latter returns TRUE if the focus lost is temporary and will automatically be restored. [Previous Section] [Next Section]
The key code (defined in the KeyEvent class) is one of the following constants:
VK_A VK_B ... VK_Z VK_0 ... VK_9 VK_COMMA VK_PERIOD ... etc
Instead of tracking the key codes in the case of combination strokes, the following methods which returns a Boolean value are useful: "KeyEvent.isShiftDown()", "KeyEvent.isControlDown()", "KeyEvent.isAltDown()" and "KeyEvent.isMetaDown()". To work with keyTyped method, you can call the "getKeyChar" method. The following demo is a tch-A-Sketch" toy where you move a pen up, down, left, right with cursor keys or h, j, k, l. Holding down the SHIFT key at the same time will move the pen by larger increments. [Previous Section] [Next Section]
STEP 2: Instance the Action class STEP 3: Associate the action instance with components STEP 4: Add the components to the windowing system STEP 1: As usual, there is a default implementation of the Action interface, called bstractAction". You can adapt from this class, and only ctionPerformed" method needs to be explicitly programed by you. Usually, you also want to provide a constructor to set the values stored under various keys, and your class will want a member variable "target" to remember the component where the action is to be performed (recall that the Action object need not be the component itself, after our decoupling of vent generator" from vent listener"). Here is an implementation of the action et background color":
class BackgroundColorAction extends AbstractAction { //members: private Component target; // where you want the action done! //constructor: public BackgroundColorAction( String name, Icon i, Color c, Component comp) { putValue(Action.NAME, name); putValue(Action.SMALL\_ICON, i); putValue("Color", c); target = comp; } // constructor //methods: public void actionPerformed(ActionEvent e) { Color c = (Color)getValue("Color"); target.setBackground(c); target.repaint(); }// actionPerformed method }// BackgroundColorAction class
STEP 3: associate the action with components or their instances: The following associates "redAction" with a component instance. The component illustrated here is a JButton instance.
JButton redButton = new JButton("Red"); redButton.addActionListener(redAction);
Alternatively, we associate any given ction" with an entire class of components. For JButtons, we create button class that comes with an action:
class ActionButton extends JButton { public ActionButton(Action a) { setText((String)a.getValue(Action.NAME)); Icon icon = (Icon)a.getValue(Action.SMALL\_ICON); if (icon != null) setIcon(icon) addActionListener(a); }// ActionButton constructor }// ActionButton class
NOTE: If we introduce ctionButtons" then STEPS 2 and 3 should be interchanged! STEP 4: Now add ActionButtons to a menu, then to the menu bar:
// create the menu of ActionButtons: JMenu m = new JMenu("Color"); m.add(redAction); m.add(blueAction); // add menu to menubar JMenuBar mbar = new JMenuBar(); mbar.add(m); setJMenubar(mbar);
A Graphical User Interface (GUI) is a visual paradigm which allows a user to communicate with a program in an intuitive way. Its main features are widgets (aka controls) and event driven activities. Application users expect a graphical interface. The next few tutorials will introduce Java's GUI widgets as well as some layout design considerations. One reference with lots of examples can be found in the Guidebook.Swing Sightings demos Swing in significant applications. Java has two GUI packages, the original Abstract Windows Toolkit (AWT) and the newer Swing. AWT uses the native operating system's window routines so the visual effect is dependent on the run-time system platform. But this is contrary to the concept of having a virtual model. Swing allows three modes: a unified look and feel [the default], the native platform look, or a specific platform's look. Swing is built on the original objects and framework of AWT. Swing components have the prefix J to distinguish them from the original AWT ones (eg JFrame instead of Frame). To include Swing components and methods in your project you must import the java.awt.*, java.awt.event.*, and javax.swing.* packages. Intermediate|Advanced
Containers,Wind Dialog Ba
the pane. The way they are added is controlled by the current layout manager. JPanel defaults to FlowLayout. All other content panes default to BorderLayout. The following is a simple template that creates a JFrame container class using inheritance. The created subclass then adds a JPanel. This custom class will form the basis of many of our GUI examples.
import java.aw t.*; import java.aw t.event.*; import javax.sw ing.*; public class Frame1 extends JFrame { JPanel pane=new JPanel(); Frame1() // the frame constructor method { super("My Simple Frame"); setBounds(100,100,300,100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con=this.getContentPane(); // inherit main frame con.add(pane); // add the panel to frame // customize panel here // pane.add(someWidget); setVisible(true); // display this frame } public static void main(String args[]) {new Frame1();} }
Dialog Boxes
Dialogs are short messages, confirmationsor input prompts for simple string information which appear as popup windows. Dialogs can either be modal (must be dismissed before another window is accessed) or modeless. JOptionPane provides a modal dialog with predefined methods for each type of dialog. Each JOptionPane method has a first parameter that points to a parent (ie. window that it appears in) or null (default to the current window). The second parameter is the message or prompt to be displayed. New instances of JOptionPane are not normally generated. showMessageDialog() has two more optional parameters to set a dialog title and to select the dialog's icon. The dialog has a single 'ok' button for completion and no data is returned by this method.
JOptionPane.showMessageDialog(null,"This is just a message", "Message Dialog",JOptionPane.PLAIN_MESSAGE);
showConfirmDialog() has three more optional parameters to set a dialog title, alter the button display, and select the dialogs icon. By default there are three buttons 'Yes', 'No' and Cancel for dialog completion. The returned value is one of JOptionPane.YES_OPTION, JOptionPane.NO_OPTION or JOptionPane.CANCEL_OPTION.
pressed=JOptionPane.showConfirmBox(null,"Everything aok"); if (pressed==JOptionPane.YES_OPTION) { // do the action for confirmation }
showInputDialog() has two more optional parameters to set a dialog title and to select the dialog's icon. There is both an 'ok' button and a 'cancel' button for dialog completion. Any information typed into the entry box is returned as a string.
The list of icon types that can be displayed (by predefined constant) contains ERROR_MESSAGE, INFORMATION_MESSAGE, PLAIN_MESSAGE, QUESTION_MESSAGE, and WARNING_MESSAGE. JDialog provides a simple unadorned window used to create customized dialog boxes. Customization can include modality and mnemonics (aka hotkeys).
Buttons are created with the JButton() constructor and are used to start operations. They can be deactivated with thesetEnabled(false) method and tested with the isEnabled()method. A useful method is setMnemonic(char) which allows a hot key to be associated with the button. Simple buttons require anActionEvent event listener that reacts to the button click. Many GUIs use an array set of buttons. CheckBgui for a demo of this technique. Toggle buttons are a visual push on - push off mechanism. They are created with the JToggleButton() constructor. The isSelected() method returns the state of the button. In addition to ActionEvent, the ChangeEvent is triggered.
import java.aw t.*; import java.aw t.event.*; import javax.sw ing.*; public class Frame2 extends JFrame { JPanel pane=new JPanel(); JButton pressme=new JButton("Press Me"); Frame2() // the frame constructor { super("JPrompt Demo"); setBounds(100,100,300,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con=this.getContentPane(); // inherit main frame con.add(pane); // JPanel containers default to Flow Layout pressme.setMnemonic('P'); // associate hotkey to button pane.add(pressme); pressme.requestFocus(); setVisible(true); // make frame visible } public static void main(String args[]) {new Frame2();} }
GUIs are event-based as they respond to buttons, keyboard input or mouse activities. Java uses event listeners to monitor activity on specified objects and react to specific conditions. Check theappendix for a listing of event listeners. View advanced event listeners for techniques on organizing many different events in larger projects. The first step in adding a basic button push event handler to the above example is to import awt.event.* which contains all of the event classes. Next add the phrase implements ActionListenerto the class header to use the interface. Register event listeners for each button widget using theaddActionListener(this) method. The reserved word thisindicates that the required (by implements ActionListener) handler method called actionPerformed() will be included in the current class. For example:
import java.aw t.*; import java.aw t.event.*; import javax.sw ing.*; public class Frame3 extends JFrame implements ActionListener { JLabel answ er=new JLabel(""); JPanel pane=new JPanel(); // create pane object JButton pressme=new JButton("Press Me"); Frame3() // the constructor { super("Event Handler Demo"); setBounds(100,100,300,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con=this.getContentPane(); // inherit main frame con.add(pane); pressme.setMnemonic('P'); // associate hotkey pressme.addActionListener(this); // register button listener pane.add(answ er); pane.add(pressme); pressme.requestFocus(); setVisible(true); // make frame visible } // here is the basic event handler public void actionPerformed(ActionEvent event) { Object source=event.getSource(); if (source==pressme) { answ er.setText("Button pressed!"); JOptionPane.show MessageDialog(null,"I hear you!", "Message Dialog",JOptionPane.PLAIN_MESSAGE); setVisible(true); // show something } } public static void main(String args[]) {new Frame3();} }
Bounded-Range Components
Bounded-range components are controls that have a single integer value within fixed integer boundaries. Examples of bounded-range controls are progress bars. sliders and scroll bars. Each bounded-range component has the following methods: setExtent(), setMaximum(), setMinimum(), setValue(), getValueIsAdjusting()and setOrientation(). Bounded-range components useChangeEvent to start an update. Progress bars indicate status for time consuming jobs. The basic JProgressBar class offers a subtle control. If you want a dialog frame for canceling an operation the classes,ProgressMonitor and ProgressMonitorInputStreamare better choices.
ProgressMonitorInputStream is a stream filter in addition to a progress monitor. ProgBar.java is a simple progress bar demo. Sliders allow integer selection within limits. They can be dressed up with ticks and labels using setPaintTicks(true)and setPaintLabels(true). setMajorTickSpacing(int)and setMinorTickSpacing(int) set the intervals used for marker ticks. setSnapToTicks(true) forces the slider to the closest tick. setInverted(true) reverses the low and high marks.labelTable is a dictionary of slider values and Jlabel objects for painting the object. Slider.javais a simple slider demo. Java Swings Tutorial
What is Swings in java ? A part of The JFC Swing Java consists of Look and feel Accessibility Java 2D Drag and Drop, etc Compiling & running programs javac <program.java> && java <program> Or JCreator / IDE if you do not explicitly add a GUI component to a container, the GUI component will not be displayed when the container appears on the screen. Swing, which is an extension library to the AWT, includes new and improved components that enhance the look and functionality of GUIs. Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets. It employs a model/view design architecture. Swing is more portable and more flexible than AWT. Swing Model/view design: The view part of the MV design is implemented with a component object and the UI object. The model part of the MV design is implemented by a model object and a change listener object. <br /><font size=-1> Swing is built on top of AWT and is entirely written in Java, using AWTs lightweight component support. In particular, unlike AWT, t he architecture of Swing components makes it easy to customize both their appearance and behavior. Components from AWT and Swing can be mixed, allowing you to add Swing support to existing AWT-based programs. For example, swing components such as JSlider, JButton and JCheckbox could be used in the same program with standard AWT labels, textfields and scrollbars. You could subclass the existing Swing UI, model, or change listener classes without having to reinvent the entire implementation. Swing also has the ability to replace these objects on-the-fly.
100% Java implementation of components Pluggable Look & Feel Lightweight components Uses MVC Architecture Model represents the data
View as a visual representation of the data Controller takes input and translates it to changes in data Three parts Component set (subclasses of JComponent) Support classes Interfaces
In Swing, classes that represent GUI components have names beginning with the letter J. Some examples are JButton, JLabel, and JSlider. Altogether there are more than 250 new classes and 75 interfaces in Swing twice as many as in AWT. Java Swing class hierarchy The class JComponent, descended directly from Container, is the root class for most of Swings user interface components.
Swing contains components that youll use to build a GUI. I am listing you some of the commonly used Swing components. To learn and understand these swing programs, AWT Programming knowledge is not required.
} Output
public static void main(String args[]) { new HelloWorldFrame(); } HelloWorldFrame() { JLabel jlbHelloWorld = new JLabel("Hello World"); add(jlbHelloWorld); this.setSize(100, 100); // pack(); setVisible(true); }
Note: Below are some links to java swing tutorials that forms a helping hand to get started with java programming swing.
JPanel is Swings version of the AWT class Panel and uses the same default layout,
class. The components added to the frame are referred to as its contents; these are managed by the contentPane. To add a component to a JFrame, we must use its contentPane instead.
JWindow
is Swings version of Window and is descended directly from that class. Like Window, it uses BorderLayout by default.
JDialog is Swings version of Dialog and is descended directly from that class. Like
Dialog, it uses BorderLayout by default. Like JFrame and JWindow, JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass panes. All dialogs are modal, which means the current thread is blocked until user interaction with it has been completed. JDialog class is intended as the basis for creating custom dialogs; however, some of the most common dialogs are provided through static methods in the class JOptionPane.
JButton.
JTextField allows editing of a single line of text. New features include the
ability to justify the text left, right, or center, and to set the texts font.
JTextArea
allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying
JCheckBox
is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state.
JComboBox JList
is like a drop down box. You can click a drop-down arrow and select an option from a list. For example, when the component has focus, pressing a key that corresponds to the first character in some entrys name selects that entry. A vertical scrollbar is used for longer lists. provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the scroll pane can also have a user-defined border. JList actions are handled using ListSelectionListener.
JTabbedPane contains a tab that can have a tool tip and a mnemonic,
and it can display both text and an image.
BorderLayout
places swing components in the North, South, East, West and center of a container. You can add horizontal and vertical gaps between the areas.
JMenubar
can contain several JMenus. Each of the JMenus can contain a series of JMenuItem s that you can select. Swing provides support for pull-down and popup menus.
developed using Java Swing. It is a basic four-function calculator java program source code.
simple free address book program using java swing and jdbc. Also you will learn to use the following swing components like Jbuttons, JFrames, JTextFields and Layout Manager (GridBagLayout).