Created by dovari.sudheerkiran@gmail.


The Java Swing tutorial

First Programs

Menus and Toolbars

Swing Layout Management

Swing Events

Swing Dialogs

Basic Swing Components

Basic Swing Components II

Swing models

Drag and Drop


Resizable component



For more information

Introduction to the Java Swing Toolkit
About this tutorial
This is an introductory Swing tutorial. The purpose of this tutorial is to get you started with the Java Swing toolkit. The tutorial has been created and tested on Linux.

About Swing
Swing library is an official Java GUI toolkit released by Sun Microsystems. The main characteristics of the Swing toolkit • • • • • platform independent customizable extensible configurable lightweight

Swing consists of the following packages • • • • • • • • • • • • • javax.swing javax.swing.border javax.swing.colorchooser javax.swing.event javax.swing.filechooser javax.swing.plaf javax.swing.plaf.basic javax.swing.plaf.metal javax.swing.plaf.multi javax.swing.plaf.synth javax.swing.table javax.swing.text javax.swing.text.html

For more information

Created by

• • • •

javax.swing.text.html.parser javax.swing.text.rtf javax.swing.tree javax.swing.undo

Swing is probably the most advanced toolkit on this planet. It has a rich set of widgets. From basic widgets like Buttons, Labels, Scrollbars to advanced widgets like Trees and Tables. Swing is written in 100% java. Swing is a part of JFC, Java Foundation Classes. It is a collection of packages for creating full featured desktop applications. JFC consists of AWT, Swing, Accessibility, Java 2D, and Drag and Drop. Swing was released in 1997 with JDK 1.2. It is a mature toolkit. The Java platform has Java2D library, which enables developers to create advanced 2D graphics and imaging. There are basically two types of widget toolkits. • • Lightweight Heavyweight

A heavyweight toolkit uses OS's API to draw the widgets. For example Borland's VCL is a heavyweight toolkit. It depends on WIN32 API, the built in Windows application programming interface. On Unix systems, we have GTK+ toolkit, which is built on top of X11 library. Swing is a lightweight toolkit. It paints it's own widgets. It is in fact the only lightweight toolkit I know about.

SWT library
There is also another GUI library for the Java programming language. It is called SWT. The Standard widget toolkit. The SWT library was initially developed by the IBM corporation. Now it is an open source project, supported by IBM. The SWT is an example of a heavyweight toolkit. It lets the underlying OS to create GUI. SWT uses the java native interface to do the job. The main advantages of the SWT are speed and native look and feel. The SWT is on the other hand more error prone. It is less powerful then Swing. It is also quite Windows centric library.

For more information

Java Swing first programs
In this chapter, we will program our first programs in Swing toolkit. The examples are going to be very simple. We will cover some basic functionality.

Our first example
In our first example, we will show a basic window.

import javax.swing.JFrame;

public class Simple extends JFrame {

public Simple() {

setSize(300, 200); setTitle("Simple"); setDefaultCloseOperation(EXIT_ON_CLOSE); }

public static void main(String[] args) {

Simple simple = new Simple();

For more information

Created by


} }

While this code is very small, the application window can do quite a lot. It can be resized, maximized, minimized. All the complexity that comes with it has been hidden from the application programmer.

import javax.swing.JFrame; Here we import the JFrame widget. It is a toplevel container, which is used for placing other widgets.

setSize(300, 200);

setTitle("Simple"); This code will resize the window to be 300px wide and 200px tall. It will set the title of the window to Simple.

setDefaultCloseOperation(EXIT_ON_CLOSE); This method will close the window, if we click on the close button. By default nothing happens.

For more information

Figure: Simple

Centering window on the screen
By default, when the window is shown on the screen, it is not centered. It will pop up most likely in the upper left corner. The following code example will show the window centered on the screen.

import java.awt.Dimension; import java.awt.Toolkit;

import javax.swing.JFrame;

public class CenterOnScreen extends JFrame {

public CenterOnScreen() {

For more information

setVisible(true).com . Toolkit toolkit = getToolkit(). setDefaultCloseOperation(EXIT_ON_CLOSE). For more information http://www.height/2 .computertech-dovari.Created by dovari. cos. setLocation(size.getWidth()/2. Toolkit toolkit = getToolkit().com setSize(300. For this.getHeight()/2). Dimension size = toolkit. we use the Toolkit class. setTitle("CenterOnScreen").width/2 . 200).blogspot. we must know the resolution of the monitor. } } To center the window on the screen. } public static void main(String[] args) { CenterOnScreen cos = new CenterOnScreen().sudheerkiran@gmail. size.getScreenSize().

For more information http://www.JPanel.awt. setLocation( . import javax. import java. We get the toolkit and figure out the screen size.event. import java.blogspot.width/2 .ActionEvent.getWidth()/2. we call the setLocation() method.ActionListener. import javax.Dimension.Toolkit.swing. we will show two buttons. size.Dimension size = toolkit. The first button will beep a sound and the second button will close the window.JFrame.awt.getScreenSize().awt.event.swing. To place the window on the screen. public class Buttons extends JFrame { private Toolkit toolkit. import java.height/2 . import java.awt.getHeight()/2).swing. Buttons In our next example. import javax.computertech-dovari.

com . panel.sudheerkiran@gmail.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { toolkit.setBounds(150. toolkit = getToolkit().add(panel).getScreenSize(). For more information http://www. 200). JPanel panel = new JPanel(). 30). beep. 60. JButton beep = new JButton("Beep").blogspot.width . beep.Created by dovari.height getHeight())/2). 80.beep(). setDefaultCloseOperation(EXIT_ON_CLOSE). Dimension size = toolkit. setSize(300. getContentPane().getWidth())/2.setLayout(null). (size.computertech-dovari. setLocation(( public Buttons() { setTitle("Buttons").

setBounds(50.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.blogspot. } public static void main(String[] args) { Buttons buttons = new Buttons(). 30).add(beep).computertech-dovari. } }). buttons. 80. JButton close = new JButton("Close").} }). panel. close. For more information http://www.setVisible(true).exit(0). 60. .add(close). panel.

addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { toolkit. we use the setBounds() } } In this example. The layout manager is used to place widgets onto the containers.setBounds(150. JPanel panel = new JPanel(). They will be touched only briefly. we will see two new .add(panel). the JPanel has a FlowLayout manager.blogspot.beep(). 80. By default. beep.Created by dovari. For more information http://www. Both of the topics will have their own chapter. beep. We create a JPanel component.setLayout(null).computertech-dovari. JButton beep = new JButton("Beep"). getContentPane(). If we call setLayout(null) we can position our components absolutely. panel. It is a generic lightweight container. 30).sudheerkiran@gmail. } }). Layout management and event handling. For this. We add the JPanel to the JFrame. 60.

The Swing shows a small rectangular window. import java. The beep button will play a simple beep sound. We position it by calling the setBounds() method.Dimension. For this.awt. For more information http://www. panel. Figure: Buttons A tooltip Tooltips are part of the internal application's help system. we must add them to the panel. if we hover a mouse pointer over an object. In order to show the buttons. Then we add an action listener. System.add(close). In our case.add(beep). if we click on the button. we call the System.exit(0).exit() method.awt. The action listener will be called.Toolkit. The close button will exit the application. import java.Here we create a button. panel. when we perform an action on the .blogspot.

width . toolkit = getToolkit().JButton. public Tooltip() { setTitle("Tooltip").swing. 200).Created by dovari.swing. Dimension size = toolkit.sudheerkiran@gmail. setLocation((size. JPanel panel = new JPanel().com import javax.height getHeight())/2). import javax. import . (size.JPanel. setSize(300. public class Tooltip extends JFrame { private Toolkit toolkit.getScreenSize(). setDefaultCloseOperation(EXIT_ON_CLOSE).swing. For more information http://www.getWidth())/2.

getContentPane(). button. button. panel.add(panel).setToolTipText("A Panel container").computertech-dovari. JButton button = new JButton("Button").setToolTipText("A button component").setVisible(true). 80. } public static void main(String[] args) { Tooltip tooltip = new Tooltip().setLayout(null).blogspot.setBounds(100. 60. panel. panel. } } For more information .add(button). 30). tooltip.

For more information http://www. we call the setTooltipText() method.sudheerkiran@gmail.Created by In the example.setToolTipText("A Panel container"). There are accepted standards that further reduce the amount of time spending to learn a new application. A JMenuBar.computertech-dovari. To enable a tooltip. In Java Swing. a JMenu and a JMenuItem.blogspot. While in console applications you had to remember all those arcane commands. Figure: Tooltip Menus and toolbars in Java Swing Creating a menubar A menubar is one of the most visible parts of the GUI application. It is a group of commands located in various menus. we set the tooltip for the frame and the button. panel. to implement a menubar. we use three objects. Simple menubar We begin with a simple menubar example. here we have most of the commands grouped into logical .

computertech-dovari.zetcode.awt.awt.ActionListener.KeyEvent.swing.swing. import javax.png"). import java.JMenu. import java. import javax.JMenuItem.swing. JMenuBar menubar = new JMenuBar().blogspot. import javax.awt. import javax.event.event.ImageIcon.JFrame.event. For more information http://www. import java.package com.swing. import javax. public class Menu extends JFrame { public Menu() { setTitle("JMenuBar").JMenuBar.ActionEvent. ImageIcon icon = new ImageIcon(" .swing.

add(fileClose).exit(0).VK_C). JMenu file = new JMenu("File").blogspot. setSize(250.computertech-dovari. file.add(file). } }).setMnemonic(KeyEvent. fileClose. fileClose. fileClose. For more information http://www.setToolTipText("Exit application").sudheerkiran@gmail. file. 200).setMnemonic(KeyEvent. icon).Created by dovari.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { . JMenuItem fileClose = new JMenuItem("Close".VK_F). setJMenuBar(menubar).

We will display an icon in the menu. Here we create a menubar. We create a menu object. In our case.VK_F).blogspot.setMnemonic(KeyEvent. For more information http://www.setLocationRelativeTo(null). ImageIcon icon = new ImageIcon("exit. Selecting the close menu item we close the application. } public static void main(String[] args) { new Menu(). JMenuBar menubar = new JMenuBar(). the menu can be opened with the ALT + F shortcut.png").com . setDefaultCloseOperation(EXIT_ON_CLOSE). To bind a menu to a particular key. we use the setMnemonic method.computertech-dovari. } } Our example will show a menu with one item. The menus can be accessed via the keybord as well. JMenu file = new JMenu("File"). file. setVisible(true).

sudheerkiran@gmail.KeyEvent.Created by dovari.blogspot.awt.event. status bar or navigation bar into a submenu called toolbars. .event.computertech-dovari. import java. print preview with a single separator.ActionEvent. we can seperate commands with a separator.awt.event. import java. Menus commands can be launched via keyboard shortcuts. This code line creates a tooltip for a menu item. address bar. For this.awt. import java.swing. It is common practice to separate commands like new. import javax. For more information http://www.setToolTipText("Exit application").ImageIcon. we define menu item accelerators.ActionListener. Figure: JMenuBar Submenu Each menu can also have a submenu. This way we can group similar commnads into fileClose. For example we can place commands that hide/show various toolbars like personal bar. save from commands like print. It is a simple line. Within a menu.

import javax.JMenu. import javax.JMenuItem.swing.swing. For more information http://www. ImageIcon iconNew = new ImageIcon("new. JMenuBar menubar = new JMenuBar().com . ImageIcon iconClose = new ImageIcon("exit. JMenu file = new JMenu("File").swing.png"). ImageIcon iconSave = new ImageIcon("save. public class Submenu extends JFrame { public Submenu() { setTitle("Submenu").VK_F). file. import javax.png").JFrame.KeyStroke.swing.JMenuBar.blogspot.png"). ImageIcon iconOpen = new ImageIcon("open. import javax.setMnemonic(KeyEvent.png").import javax.computertech-dovari.swing.

JMenuItem bookm = new JMenuItem("Import bookmarks. imp. JMenuItem fileOpen = new JMenuItem("Open". imp. JMenuItem newsf = new JMenuItem("Import newsfeed list.add(newsf). iconOpen).").add(bookm).setMnemonic(KeyEvent.VK_N). . imp.VK_O).VK_M).setMnemonic(KeyEvent.").add(mail).."). imp. JMenu imp = new JMenu("Import").Created by dovari.sudheerkiran@gmail.VK_S). JMenuItem fileSave = new JMenuItem("Save"..setMnemonic(KeyEvent.. JMenuItem mail = new JMenuItem("Import mail. fileSave. iconNew).blogspot.. JMenuItem fileNew = new JMenuItem("New".. For more information http://www. iconSave)..setMnemonic(KeyEvent.

add(fileClose).add(fileNew).setAccelerator(KeyStroke.addSeparator().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.VK_W.add(fileSave).computertech-dovari. fileClose. file. ActionEvent.JMenuItem fileClose = new JMenuItem("Close". } }). file. file. fileClose. fileClose. file.exit(0).getKeyStroke(KeyEvent.CTRL_MASK)).addSeparator().add(imp). iconClose). file.VK_C).com . file. file.setMnemonic(KeyEvent. For more information http://www.add(fileOpen).blogspot.setToolTipText("Exit application"). fileClose.

. . setVisible(true). For more information http://www. JMenu imp = new JMenu("Import").getKeyStroke(KeyEvent. 250).blogspot.computertech-dovari. file.add(imp). setJMenuBar(menubar). It is created the same menubar.VK_W.. } } In this example. We simply add a menu to existing menu. fileClose.add(file). } public static void main(String[] args) { new Submenu(). setSize(360.setAccelerator(KeyStroke. a menu separator and an accelerator key.Created by dovari. setDefaultCloseOperation(EXIT_ON_CLOSE). setLocationRelativeTo(null).com . we create a submenu. A submenu is just like any other normal menu.

Figure: Submenu JCheckBoxMenuItem A menu item that can be selected or deselected. An accelerator is a key shortcut that launches a menu item. import java.blogspot.event.ActionListener.addSeparator(). This way we can group items into some logical places. the menu item appears without a . In our case. the menu item typically appears with a checkmark next to it.awt. Like a regular menu item. by pressing Ctrl + W we close the application.CTRL_MASK)). or both.ActionEvent. If unselected or deselected.event. file.ActionEvent. import java. a check box menu item can have either text or a graphic icon associated with it.awt. import java. A separator is a vertical line that visually separates the menu items. For more information http://www. If selected.BorderLayout.awt.computertech-dovari.

import javax.awt.blogspot. import javax.sudheerkiran@gmail.swing.swing.JCheckBoxMenuItem.computertech-dovari. import javax.JMenu.swing.event. For more information http://www.EtchedBorder.swing.Created by dovari.JFrame.swing.JLabel.BorderFactory. public CheckMenuItem() { setTitle("CheckBoxMenuItem"). import javax. import import java. import javax.swing.UIManager. import javax.swing. import . public class CheckMenuItem extends JFrame { private JLabel statusbar.JMenuBar.

JMenuBar menubar = new JMenuBar(); JMenu file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F);

JMenu view = new JMenu("View"); view.setMnemonic(KeyEvent.VK_V);

JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar"); sbar.setState(true);

sbar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (statusbar.isVisible()) { statusbar.setVisible(false); } else { statusbar.setVisible(true); } }


For more information

Created by


menubar.add(file); menubar.add(view);


statusbar = new JLabel(" Statusbar"); statusbar.setBorder(BorderFactory.createEtchedBorder( EtchedBorder.RAISED)); add(statusbar, BorderLayout.SOUTH);

setSize(360, 250); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); }

public static void main(String[] args) { new CheckMenuItem();

For more information

} } The example shows a JCheckBoxMenuItem.. By selecting the menu item, we toggle the visibility of the statusbar.

JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar");

sbar.setState(true); We create the JCheckBoxMenuItem and check it by default. The statusbar is initially visible.

if (statusbar.isVisible()) {


} else {


} Here we toggle the visibility of the statusbar.

statusbar = new JLabel(" Statusbar");

statusbar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED)); The statusbar is a simple JLabel component. We put a raised EtchedBorder around the label, so that it is discernible.

For more information

Created by

Figure: JCheckBoxMenuItem

A popup menu
Another type of a menu is a popup menu. It is sometimes called a context menu. It is usually shown, when we right click on a component. The idea is to provide only the commands, that are relevant to the current context. Say we have an image. By right clicking on the image, we get a window with commands to save, rescale, move etc the image.

import java.awt.Toolkit;

import javax.swing.*; import java.awt.event.*;

public class PopupMenu {

For more information

private JPopupMenu menu; private Toolkit toolkit;

public PopupMenu(){

JFrame frame = new JFrame("JPopupMenu"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

toolkit = frame.getToolkit();

menu = new JPopupMenu(); JMenuItem menuItemBeep = new JMenuItem("Beep");

menuItemBeep.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { toolkit.beep(); } });


For more information

Created by

JMenuItem menuItemClose = new JMenuItem("Close"); menuItemClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); }



frame.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { if (e.getButton() == e.BUTTON3) {, e.getX(), e.getY()); } } });

frame.setSize(250, 200); frame.setLocationRelativeTo(null);

For more information

To create a popup menu. as with the standard JMenu frame. The menu item is the same.frame. In our example.setVisible(true).BUTTON3) { menu.computertech-dovari.getX(). } For more information http://www. e. menu = new JPopupMenu().addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { if (e. menu separators and create an accelerator key.getComponent(). we have a class called JPopupMenu. The first option of the popup menu will beep a . JMenuItem menuItemBeep = new JMenuItem("Beep"). we create a submenu. } public static void main(String[] args) { new PopupMenu().getButton() == e. } } Our example shows a demonstrational popup menu with two commands. the second one will close the window. e.

import java.sudheerkiran@gmail.awt. where we clicked with the mouse . import javax. The popup menu is shown.ImageIcon. import javax.awt. In Java } }). import java. the JToolBar class creates a toolbar in an application.swing. For more information http://www.JButton.event. The BUTTON3 constant is here to enable the popup menu only for the mouse right click.Created by dovari.BorderLayout.blogspot.ActionEvent. import java.event.ActionListener.swing. Toolbars provide a quick access to the most frequently used commands. Figure: Popup menu JToolbar Menus group commands that we can use in an application.computertech-dovari.

JMenu. JMenu file = new JMenu("File").swing. JMenuBar menubar = new JMenuBar(). public class SimpleToolbar extends JFrame { public SimpleToolbar() { setTitle("SimpleToolbar"). import javax.add(file). menubar. setJMenuBar(menubar).blogspot. import .swing. For more information http://www. import javax.import javax.JToolBar.JFrame.swing. JToolBar toolbar = new JToolBar().computertech-dovari.swing.

sudheerkiran@gmail. toolbar.getResource("exit.NORTH).com . exit. setSize(300. BorderLayout. setVisible(true). add(toolbar.computertech-dovari. } }).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.Created by dovari. setLocationRelativeTo(null). JButton exit = new JButton(icon). } For more information http://www. 200).com ImageIcon icon = new ImageIcon(getClass().exit(0).png")).add(exit). setDefaultCloseOperation(EXIT_ON_CLOSE).blogspot.

For more information http://www.BorderLayout.computertech-dovari.add(exit).public static void main(String[] args) { new SimpleToolbar(). import java. JToolBar toolbar = new JToolBar(). how we could do it.blogspot. } } The example creates a toolbar with one exit button.awt. The next example shows. toolbar. This is the JToolBar . We create a button and add it to the toolbar. Figure: Simple JToolBar Toolbars Say. we wanted to create two toolbars. JButton exit = new JButton(icon).

import javax.swing.ActionListener.awt. import java. import . JToolBar toolbar2 = new JToolBar().com import java. import javax. For more information http://www.event. public class Toolbars extends JFrame { public Toolbars() { setTitle("Toolbars").ActionEvent.Created by dovari. JPanel panel = new JPanel().swing.JPanel. import javax.JButton. import javax.swing.swing.swing.awt. import javax.computertech-dovari.sudheerkiran@gmail.blogspot.BoxLayout.JFrame.swing. JToolBar toolbar1 = new JToolBar().event.

Y_AXIS)) .setAlignmentX(0). toolbar1.png")). ImageIcon exit = new ImageIcon( getClass().getResource("save.getResource("open. JButton saveb = new JButton(save). ImageIcon newi = new ImageIcon( getClass(). For more information http://www.add(saveb).add(openb). JButton openb = new JButton(open).blogspot. JButton exitb = new JButton(exit).getResource("new. toolbar1. toolbar1. ImageIcon open = new ImageIcon( getClass().computertech-dovari. ImageIcon save = new ImageIcon( getClass().png")).png")). toolbar1. BoxLayout.setLayout(new BoxLayout(panel. JButton newb = new JButton(newi).png")).add(newb).getResource("exit.

com toolbar2. panel. .add(toolbar2). panel. add(panel.add(toolbar1). setSize(300. BorderLayout.blogspot.Created by dovari.add(exitb).exit(0).NORTH). 200).computertech-dovari. setVisible(true). } For more information http://www.sudheerkiran@gmail.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System. exitb. } }). setLocationRelativeTo(null).setAlignmentX(0). setDefaultCloseOperation(EXIT_ON_CLOSE).

Y_AXIS)). add(panel. The toolbar is left aligned.add(toolbar2). panel. panel. the panel is located into the north part of the frame. Finally.setLayout(new BoxLayout(panel. toolbar1. We put a JPanel to the north of the BorderLayout manager. For more information http://www. JToolBar toolbar2 = new JToolBar(). JToolBar toolbar1 = new JToolBar(). The panel has a vertical BoxLayout. BoxLayout. Of course. The panel has a vertical BoxLayout. there are several possibilities.NORTH).blogspot. } } We show only one way. Creation of two . how we could create toolbars. JPanel panel = new JPanel(). panel. We add the toolbars to the panel.computertech-dovari. We add the two toolbars into this panel.setAlignmentX(0). BorderLayout.public static void main(String[] args) { new Toolbars().add(toolbar1).

BorderLayout. import javax.swing.awt.JFrame.UIManager. import javax. import javax.JButton.swing.swing. import Figure: Toolbars A vertical toobar The following example shows a vertical .Created by dovari. import javax.computertech-dovari. import java. public class VerticalToolbar extends JFrame { For more information http://www.

ImageIcon pen = new ImageIcon( getClass().getResource("rectangle. JToolBar toolbar = new JToolBar(JToolBar. ImageIcon shapeed = new ImageIcon( getClass().gif")).gif")).getResource("qs. ImageIcon qs = new ImageIcon( getClass(). For more information http://www.gif")).VERTICAL). ImageIcon freehand = new ImageIcon( getClass(). ImageIcon rectangle = new ImageIcon( getClass().gif")).getResource("freehand. ImageIcon select = new ImageIcon( getClass().gif")).getResource("ellipse.getResource(" .getResource("pen.computertech-dovari.gif")).public VerticalToolbar() { setTitle("Vertical toolbar"). ImageIcon ellipse = new ImageIcon( getClass().gif")).getResource("shapeed.blogspot.

toolbar.add(ellipseb). JButton qsb = new JButton(qs).gif")).com ImageIcon text = new ImageIcon( getClass(). toolbar. JButton freehandb = new JButton(freehand). toolbar.add(shapeedb).add(penb). JButton textb = new JButton(text). toolbar. JButton rectangleb = new JButton(rectangle). JButton selectb = new JButton(select).add(rectangleb).com . For more information http://www.blogspot. JButton ellipseb = new JButton(ellipse).add(textb).add(selectb). toolbar.sudheerkiran@gmail.add(freehandb).getResource("text. toolbar.Created by dovari. toolbar. JButton shapeedb = new JButton(shapeed). JButton penb = new JButton(pen).add(qsb).computertech-dovari. toolbar.

setVisible(true). BorderLayout.out.add(toolbar. This is typical for a graphics applications likeXara Extreme or Inkscape.setLookAndFeel( UIManager. we use icons from Xara Extreme application. setDefaultCloseOperation(EXIT_ON_CLOSE).println("Error:" + e. setLocationRelativeTo(null).getSystemLookAndFeelClassName()). we put a vertical toolbar to the left side of the window.getStackTrace()). } public static void main(String[] args) { try { UIManager. In our example. } new VerticalToolbar(). 350).computertech-dovari. For more information http://www. } catch (Exception e) { System.WEST). setSize(250. } } In the .

blogspot.sudheerkiran@gmail. and they would not look ok on a different theme. In my case. it was the gtk theme.VERTICAL). We create a vertical toolbar.WEST). Figure: Vertical toolbar The Swing layout management For more information http://www.Created by dovari. add(toolbar. The icons are not JToolBar toolbar = new JToolBar( .setLookAndFeel( UIManager. The toolbar is placed into the left part of the window.getSystemLookAndFeelClassName()). I used the system look and feel.computertech-dovari. BorderLayout. UIManager.

complex applications. we position components using absolute values. we use layout . import javax. we need layout managers.blogspot. that GUI builder's like Matisse cannot replace the proper understanding of layout managers. For example. Many beginning programmers have too much respect for layout managers. To create layouts. public class Absolute extends JFrame { public Absolute() { setTitle("Absolute positioning"). Containers and children. Without layout manager. Mainly because they are usually poorly documented. It is because I did not want to make the examples too complex.swing.swing. I often go without a manager. There might be situations.JFrame. But to create truly portable. in my code examples. I believe. if we want.The Java Swing toolkit has two kind of components. import javax.computertech-dovari. For more information http://www. where we might not need a layout manager. ZetCode offers a dedicated 196 pages e-book for the Swing layout management process: Java Swing layout management tutorial No manager We can use no layout manager.JButton. The containers group children into suitable layouts. Layout managers are one of the most difficult parts of modern GUI programming.

setSize(300. 80. add(ok). 25). 250).Created by dovari.sudheerkiran@gmail. } public static void main(String[] args) { new Absolute(). 150. 25). ok. } For more information http://www. setVisible(true).EXIT_ON_CLOSE). close.setBounds(150. 150. setLocationRelativeTo(null). JButton ok = new JButton("OK"). 80.blogspot. JButton close = new JButton("Close").setBounds( setLayout(null). setDefaultCloseOperation( .computertech-dovari. add(close).

com . FlowLayout manager This is the simplest layout manager in the Java Swing toolkit. It is mainly used in combination with other layout managers. int hgap. the components are centered and there is 5px space among components and components and the edges of the container. The components can be added from the right to the left or vice versa. The parameters are the x. 25). import java. they go into the next one. The others allow to specify those parametes. setLayout(null).blogspot. The first one creates a manager with implicit values.computertech-dovari. When calculating it's children size.setBounds(50.awt. The setBounds() method positions the ok button. ok. If they do not fit into one row.} This simple example shows two buttons. For more information http://www. Centered and 5px spaces. FlowLayout() FlowLayout(int align) FlowLayout(int align. they were added. a flow layout lets each component assume its natural (preferred) size. The manager allows to align the components. We use absolute positioning by providing null to the setLayout() method. int vgap) There are three constructors available for the FlowLayout manager.Dimension. 150. Implicitly. 80. In the order. The manager puts components into a row. y location values and the width and height of the component.

Created by dovari.sudheerkiran@gmail.swing. import import javax.JButton. 100)).swing. JTextArea area = new JTextArea("text area").JTree.swing.JPanel. For more information http://www. import javax. JPanel panel = new JPanel().com .blogspot. JButton button = new JButton("button"). area.setPreferredSize(new Dimension(100. import javax.computertech-dovari.swing.JFrame. public class FlowLayoutExample extends JFrame { public FlowLayoutExample() { setTitle("FlowLayout Example").JTextArea. import javax.swing.

pack().com .add(button). panel.panel. } public static void main(String[] args) { new FlowLayoutExample(). setVisible(true). } } For more information http://www. setDefaultCloseOperation(JFrame. panel.EXIT_ON_CLOSE). JTree tree = new JTree().add(tree). add(panel).blogspot. setLocationRelativeTo(null).computertech-dovari.add(area).

that in our case. For more information http://www. the component would have a size of it's text. Interesingly.Created by dovari. a tree and a text area component in the window. panel. if we create an empty tree component.sudheerkiran@gmail. Without the text. This The example shows a button. No more. we simply call the add() method. If we didn't set the preferred size. One component is placed in each rectangle. Try to write or delete some text in the area component. We do not have to set it manually. The container is divided into equally sized rectangles.add(area). 100)). The flow layout manager sets a preferred size for it's components. there are some default values inside the component. no . Figure: FlowLaout manager GridLayout The GridLayout layout manager lays out components in a rectangular grid. JTextArea area = new JTextArea("text area"). To put a component inside a container.computertech-dovari.awt. JPanel panel = new JPanel(). The component will grow and shrink accordingly. the component would not be visible at all. The implicit layout manager of the JPanel component is a flow layout manager. area.GridLayout. import java.setPreferredSize(new Dimension(100. the area component will have 100x100 px.

4. import javax.JFrame. 5)).computertech-dovari. "7". "8".JPanel.BorderFactory.JButton. 5.import javax.createEmptyBorder(5. String[] buttons = { "Cls". panel. For more information http://www.swing. 5.swing. import javax. panel. "9".swing.swing. public class GridLayoutExample extends JFrame { public GridLayoutExample() { setTitle("GridLayout"). import javax. import javax.blogspot. "/".swing. "Bck". "". "Close".setLayout(new GridLayout(5.setBorder(BorderFactory. . 5)). JPanel panel = new JPanel().JLabel. "4".

"+" }. "-". } add(panel).computertech-dovari. setDefaultCloseOperation(JFrame. i++) { if (i == 2) panel.add(new JLabel(buttons[i])).Created by dovari. "1". "6". setVisible(true).EXIT_ON_CLOSE).com .blogspot. "2". i < buttons.length. 300).sudheerkiran@gmail. } For more information http://www. setLocationRelativeTo(null). "3".add(new JButton(buttons[i])). for (int i = 0.". "*". ". else panel. "=".com "5". "0". setSize(350.

com . The number of rows. We put 19 buttons and one label into the manager.public static void main(String[] args) { new GridLayoutExample(). that each button is of the same size. Figure: GridLayout manager BorderLayout For more information http://www. } } The example shows a skeleton of a simple calculator tool.computertech-dovari. It is an ideal example for this layout manager.blogspot.setLayout(new GridLayout(5. the number of columns and the horizontal and vertical gaps between components. Here we set the grid layout manager for the panel component. 5. Notice. 5)). The layout manager takes four parameters. 4. panel.

Dimension.awt. there are other types of borders as well.BorderLayout. import javax. import javax. I haven't seen it elsewhere.swing. North. It does not look good. we can simply put a panel there with a manager of our choice. if child components are too close to each other. we either create a new instance of an EmptyBorder class or we use a BorderFactory.Color. If we need to put more components into a region. But for layout management we will use only this one. Each region can have only one component.blogspot.JFrame. S. The component in the centre takes up the whole space left.sudheerkiran@gmail.computertech-dovari. Each component in Swing toolkit can have borders around it's edges. A BorderLayout manager is a very handy layout manager.awt.swing. import java.JPanel.awt. import javax. public class BorderExample extends JFrame { public BorderExample() { For more information http://www. import java.EmptyBorder.swing. E regions get their preferred size. We must put some space among them.border. To create a border.Created by dovari. South. It divides the space into five regions. East and Centre. import java. import java. . The components in N.Insets. Except for EmptyBorder.awt.

computertech-dovari.setBackground(Color. panel.add(top). JPanel top = new JPanel(). 20))). setDefaultCloseOperation(JFrame. } For more information http://www. add(panel).setBorder(new EmptyBorder(new Insets(20.setTitle("Border Example"). 150)).com . setLocationRelativeTo(null). panel. setVisible(true). pack(). top. top.setPreferredSize(new Dimension(250. 20. JPanel panel = new JPanel(new BorderLayout()). 20.blogspot.gray).EXIT_ON_CLOSE).

We used a BorderLayout manager for the first panel. . JPanel top = new JPanel(). Here we created a 20px border around the panel. Here we placed a top panel into the panel component. 20.add(top).Created by dovari. public static void main(String[] args) { new BorderExample(). We place a panel into a panel. They go counterclockwise. left. bottom and right. we placed into the center area of theBorderLayout manager. because this manager will resize it's children. The border values are as follows: top. panel. Figure: Border example For more information http://www. } } The example will display a gray panel and border around it.computertech-dovari. 20))). More precisely.setBorder(new EmptyBorder(new Insets(20.sudheerkiran@gmail.blogspot. JPanel panel = new JPanel(new BorderLayout()).

blogspot.swing. import javax.JMenu. import java.swing.JLabel.swing.BorderLayout. import javax. import javax.computertech-dovari. import java. import javax.JFrame.border. public class BorderLayoutExample extends JFrame { public BorderLayoutExample() { For more information http://www. import javax.awt.swing.swing.swing.The next example will show a typical usage of a border layout manager.border. import javax. import javax. import javax.EmptyBorder.JMenuBar. import java.awt.ImageIcon. import javax.JTextArea.swing. import .Insets.LineBorder.JButton.awt.swing.swing.swing.Dimension.JToolBar.

JToolBar vertical = new JToolBar(JToolBar. 0)).com . JMenuBar menubar = new JMenuBar(). toolbar.VERTICAL). vertical.setBorder(new EmptyBorder(0 . bexit.Created by dovari.0. JToolBar toolbar = new JToolBar().computertech-dovari. BorderLayout.NORTH). JMenu file = new JMenu("File"). JButton bexit = new JButton(exit).add(bexit).setFloatable(false). 0.add(file).com setTitle("BorderLayout"). setJMenuBar(menubar). add(toolbar. ImageIcon exit = new ImageIcon("exit. menubar.png").setFloatable(false). For more information http://www. toolbar.sudheerkiran@gmail.blogspot.

blogspot.png").add(freehandb). ImageIcon shapeed = new ImageIcon("printer.add(selectb). 3. 0)). 5. add(vertical. 0)). shapeedb. BorderLayout. JButton shapeedb = new JButton(shapeed).setBorder(new EmptyBorder(3. ImageIcon select = new ImageIcon("drive.add(shapeedb). vertical. 0.computertech-dovari. 3.png"). 0. ImageIcon freehand = new ImageIcon("computer. For more information . vertical. freehandb.png"). JButton selectb = new JButton(select). 0)).vertical. 0. 3.CENTER).setBorder(new EmptyBorder(3.setMargin(new Insets(10. BorderLayout. 5)). selectb. JButton freehandb = new JButton(freehand).setBorder(new EmptyBorder(3. add(new JTextArea(). vertical.WEST). 5.

statusbar. setLocationRelativeTo(null). } } The example shows a typical application skeleton. 22)). BorderLayout. So we don't have to set it.setPreferredSize(new Dimension(-1. } public static void main(String[] args) { new BorderLayoutExample().com .blogspot. setVisible(true). statusbar. (a text area) A default layout manager for a JFrame component is BorderLayout JLabel statusbar = new JLabel(" Statusbar").NORTH).Created by dovari.EXIT_ON_CLOSE). setSize(350. 300).computertech-dovari.setBorder(LineBorder. add(statusbar.createGrayLineBorder()).SOUTH). For more information http://www. setDefaultCloseOperation(JFrame. BorderLayout. a statusbar and a central component. add(toolbar. We show a vertical and horizontal toolbars.

For more information http://www. It enables nesting. add(statusbar.SOUTH). BorderLayout. This layout manager puts components into a row or into a column. Figure: BorderLayout manager BoxLayout BoxLayout is a powerful manager. Put the statusbar to the .WEST).blogspot. that can be used to create sofisticated layouts. a powerful feature. that we can put a box layout into another box layout. add(new JTextArea(). Put the vertical toobar to the west. that makes this manager very flexible.CENTER).Simply put the toolbar to the north of the layout. BorderLayout. It means. Put the text area to the center. add(vertical. That's it. BorderLayout.

JFrame. This class creates several invisible components. For more information http://www.Box.swing. import javax.blogspot. import javax.JPanel. import The box layout manager is often used with the Box class.swing. which affect the final layout. • • • glue strut rigid area Let's say.sudheerkiran@gmail.swing. import javax.BoxLayout.swing. import javax. import java. we want to put two buttons into the right bottom corner of the window. We will use the boxlayut managers to accomplish .Dimension.JButton.swing. public class TwoButtons extends JFrame { public TwoButtons() { setTitle("Two Buttons").Created by dovari.awt.

createRigidArea(new Dimension(5. 0))). bottom.add(ok).createRigidArea(new Dimension(0.createVerticalGlue()).add(Box. . 15))). JButton ok = new JButton("OK"). bottom. For more information http://www.add(Box. add(basic).JPanel basic = new JPanel().setAlignmentX(1f).createRigidArea(new Dimension(15.computertech-dovari. bottom.blogspot. JButton close = new JButton("Close"). BoxLayout.add(bottom). basic. BoxLayout. basic. JPanel bottom = new JPanel(). 0))).Y_AXIS)).X_AXIS)).add(Box. bottom.add(Box.add(close). basic.setLayout(new BoxLayout(basic.setLayout(new BoxLayout(bottom. bottom. bottom.

blogspot. The basic panel has a vertical box layout. setDefaultCloseOperation(JFrame. setVisible(true). 250). The bottom panel has a horizontal one. } public static void main(String[] args) { new TwoButtons().com setSize(300. setLocationRelativeTo(null). We will put a bottom panel into the basic panel.EXIT_ON_CLOSE).Created by dovari. We will right align the For more information http://www. Figure: Two buttons We will create two . } } The following drawing illustrates the example.

bottom.bottom panel.computertech-dovari.createRigidArea(new Dimension(0.setLayout(new BoxLayout(bottom. For more information http://www. BoxLayout.setAlignmentX(1f). It is done by the vertical glue. basic. The panel has a horizontal layout.setLayout(new BoxLayout(basic.add(bottom). basic. Here we create a basic panel with the vertical BoxLayout.blogspot.Y_AXIS)). This is done by the setAlignmentX() method. The space between the top of the window and the bottom panel is expandable. The bottom panel is right aligned. We also put some space between the bottom panel and the border of the window. basic.add(Box.add(Box. 15))). bottom.createRigidArea(new Dimension(5. bottom. We put some rigid space between the buttons.X_AXIS)).com . BoxLayout. Here we put the bottom panel with a horizontal box layout to the vertical basic panel. 0))). JPanel bottom = new JPanel().

JPanel panel = new JPanel(). import javax.BoxLayout. import javax. we can set a rigid area among our . import Figure: Two buttons When we use a BoxLayout manager.JButton. import javax. import javax.JPanel. import java.Box.computertech-dovari.awt. import java.awt.swing.swing.Created by dovari.swing.Dimension.border. import javax.blogspot.EmptyBorder. public class RigidArea extends JFrame { public RigidArea() { setTitle("RigidArea").sudheerkiran@gmail.swing. For more information http://www.swing.

40.computertech-dovari.blogspot. 5))). panel. 60))). panel. panel.add(Box. panel. 5))).com . BoxLayout.panel.createRigidArea(new Dimension(0.Y_AXIS)).setLayout(new BoxLayout(panel.add(new JButton("Button")). setVisible(true). add(panel). pack().createRigidArea(new Dimension(0. } For more information http://www.createRigidArea(new Dimension(0.EXIT_ON_CLOSE).add(new JButton("Button")).add(Box.add(new JButton("Button")). 60. panel. panel.add(new JButton("Button")).setBorder(new EmptyBorder(new Insets(40. panel. panel.add(Box. 5))). setDefaultCloseOperation(JFrame. setLocationRelativeTo(null).

blogspot. panel. panel.computertech-dovari. we display four buttons. 5))). We add buttons and create a rigid area in between them. Figure: Rigid area Tip of the Day For more information http://www.createRigidArea(new Dimension(0. We use a vertical BoxLayout manager for our panel.Y_AXIS)).add(new JButton("Button")).com . there is no space among the buttons.add(new JButton("Button")). } } In this example.setLayout(new BoxLayout( public static void main(String[] args) { new RigidArea(). To put some space among them. we add some rigid area. BoxLayout.add(Box.sudheerkiran@gmail.Created by dovari. panel. By default. panel.

KeyEvent.awt. import java. import java.Color. flow layout and box layout manager. We will use a combination of various layout managers. import . import javax.Dimension.BorderFactory. import java.awt.blogspot. For more information http://www.awt.BorderLayout.awt.event.computertech-dovari. Figure: Tip of the Day We will create a similar dialog.swing.FlowLayout. Namely a border layout.awt.JDeveloper has a dialog window called Tip of the Day. import java.

import javax.JPanel.JTextPane.setLayout(new BoxLayout(basic. import javax. import javax.swing.swing. import javax.JButton.swing.swing. import javax.JCheckBox.swing.BoxLayout. public class TipOfDay extends JDialog { public TipOfDay() { setTitle("Tip of the Day"). import javax.Y_AXIS)).swing. basic.Created by dovari. JPanel basic = new JPanel() import javax. import javax.JDialog. add(basic). import javax.sudheerkiran@gmail. For more information http://www.ImageIcon.swing.blogspot. .

setMaximumSize(new Dimension(450. topPanel.gray).createEmptyBorder(5. For more information http://www.add(hint).add(topPanel).add(label. 0. 0)).SOUTH).setBorder(BorderFactory.computertech-dovari.setBorder(BorderFactory.setForeground(Color.createEmptyBorder(0.blogspot. JLabel label = new JLabel(icon).com . topPanel.EAST). separator.add(separator. 25. BorderLayout. JPanel textPanel = new JPanel(new BorderLayout()). basic. ImageIcon icon = new ImageIcon("jdev. 0)).JPanel topPanel = new JPanel(new BorderLayout(0. 5. 0)). JSeparator separator = new JSeparator(). JLabel hint = new JLabel("JDeveloper Productivity Hints"). 5. topPanel. topPanel. hint. label.png"). 5)). BorderLayout.

setEditable(false). String text = "<p><b>Closing windows using the mouse wheel</b></p>" + "<p>Clicking with the mouse wheel on an editor tab closes the window.createEmptyBorder(15. textPanel.add(pane). 15.blogspot.add(textPanel).setContentType("text/html"). box. boxPanel. pane.LEFT. 0)). JTextPane pane = new JTextPane(). 25. . JCheckBox box = new JCheckBox("Show Tips at startup"). For more information http://www.computertech-dovari.setText(text). 25)).Created by dovari. pane.setBorder(BorderFactory.VK_S).setMnemonic(KeyEvent. JPanel boxPanel = new JPanel(new FlowLayout(FlowLayout.</p>". " + "This method works also with dockable windows or Log window tabs.add(box). 20. textPanel.

basic. setDefaultCloseOperation(JDialog. bottom.add(ntip).setMaximumSize(new Dimension(450. bottom. JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT)).setMnemonic(KeyEvent.add(bottom).VK_C).computertech-dovari. } For more information http://www.setMnemonic(KeyEvent. setVisible(true). setSize(new Dimension(450.blogspot. 0)). close.VK_N). JButton ntip = new JButton("Next Tip"). setLocationRelativeTo(null). ntip.add(close). bottom.DISPOSE_ON_CLOSE).com . JButton close = new JButton("Close"). setResizable(false). 350)).add(boxPanel). basic.

We will put three components into it. 0)). The topPanel panel has a border layout manager.Created by dovari. } } The example uses a mix of layout managers.setLayout(new BoxLayout(basic. The manager calculates the necessary heights.Y_AXIS)).sudheerkiran@gmail. JPanel topPanel = new JPanel(new BorderLayout(0. we must set it's maximum size. Two labels and a separator. basic. JPanel textPanel = new JPanel(new BorderLayout()) . It has a vertical box layout manager. JPanel basic = new JPanel().com public static void main(String[] args) { new TipOfDay().blogspot. 0)). textPanel. . This component has a border layout manager by default. BoxLayout.. add(basic). The basic panel is added to the default JDialogcomponent. This is the very bottom panel.add(pane). If we want to have a panel. For more information http://www. The zero value is ignored.. topPanel.setMaximumSize(new Dimension(450. Simply we put four panels into the vertically organized basic panel. that is not greater than it's components.

e.setMaximumSize(new Dimension(450. Java Swing Events Events are an important part in any GUI program. there are three participants: • • • event source event object event listener The Event source is the object whose state changes. . All GUI applications are event-driven.. 20. Event source object delegates the task of handling an event to the event listener. The check box is shown in the boxPanel panel. window manager. But they can be generated by other means as well.The text pane component is added to the center area of the border layout manager. It is left aligned. It generates Events. as we wanted. Events are generated mainly by the user of an application. Exactly. The bottom panel displays two buttons. Why is that? It is because the flow layout manager puts some space to between the component and the edge as well. The Event object (Event) encapsulates the state changes in the event source. In the event model. It has a right aligned flow layout manager.blogspot. The Event listener is the object that wants to be notified. . In order to show the buttons on the right edge of the dialog. 0)).RIGHT)). timer. the panel must stretch horizontally from the beginning to the end. An application reacts to different event types which are generated during it's life. Other components have 25px. It takes all space left.computertech-dovari.LEFT..g. JPanel bottom = new JPanel(new FlowLayout(FlowLayout. JPanel boxPanel = new JPanel(new FlowLayout(FlowLayout. 0)). For more information http://www. internet connection. The flow layout manager has a 20px horizontal gap.

blogspot. FocusEvent.Date.util.Created by dovari. import javax. that has happened. when we click on the button or select an item from list. import java.Calendar.DefaultListModel. an event object is created.ActionEvent. An event object When something happens in the application. Java uses Event Delegation Model.Locale.event.swing. we will analyze an ActionEventin more detail. Each of them is created under specific conditions. import java.JList.util.awt. Event object has information about an event. import Event handling in Java Swing toolkit is very powerful and flexible. For more information http://www. import javax.util. import java.ActionListener.swing.awt. import java.JFrame. import java.text. An ActionEvent. We specify the objects that are to be notified when a specific event occurs. import javax.DateFormat. There are several types of events. . For example.sudheerkiran@gmail.swing.computertech-dovari.event. import javax. In the next example.ComponentEvent etc.

150).swing. panel.JPanel. public EventObject() { setTitle("Event Object").setLayout(null). model = new DefaultListModel().blogspot. 220. For more information http://www. list. .setBounds(150. private DefaultListModel model. list = new JList(model). JButton ok = new JButton("Ok").computertech-dovari. public class EventObject extends JFrame { private JList list. JPanel panel = new JPanel().import javax.

format(date).ACTION_PERFORMED) model.getSource(). For more information http://www.getDefault(). locale).getClass().Created by dovari. 25).setBounds(30.blogspot. 80. Date date = new Date().sudheerkiran@gmail.addElement(" Event Id: ACTION_PERFORMED"). 35.isEmpty() ) model.computertech-dovari.getID() == ActionEvent.getTimeInstance(DateFormat. String s = ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Locale locale = . if ( !model.addElement(" Source: " + source).getName(). ok.clear(). if (event.addElement(" Time: " + s). String source = event.SHORT. model. model.

getModifiers().int mod = event. StringBuffer buffer = new StringBuffer(" Modifiers: "). } }). panel.SHIFT_MASK) > 0) buffer. if ((mod & ActionEvent. model.append("Meta ").ALT_MASK) > 0) buffer.add(ok). For more information http://www.addElement(buffer).CTRL_MASK) > 0) buffer.blogspot. if ((mod & ActionEvent. if ((mod & ActionEvent. if ((mod & ActionEvent.append("Shift ").append("Alt ").com .computertech-dovari.META_MASK) > 0) buffer.append("Ctrl ").

we have an event parameter. that has occured. setLocationRelativeTo(null). the id of the event.add(list). Here we get the time. So we must format it appropriately. public void actionPerformed(ActionEvent event) { Inside the action listener. The data will be the time. the event source and the modifier keys. } } The code example shows a button and a list. when the event occured.setTimeInMillis(event. setDefaultCloseOperation(EXIT_ON_CLOSE). 250). we are talking about an ActionEvent class. information about the event is displayed in the list. setSize(420. when the event occured. } public static void main(String[] args) { new EventObject(). add(panel).computertech-dovari. In our case it is an ActionEvent.blogspot. In our .Created by dovari. cal. For more information http://www. If we click on the button. setVisible(true). The method returns time value in milliseconds.sudheerkiran@gmail. It is the instance of the event.getWhen()).com panel.

It is a bitwise-or of the modifier constants.getSource(). Figure: Event Object Implementation There are several ways.String source = event. In our case the source is a JButton.getClass(). • • • Anonymous inner class Inner class Derived class For more information http://www.blogspot. if ((mod & ActionEvent.SHIFT_MASK) > 0) buffer.getModifiers(). model. int mod = event. We get the modifier keys. Here we add the name of the source of the event to the list.addElement(" Source: " + source).append("Shift ").com . how we can implement event handling in Java Swing toolkit. Here we determine.getName().computertech-dovari. whether we have pressed a Shift key.

computertech-dovari. public class SimpleEvent extends JFrame { public SimpleEvent() { setTitle("Simle Event").ActionEvent.setLayout(null). import javax.JPanel. panel. import java.event.sudheerkiran@gmail.swing.event.Created by Anonymous inner class We will illustrate these concepts on a simple event example.blogspot.swing. import java. JButton close = new JButton("Close").com .JFrame.awt. import javax.swing. import javax.ActionListener. JPanel panel = new JPanel().JButton. For more information http://www.awt.

50. setSize(300. 80. } }). panel.close. setDefaultCloseOperation(EXIT_ON_CLOSE). } public static void main(String[] args) { new SimpleEvent(). close. setVisible(true). add(panel). setLocationRelativeTo(null).blogspot. 25).exit(0).com .computertech-dovari.add(close).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.setBounds(40. 200). } For more information http://www.

computertech-dovari. the events are sent to the event target. Here we register an action listener with the button. This way. import javax. In this code. we use an anonymous inner class. import } In this example. close.awt.JPanel.sudheerkiran@gmail.event. Inner class Here we implement the example using an inner ActionListener class.swing. The event target in our case is ActionListener class. The button is the event source.swing. import javax. import . For more information http://www.Created by dovari.ActionListener. JButton close = new JButton("Close"). } }). import javax.event.JButton.swing. we have a button that closes the window upon clicking.ActionEvent. It will generate events.awt.exit(0).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.blogspot.JFrame.

80.blogspot.setLayout(null).setBounds(40. close. 25). 200).add(close). panel. close.addActionListener(listener). JPanel panel = new JPanel(). setLocationRelativeTo(null).public class InnerClass extends JFrame { public InnerClass() { setTitle("Using inner class"). add(panel). JButton close = new JButton("Close"). 50. For more information . panel.computertech-dovari. ButtonListener listener = new ButtonListener(). setSize(300. . setVisible(true). } } public static void main(String[] args) { new InnerClass(). class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) For more information http://www.exit(0).com setDefaultCloseOperation(EXIT_ON_CLOSE). } } ButtonListener listener = new ButtonListener().computertech-dovari.blogspot. close. Here we have a non anonymous inner class.Created by dovari. } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.addActionListener(listener).

import javax.exit(0). A derived class implementing the listener The following example will derive a class from a component and implement an action listener inside the class. import .swing.{ System.event.awt. import javax.blogspot. import java. } } The button listener is defined here. import javax. public class UsingInterface extends JFrame { public UsingInterface() { For more information http://www.JFrame.swing.JButton.

setBounds(40. setSize(300. 80.blogspot. 200). setVisible(true). MyButton close = new MyButton("Close"). For more information setTitle("Using inner class").add(close).setText(text). 25). setLocationRelativeTo(null).sudheerkiran@gmail.computertech-dovari. . close.Created by dovari.setLayout(null). add(panel). setDefaultCloseOperation(EXIT_ON_CLOSE). JPanel panel = new JPanel(). } class MyButton extends JButton implements ActionListener { public MyButton(String text) { super. panel. 50.

computertech-dovari. we create a MyButton class.exit(0). It implements the ActionListener interface.blogspot. class MyButton extends JButton implements ActionListener { The MyButton class is extended from the JButton class. For more information http://www. This way. MyButton close = new MyButton("Close"). Here we create the MyButton custom class. } public void actionPerformed(ActionEvent e) { System.addActionListener(this). } } In this example. Here we add the action listener to the MyButton . } } public static void main(String[] args) { new UsingInterface(). addActionListener(this). which will implement the action listener. the event handling is managed within the MyButton class.

JFrame. import Multiple sources A listener can be plugged into several sources. import javax. import java.awt.blogspot. public MultipleSources() { For more information . import javax.BorderFactory.BorderLayout. import javax. import javax.swing. public class MultipleSources extends JFrame { JLabel statusbar.ActionListener.JLabel.swing. import javax.swing.awt.EtchedBorder.event.JPanel. import javax.swing. import java.event.swing.sudheerkiran@gmail.border. This will be explained in the next example.Created by dovari.awt.

RAISED)). 80.addActionListener(new ButtonListener()). 80.setLayout(null). 30. panel. open. 25). For more information http://www. JButton find = new JButton("Find").setBounds(40. JButton close = new JButton("Close").setTitle("Multiple Sources"). statusbar = new JLabel(" ZetCode").setBounds( . 130.blogspot.createEtchedBorder( EtchedBorder. JButton open = new JButton("Open"). 25). open.addActionListener(new ButtonListener()). statusbar.addActionListener(new ButtonListener()). 80. close. find.setBounds(40. find.setBorder(BorderFactory. 80. 25). JPanel panel = new JPanel().computertech-dovari. close.

panel. setSize(400. .com JButton save = new JButton("Save"). setVisible(true). setDefaultCloseOperation(EXIT_ON_CLOSE). 180. BorderLayout.add(open). setLocationRelativeTo(null).SOUTH). 25).sudheerkiran@gmail. add(panel). panel. 300).blogspot. panel.add(find).addActionListener(new ButtonListener()).Created by dovari.add(save). } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { For more information http://www.setBounds(40.add(close). save. add(statusbar.computertech-dovari. panel. 80.

String label = o. The statusbar will display an informative message upon clicking on the button. open. For more information http://www.addActionListener(new ButtonListener()).getSource(). which button was pressed.getSource(). Each button will be registered against a ButtonListener class. statusbar.. JButton o = (JButton) e. Here we determine.. String label = o.getText().getText().addActionListener(new ButtonListener()).. . close.. } } We create four buttons and a . } } public static void main(String[] args) { new MultipleSources().computertech-dovari.setText(" " + label + " button clicked").JButton o = (JButton) e.blogspot. . .ActionEvent. import java. Figure: Multiple Sources Multiple listeners We can register several listeners for one event.event. import java. import java. For more information http://www.sudheerkiran@gmail.setText(" " + label + " button clicked") We update the statusbar.Created by dovari.util.BorderFactory.Calendar. import java. import javax.blogspot.swing.ActionListener.awt.awt.computertech-dovari.BorderLayout.event.

import javax.computertech-dovari. private static int count = 0. import javax. For more information http://www.swing.swing.SpinnerNumberModel.border.import javax. statusbar = new JLabel("0").swing.swing.swing. JPanel panel = new JPanel().swing.JPanel.SpinnerModel. import javax.JFrame.EtchedBorder.JSpinner. public class MultipleListeners extends JFrame { private JLabel statusbar. import javax. public MultipleListeners() { setTitle("Multiple Listeners"). import javax.swing.JLabel.blogspot. private JSpinner spinner.JButton.swing. import . import javax.

addActionListener(new ButtonListener1()).blogspot. SpinnerModel yearModel = new SpinnerNumberModel(currentYear. add. JButton add = new JButton("+"). spinner = new JSpinner(yearModel).sudheerkiran@gmail. add. 1). 80. . currentYear .NumberEditor(spinner.setBorder(BorderFactory.RAISED)).getInstance().get(Calendar. statusbar. Calendar calendar = Calendar.createEtchedBorder( EtchedBorder.setEditor(new JSpinner. 25). For more information http://www.YEAR). panel.setBounds(40.Created by dovari.setLayout(null). add.computertech-dovari. "#")). int currentYear = calendar.addActionListener(new ButtonListener2()). currentYear + 100.100.

BorderLayout. setVisible(true). add(statusbar. 30.SOUTH). add(panel). 25). setLocationRelativeTo(null).spinner.computertech-dovari. 200).setBounds(190. } class ButtonListener1 implements ActionListener { public void actionPerformed(ActionEvent e) { Integer val = (Integer) spinner.setValue(++val). setSize(300. 80.getValue().add(spinner).add(add).com .blogspot. setDefaultCloseOperation(EXIT_ON_CLOSE). panel. panel. spinner. } For more information http://www.

blogspot. add. } } public static void main(String[] args) { new MultipleListeners().addActionListener(new ButtonListener1()).100. we have a button.setText(Integer. We register two button .sudheerkiran@gmail. spinner and a statusbar.computertech-dovari.toString(++count)). We use two button listeners for one event. how many times we have clicked on the button. currentYear .addActionListener(new ButtonListener2()). For more information } class ButtonListener2 implements ActionListener { public void actionPerformed(ActionEvent e) { statusbar. SpinnerModel yearModel = new SpinnerNumberModel(currentYear. add.Created by dovari. The statusbar will show. One click of a button will add one year to the spinner component and update the statusbar. } } In this example.

com .blogspot. "#")).NumberEditor(spinner. Figure: Multiple Listeners Removing listeners The Java Swing toolkit enables us to remove the registered listeners.setEditor(new JSpinner.event.awt. 1). spinner = new JSpinner(yearModel). We use a year model for the spinner. max values and the step. Integer val = (Integer) spinner.ActionListener. Here we increase the year number. spinner.computertech-dovari.currentYear + 100. min.getValue().event.ActionEvent. The SpinnerNumberModel arguments are initial value. import java. Here we create the spinner component. For more information http://www.setValue(++val). We remove the thousands separator. import java.awt. spinner.

import import java. private JCheckBox active.Created by dovari. public RemoveListener() { setTitle("Remove listener"). import javax.sudheerkiran@gmail.swing. import javax.awt.JPanel.swing.swing.JFrame. private JButton add.ItemEvent. private static int count = 0. private ButtonListener . import java. public class RemoveListener extends JFrame { private JLabel text.computertech-dovari. For more information http://www. import javax.JLabel.event.blogspot.swing.JCheckBox.event. import javax.

25). active. 30.blogspot.} else { add. 140.isSelected()) { add. 30. active. panel.addActionListener(buttonlistener).setBounds(160. active = new JCheckBox("Active listener").com .JPanel panel = new JPanel(). buttonlistener = new ButtonListener().computertech-dovari. For more information http://www.removeActionListener(buttonlistener). add.setBounds(40. 25).addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent event) { if (active. 80.setLayout(null). add = new JButton("+"). } } }).

add(active). text. 200). add(panel).add(text). panel. setDefaultCloseOperation(EXIT_ON_CLOSE). 80. 80.add(add). } class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { .computertech-dovari. panel.setBounds(40. panel.blogspot.Created by dovari. setVisible(true).com text = new JLabel("0"). } } For more information http://www.sudheerkiran@gmail. setSize(310. 25). setLocationRelativeTo(null).toString(++count)).setText(Integer.

public static void main(String[] args) { new RemoveListener(). if (active. A button. whether the check box is selected.removeActionListener(buttonlistener). We need a reference to it. By toggling the check box. For more information http://www. } We determine.blogspot.} else { add. we add or remove the listener for a button.computertech-dovari. We have to create a non anonymous . Then we add or remove the listener. check box and a label. } } We have three components on the panel. buttonlistener = new ButtonListener().addActionListener(buttonlistener).isSelected()) { add. if we want to later remove it.

swing.event.ComponentListener.swing.JLabel.ComponentEvent. import javax.computertech-dovari. import Figure: Remove listener Moving a window The following example will look for a position of a window on the screen.swing. import javax.Font. import java.sudheerkiran@gmail.JFrame. import java. import java.awt. public class MovingWindow extends JFrame implements ComponentListener { For more information http://www.awt.awt.blogspot.Created by dovari.

setFont(new Font("Serif". For more information http://www. 25).BOLD.BOLD. 25). Font. panel. labely. labelx. labelx = new JLabel("x: "). private JLabel labely.setBounds(20. JPanel panel = new JPanel().setLayout(null). labely.add(labely). 45. 60.add(labelx).setFont(new Font("Serif". 20.private JLabel labelx. labelx. 60. panel. . 14)). panel.computertech-dovari.blogspot. 14)). labely = new JLabel("y: "). public MovingWindow() { setTitle("Moving window").setBounds(20.

getY(). 200). addComponentListener(this). int y = e.getX().computertech-dovari.setText("y: " + y). } public void componentShown(ComponentEvent e) { For more information http://www. setDefaultCloseOperation(EXIT_ON_CLOSE). labelx. setVisible(true). } public void componentResized(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { int x = e.getComponent().com add(panel) .blogspot. setLocationRelativeTo(null).getComponent().setText("x: " + x). setSize(310.Created by dovari. labely.

To get the window position. that are available in the ComponentListener. if we do not use them.setFont(new Font("Serif". that we have to implement all four methods.computertech-dovari. } } The example shows the current window coordinates on the panel.getComponent(). We make the font bigger. Font. Even. Notice. 14)).com .getComponent(). int x = e.BOLD. Here we get the x and the y positions. we use theComponentListener labelx. int y = e.} public void componentHidden(ComponentEvent e) { } public static void main(String[] args) { new MovingWindow().blogspot. For more information http://www.getX().getY(). the default one is a bit small.

using a Figure: Moving a window Adapters Adapters are convenient classes.JLabel. import java.event. that we actually need. Adapter is a class that implements all necessary methods. The following example is a rewrite of the previous one.computertech-dovari. import javax. Even if we did not use them.ComponentEvent. import javax. we had to implement all four methods of aComponentListener class. We then use only those methods. where we have more than one method to implement.Font.Created by dovari.ComponentAdapter.JFrame. We can use adapters in situations. To avoid unnecessary coding. There is no adapter for a button click . we can use adapters.awt.event.blogspot.sudheerkiran@gmail.swing. import java. For more information http://www. Because there we have only one method to implement.swing.awt. They are empty.awt. In the previous code example. TheactionPerformed() method. import java.

labely = new JLabel("y: ").import javax.BOLD.setFont(new Font("Serif". public class Adapter extends JFrame { private JLabel labelx. panel.BOLD. For more information http://www. 25). public Adapter() { setTitle("Adapter"). 14)). 20. 60.setFont(new Font("Serif". labely.JPanel. private JLabel labely. .swing. Font.blogspot. labelx. labelx. JPanel panel = new JPanel(). labelx = new JLabel("x: "). 14)).computertech-dovari.setLayout(null).setBounds(20.

add(labelx). panel. 60. } class MoveAdapter extends ComponentAdapter { public void componentMoved(ComponentEvent e) { int x = e. setVisible(true).getY().com labely. setSize(310.blogspot. 45. int y = e. add(panel). .computertech-dovari.Created by dovari. panel.getComponent().add(labely).getComponent().sudheerkiran@gmail. 25). setDefaultCloseOperation(EXIT_ON_CLOSE).setText("x: " + x).setBounds(20.getX(). setLocationRelativeTo(null). addComponentListener(new MoveAdapter()). 200). For more information http://www.

com .setText("y: " + y). labely. } } This example is a rewrite of the previous one.getY().getComponent(). class MoveAdapter extends ComponentAdapter { public void componentMoved(ComponentEvent e) { int x = e. int y = e.blogspot.getComponent().getX(). addComponentListener(new MoveAdapter()). } } For more information http://www.setText("x: " + x). } } public static void main(String[] args) { new Adapter().labely. Here we use the ComponentAdapter.setText("y: " + y). labelx. Here we register the component listener.computertech-dovari.

Dialogs are important means of communication between a user and a computer program. import java. A typical modeless dialog is a find text dialog. In Java Swing toolkit. What type of dialog to use. we can create two kinds of dialogs. where to start the finding of the particular text.blogspot. Custom dialogs are dialogs. They save programmer's time and enhance using some standard behaviour. A dialog is used to input data. modify data. Modal and modeless. Modal dialogs block input to other top level windows.) It is handy to have the ability to move the cursor in the text control and define. created by the programmer. There are two basic types of dialogs. import java.awt. we define the componentMoved() . change the application settings etc. depends on the circumstances. receiving input .Font. no other operation should be permitted. Standard dialogs preedefined dialogs available in the Swing toolkit. Java Swing dialogs Dialog windows or dialogs are an indispensable part of most modern GUI applications. These are dialogs for common programming tasks like showing Inside the MoveAdapter inner class. It is a sample about dialog. While choosing a file to open. For more information http://www. (Like in Eclipse IDE.Modeless dialogs allow input to other windows. loading and saving files etc. In a computer application a dialog is a window which is used to "talk" to the application. Custom dialogs and standard dialogs.computertech-dovari. A simple custom dialog In the following example we create a simple custom dialog. An open file dialog is a good example of a modal dialog.Created by dovari. found in most GUI applications.awt.Dimension. They are based on the JDialog class. usually located in the help menu. A dialog is defined as a conversation between two or more persons. All the other methods are left empty. For example JColorChooser or JFileChooser.

ImageIcon. import javax.swing.event.swing. import javax. import java.swing.BoxLayout. import .ActionListener.JMenu.awt.JButton.JDialog.swing. import javax. import java.computertech-dovari. import javax.swing.awt.import java.event. For more information http://www.event. import javax.ActionEvent.JMenuBar.swing.JLabel.KeyEvent. class AboutDialog extends JDialog { public AboutDialog() { setTitle("About Notes"). import javax. import javax. import javax.blogspot.swing.awt.swing. import javax.

sudheerkiran@gmail. add(Box. label.setAlignmentX(0. name. add(label).computertech-dovari. JLabel label = new JLabel(icon). add(name). 50))). 10))). ImageIcon icon = new ImageIcon("notes.BOLD. add( . Font.5f).createRigidArea(new Dimension(0.5f). close. JButton close = new JButton("Close").23").setAlignmentX(0.Created by dovari.setFont(new Font("Serif". 10))). 13)).addActionListener(new ActionListener() { For more information http://www. name. JLabel name = new JLabel("Notes.createRigidArea(new Dimension(0. BoxLayout.createRigidArea(new Dimension( setLayout(new BoxLayout(getContentPane().png").Y_AXIS)). 1.blogspot. add(Box.

} } public class SimpleDialog extends JFrame { For more information http://www. add(close).public void actionPerformed(ActionEvent event) { dispose().blogspot.5f).com . 200). setLocationRelativeTo(null). close. } }).APPLICATION_MODAL).computertech-dovari. setDefaultCloseOperation(DISPOSE_ON_CLOSE). setSize(300. setModalityType(ModalityType.setAlignmentX(0. public SimpleDialog() { setTitle("Simple Dialog"). JMenu help = new JMenu("Help"). JMenu file = new JMenu("File"). } For more information http://www. help. about.VK_F). ad. . JMenuBar menubar = new JMenuBar().setVisible(true).VK_H).add(about).blogspot.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { AboutDialog ad = new AboutDialog().setMnemonic(KeyEvent.setMnemonic(KeyEvent. JMenuItem about = new JMenuItem("About"). file.Created by dovari.computertech-dovari.

setVisible(true).}).com . 200). For more information http://www. } public static void main(String[] args) { new SimpleDialog(). setJMenuBar(menubar). setSize(300.blogspot. menubar. setLocationRelativeTo(null). menubar.add(file).computertech-dovari. } } The sample code will popup a small dialog box. class AboutDialog extends JDialog { The custom dialog is based on the JDialog class. The dialog will display an icon a text and one close button.add(help). setDefaultCloseOperation(EXIT_ON_CLOSE).

awt. import java.sudheerkiran@gmail. Figure: Simple custom dialog Message boxes Message boxes provide information to the user. Here we set the defaul close operation. from the menu of the main frame. import java.computertech-dovari.setVisible(true).awt.event.awt.GridLayout. import java.event. ad. Here we make the dialog modal.Created by setModalityType(ModalityType. setDefaultCloseOperation(DISPOSE_ON_CLOSE).ActionListener. AboutDialog ad = new AboutDialog().APPLICATION_MODAL).com . For more information http://www. Here we display the about dialog.blogspot.ActionEvent. .JOptionPane. panel. import javax. panel = new JPanel(). JButton warning = new JButton("Warning").swing.import javax.blogspot.swing. import javax. public MessageBoxes() { setTitle("Message Boxes"). 2)).JFrame. public class MessageBoxes extends JFrame { private JPanel panel. import javax. JButton question = new JButton("Question").JButton.JPanel.setLayout(new GridLayout(2. JButton error = new JButton("Error").swing.computertech-dovari. For more information http://www.

warning.WARNING_MESSAGE). } }). JOptionPane. "A deprecated call". question.blogspot. "Could not open file".com JButton information = new JButton("Information").addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { For more information http://www.showMessageDialog(panel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JOptionPane. } }).Created by dovari.computertech-dovari. "Error". JOptionPane. "Warning".addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { .showMessageDialog(panel. error.sudheerkiran@gmail.ERROR_MESSAGE).

JOptionPane.quit?".INFORMATION_MESSAGE). } }). panel. information.add(warning). "Question". panel. add(panel).QUESTION_MESSAGE). "Download completed". panel.showMessageDialog(panel.add(error). JOptionPane.add(information). } }).com . For more information http://www.showMessageDialog(panel.blogspot. panel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JOptionPane. JOptionPane.add(question).computertech-dovari. "Are you sure to "Question".

JOptionPane.setLayout(new GridLayout(2. "Could not open file".com setSize(300. 200). setLocationRelativeTo(null). that will popup message boxes. We use a GridLayout layout manager to organize buttons.showMessageDialog(panel.Created by dovari.blogspot. . JButton question = new JButton("Question"). JButton error = new JButton("Error"). Here are the four buttons. For more information http://www.sudheerkiran@gmail. warning and information message boxes. } public static void main(String[] args) { new MessageBoxes(). 2)). JButton information = new JButton("Information"). setVisible(true). JButton warning = new JButton("Warning"). } } The example shows an error.computertech-dovari. that we will use. panel. setDefaultCloseOperation(EXIT_ON_CLOSE).

blogspot. JOptionPane. To create a message box.computertech-dovari. The message type is determined by the constant we choose. message text. Available constants are: • • • • ERROR_MESSAGE WARNING_MESSAGE QUESTION_MESSAGE INFORMATION_MESSAGE Figure: Message boxes For more information http://www. We provide the component name."Error".com . title and a message type.ERROR_MESSAGE). we call the showMessageDialog static method of the JOptionPane class.

import javax.swing.awt.computertech-dovari.BufferedReader.JScrollPane. import javax. import java.blogspot. import .swing. import java.JButton.swing.swing. import java.File. import Figure: Message boxes JFileChooser JFileChooser is a standard dialog for selecting a file from the file import import For more information http://www.JPanel. import javax. import java. import java. import java.Created by dovari.swing. import javax.ImageIcon.awt.BorderLayout.

FileFilter. public class FileChooserDialog extends JFrame { private JPanel panel. panel = new JPanel().JToolBar. For more information http://www.swing.import javax. JToolBar toolbar = new JToolBar(). ImageIcon open = new ImageIcon("open.FileNameExtensionFilter.filechooser.swing.computertech-dovari.filechooser. JButton openb = new JButton(open). import javax. public FileChooserDialog() { setTitle("FileChooserDialog").setLayout(new BorderLayout()). private JTextArea . panel.swing.swing. import javax.blogspot.JTextArea. import javax.png").

setText(text). For more information http://www.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JFileChooser fileopen = new JFileChooser().blogspot. "Open file"). fileopen.addChoosableFileFilter(filter).com .showDialog(panel.getSelectedFile().com openb. area.Created by dovari. "c"). toolbar.add(openb). int ret = fileopen.sudheerkiran@gmail. FileFilter filter = new FileNameExtensionFilter("c files".APPROVE_OPTION) { File file = fileopen. } } }). if (ret == JFileChooser. String text = readFile(file).computertech-dovari.

area. 10)). 10. } public String readFile (File file) { StringBuffer fileBuffer = null.getViewport(). add(toolbar.NORTH). JScrollPane pane = new JScrollPane().com . 300). setSize(400.setBorder(BorderFactory. panel.blogspot. For more information http://www.computertech-dovari. setVisible(true). add(panel).createEmptyBorder(10.createEmptyBorder(10. BorderLayout.setBorder(BorderFactory.add(area).area = new JTextArea(). 10)). panel. 10. setLocationRelativeTo(null).add(pane). 10. pane. setDefaultCloseOperation(EXIT_ON_CLOSE). 10.

close().toString(). while ((line = String fileString = null. } For more information http://www.getProperty("line. fileString = fileBuffer. BufferedReader brd = new BufferedReader (in).separator")).append(line + System. } in. } return fileString. String line = null.sudheerkiran@gmail. } catch (IOException e ) { return null.computertech-dovari. fileBuffer = new StringBuffer() .com .Created by dovari.blogspot. try { FileReader in = new FileReader (file).readLine()) != null) { fileBuffer.

showDialog(panel. String text = readFile(file).APPROVE_OPTION. In our case. This is the constructor of the file chooser dialog.setText(text). } } The code example will demonstrate how to use a file chooser dialog in order to load file contents into the text area component. "c"). the return value is equal toJFileChooser. if (ret == . we will have c files with extension .addChoosableFileFilter(filter).getSelectedFile(). For more information http://www. JFileChooser fileopen = new JFileChooser().public static void main(String[] args) { new FileChooserDialog().computertech-dovari. int ret = fileopen. Here we show the file chooser dialog. Upon clicking on the open file button.c. FileFilter filter = new FileNameExtensionFilter("c files". area.blogspot. "Open file"). Here we define the file filter. We have also the default All files option.APPROVE_OPTION) { File file = fileopen. fileopen. } Here we get the name of the selected file. For more information http://www. import java.awt.BorderLayout. import java. import .ActionEvent.event. import java. Figure: JFileChooser dialog JColorChooser JColorChooser is a standard dialog for selecting a color.awt. We read the contents of the file and set the text into the textarea.Color.computertech-dovari.event.awt.Created by dovari.blogspot.

JPanel. public class ColorChooserDialog extends JFrame { private JPanel .swing. public ColorChooserDialog() { setTitle("ColorChooserDialog").JButton.swing. import javax.png").blogspot.swing.swing. private JPanel display. panel.JFrame. For more information http://www. import javax.JToolBar. panel = new JPanel(). import javax.ImageIcon. import javax.import javax.setLayout(new BorderLayout()).swing. import javax.swing. ImageIcon open = new ImageIcon("color.JColorChooser. import javax.computertech-dovari.

setBorder(BorderFactory.white).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JColorChooser clr = new JColorChooser(). add(panel). } }).setBackground(Color. toolbar. "Choose Color".sudheerkiran@gmail. Color color = clr.WHITE). openb. 30.createEmptyBorder(30. 50. 50)).showDialog(panel.add(display).blogspot. panel. JToolBar toolbar = new JToolBar(). Color. display = new JPanel().com .add(openb). For more information http://www.setBackground(color).computertech-dovari. JButton openb = new JButton(open). panel. display.Created by dovari.

The showDialog() method returns the selected color value.NORTH). This code shows a color chooser dialog. JColorChooser clr = new JColorChooser(). We will change the background color of the panel by selecting a color from the color chooser dialog. 300).setBackground(color). setVisible(true). Color. BorderLayout. we have a white panel.white).showDialog(panel.add(toolbar. We change the display panel background to the newly selected color. setLocationRelativeTo(null). "Choose Color".com .computertech-dovari.blogspot. display. } } In the example. Color color = clr. } public static void main(String[] args) { new ColorChooserDialog(). setSize(400. setDefaultCloseOperation(EXIT_ON_CLOSE). For more information http://www.

It does not react to input events. For more information http://www. list boxes etc. we will describe several useful components.Created by . images or Figure: JColorChooser dialog Basic Swing components Swing components are basic building blocks of an application.computertech-dovari.sudheerkiran@gmail. check boxes. Swing toolkit has a wide range of various widgets. Everything a programmer needs for his job. In this section of the tutorial. JLabel Component JLabel is a simple component for displaying text. Buttons.blogspot.

awt.BorderLayout.swing. import java. import java.JFrame.Font. import java.swing.JPanel. import javax.awt. import java. public class MyLabel extends JFrame { private Toolkit toolkit. import javax. public MyLabel() { setTitle("No Sleep").com . import javax. import javax.computertech-dovari.JLabel.swing.awt.BorderFactory.awt.swing.awt.blogspot.Dimension. String lyrics = "<html>It's way too late to think of<br>" + For more information http://www.Color.import java.Toolkit.

world<br>" + "<br>" + "I've always been too late<br>" + "To see what's before me<br>" + "And I know nothing sweeter than<br>" + For more information "Someone I would call now<br>" + "And neon signs got tired<br>" + "Red eye flights help the stars out<br>" + "I'm safe in a corner<br>" + "Just hours before me<br>" + "<br>" + "I'm waking with the roaches<br>" + "The world has surrendered<br>" + "I'm dating ancient ghosts<br>" + "The ones I made friends with<br>" + "The comfort of fireflies<br>" + "Long gone before daylight<br>" + "<br>" + "And if I had one wishful field tonight<br>" + "I'd ask for the sun to never rise<br>" + "If God leant his voice for me to speak<br>" + "I'd say go to bed.Created by .blogspot.

add(panel). label. world<br>" + "Sleep in peace</html>".blogspot. 50. JPanel panel = new JPanel(). panel. BorderLayout.PLAIN. panel. 10)). Font.CENTER). 14))."Champaign from last New Years<br>" + "Sweet music in my ears<br>" + "And a night full of no fears<br>" + "<br>" + "But if I had one wishful field tonight<br>" + "I'd ask for the sun to never rise<br>" + "If God passed a mic to me to speak<br>" + "I'd say stay in bed.setForeground(new Color(50. 10. For more information http://www.add(label. panel.createEmptyBorder(10. JLabel label = new JLabel(lyrics).setLayout(new BorderLayout( . 10)).computertech-dovari. label.setFont(new Font("Georgia".setBorder(BorderFactory. 25)). 10.

width .setVisible(true).com . setLocation((screensize. We can use html tags in JLabel component. } public static void main(String[] args) { MyLabel mylabel = new MyLabel(). we show lyrics of no sleep song from cardigans. We use the <br> tag to separate pack(). For more information http://www. Dimension screensize = toolkit.computertech-dovari. } } In our example. setDefaultCloseOperation(EXIT_ON_CLOSE).getScreenSize().height .blogspot. We create a panel and set a BorderLayout manager.getWidth())/2. 10)).setLayout(new BorderLayout(10. panel. (screensize.Created by dovari. JPanel panel = new JPanel().sudheerkiran@gmail. mylabel. toolkit = getToolkit().getHeight())/2).

pack(). add(panel). We also change the foreground color. BorderLayout. We put 10px around the label. . so that all components are visible. 25)). panel.setForeground(new Color(50. 10)). which will resize the window. panel. For more information http://www. 14)).computertech-dovari. 14 px tall. 10.PLAIN. We set it's font to plain georgia.setBorder(BorderFactory. 50. 10. The panel is added to the frame component.CENTER).createEmptyBorder(10. label. Here we create the label component. Font.setFont(new Font("Georgia".add(label. We put the label into the center of the panel.JLabel label = new JLabel(lyrics). We call the pack() method.blogspot.

toggle visibility of a toolbar etc. If the checkbox is Figure: JLabel JCheckBox JCheckBox is a widget that has two .computertech-dovari. it is represented by a tick in a box. A checkbox can be used to show/hide splashscreen at startup.Created by dovari. For more information http://www.sudheerkiran@gmail. It is a box with a label. On and Off.blogspot.

true).blogspot.swing. checkbox. import javax.event. import javax.JFrame.swing.JCheckBox.createRigidArea(new Dimension(15.swing.import java. JCheckBox checkbox = new JCheckBox("Show Title".addActionListener(this).awt. import java.Box. import javax.computertech-dovari. public class CheckBox extends JFrame implements ActionListener { public CheckBox() { setLayout(new BoxLayout(getContentPane().com .awt. 20))).swing. import java. add(checkbox). import javax.ActionEvent. BoxLayout. checkbox. add(Box. For more information http://www.Y_AXIS)).setFocusable(false).Dimension.ActionListener.awt.event.BoxLayout.

com setSize(280.Created by dovari. setDefaultCloseOperation(JFrame.sudheerkiran@gmail. 200).getTitle() == "") { this. setResizable(false).EXIT_ON_CLOSE).setTitle("Checkbox example"). For more information .blogspot. setLocationRelativeTo(null). } public static void main(String[] args) { new CheckBox().computertech-dovari. setTitle("CheckBox example"). } public void actionPerformed(ActionEvent e) { if (this.setTitle(""). } else { this. setVisible(true).

so we go without the focus. We provide text and state. In this example. setLayout(new BoxLayout(getContentPane().Y_AXIS)). Here we have a constructor for the checkbox.createRigidArea(new Dimension(15.} } } Our code example shows or hides the title of the window depending on it's state. } Here we toggle the title of the window.setFocusable(false). true). We have disabled the focus for the checkbox. The rectangle around the text looks . checkbox.blogspot. so that the checkbox is not too close to the corner. BoxLayout.setTitle(""). we use a BoxLayout layout manager. if (this. 20))). JCheckBox checkbox = new JCheckBox("Show Title". } else { this.computertech-dovari.setTitle("Checkbox example"). For more information http://www. add(Box.getTitle() == "") { this. We put some space there.

blogspot.swing.computertech-dovari.swing. For more information http://www. import javax. Our example will show a volume control.swing.JFrame.Box. import javax.swing.swing. import java. import javax.Created by dovari.JPanel.swing. import javax. import .com Figure: JCheckBox JSlider JSlider is a component that lets the user graphically select a value by sliding a knob within a bounded interval. import java.ImageIcon. import javax.awt.BorderFactory. import javax.swing.BorderLayout.JLabel.awt.BoxLayout.Dimension.sudheerkiran@gmail.

import javax.png")).com .getSystemResource("mute.png")).event. public class Slider extends JFrame { private JSlider slider. public Slider() { setTitle("JSlider").png")). import javax.swing.png")).ChangeEvent.getSystemResource("med.swing.blogspot.getSystemResource("max.computertech-dovari. setDefaultCloseOperation(EXIT_ON_CLOSE). ImageIcon max = new ImageIcon(ClassLoader. private JLabel label.event. import javax. ImageIcon mute = new ImageIcon(ClassLoader.ChangeListener.getSystemResource("min.swing.JSlider. ImageIcon min = new ImageIcon(ClassLoader. ImageIcon med = new ImageIcon(ClassLoader. For more information http://www.

setPreferredSize(new Dimension(150.createEmptyBorder(40.X_AXIS)). } else if (value > 0 && value <= 30) { label. setLayout(new BorderLayout()).Created by dovari. 40)). slider = new JSlider(0. 40.setBorder( .add(Box. panel. panel.setIcon(min). panel. 30)).setLayout(new BoxLayout(panel. } else { For more information http://www.getValue(). 150. slider.setIcon(mute).computertech-dovari.createHorizontalGlue()).com JPanel panel = new JPanel().setIcon(med). 0). slider. 40.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent event) { int value = slider. } else if (value > 30 && value < 80) { label. BoxLayout.sudheerkiran@gmail. if (value == 0) { label.

JLabel. add(panel. } } }).com .add(Box.createHorizontalGlue()). setLocationRelativeTo(null).add(Box.add(slider). BorderLayout.createRigidArea(new Dimension(5.blogspot. pack(). } public static void main(String[] args) { For more information http://www. panel. panel. panel.computertech-dovari.CENTER). label = new JLabel(mute.CENTER). panel. 0))).setIcon(max).add(label).label.

left and right.createHorizontalGlue()).addChangeListener(new ChangeListener() { .computertech-dovari. slider. This is a JSlider constructor. 40)). we show a JSlider and a JLabel.X_AXIS))..getSystemResource("mute. Here we create an image icon. we change the icon on the label component. button. slider = new JSlider( Slider button = new Slider(). maximum value and current value. We creare a 40px border around the panel. ImageIcon mute = new ImageIcon(ClassLoader. We put resizable space to bo both sides.setLayout(new BoxLayout(panel. BoxLayout.png")). 150.setBorder(BorderFactory. . 40. By dragging the slider. It is to prevent JSlider from growing to unnatural sizes. panel. 40. }).Created by dovari. } } In the code example. For more information http://www.setVisible(true). The parameters are minimum value. 0). panel.sudheerkiran@gmail. Panel component has a horizontal BoxLayout.add(Box..createEmptyBorder(40.

which appears at the user's request.awt.ItemEvent.awt. For more information http://www.ActionListener.blogspot.Dimension. 0))).computertech-dovari. then the combo box includes an editable field into which the user can type a value. panel. Figure: JSlider JComboBox Combobox is a component that combines a button or editable field and a drop-down list.add(Box.createRigidArea(new Dimension(5.awt.Component. The user can select a value from the drop-down . We place a 5px rigid space between the two components. import java.awt. import java. when the slider is at the end position.event. we determine the current slider value and update the label accordingly. import java. import java.We add a ChangeListener to the slider.event.ItemListener. Inside the listener.event. If you make the combo box editable. import java.awt. They are too close to each other. import java.event.

final String[] images = { For more information http://www.blogspot.swing. import javax.swing.swing. "Stefan Zweig". "Tom Wolfe" }. ItemListener { final String[] authors = { "Leo Tolstoy". import import javax.JDialog.LineBorder. "Honore de Balzac".JButton. "Boris Pasternak".swing. "John Galsworthy".Created by dovari.BoxLayout.border. import javax.Box.ImageIcon. import javax.swing. import .swing. public class ComboBox extends JDialog implements ActionListener. import javax.swing. import javax.JLabel.computertech-dovari.swing.sudheerkiran@gmail.

jpg".Y_AXIS)).jpg")). display.blogspot.CENTER_ALIGNMENT). private JButton button = null. public ComboBox() { setLayout(new BoxLayout(getContentPane()."tolstoy. "pasternak.jpg". display.getSystemResource("balzac. "galsworthy.jpg". "zweig.computertech-dovari.jpg". 127)).jpg" }. private JLabel display = null. add(Box. display. 35))). private JComboBox combobox = null. For more information http://www. "balzac. ImageIcon icon = new ImageIcon( ClassLoader.setPreferredSize(new Dimension(100. display = new JLabel().createRigidArea(new Dimension(0. 127)). .setAlignmentX(Component.setMaximumSize(new Dimension(100.jpg". "wolfe.

add(button). button. 15))).com display. button.createGrayLineBorder()).setBorder( .blogspot. add(combobox). 15))).computertech-dovari. combobox = new JComboBox(authors).createRigidArea(new Dimension(0.setPreferredSize(new Dimension(140.setAlignmentX(Component.addItemListener(this). 22)).setMaximumSize(new Dimension(140. add(Box. combobox. 22)). setTitle("JComboBox"). setSize(300. combobox.sudheerkiran@gmail. add(display).setSelectedIndex(-1). add(Box. 300).Created by dovari.createRigidArea(new Dimension(0.CENTER_ALIGNMENT). combobox. button = new JButton("Close"). For more information http://www. combobox.addActionListener(this).

com .DISPOSE_ON_CLOSE).setDefaultCloseOperation(JDialog.setIcon(new ImageIcon( ClassLoader. setVisible(true). } public static void main(String[] args) { new ComboBox(). } public void actionPerformed(ActionEvent e) { System. For more information http://www.computertech-dovari. } public void itemStateChanged(ItemEvent e) { if (e. display.getSelectedIndex(). setLocationRelativeTo(null). int index = combo.getSystemResource(images[index]))).getStateChange() == ItemEvent.getSource().blogspot.SELECTED) { JComboBox combo = (JComboBox) e.exit(0).

The button closes the window. we get the selected index of the combobox and set an appropriate icon for the label. combobox.setSelectedIndex(-1). no item to be selected. The display area is a simple } } } In our example. combobox = new JComboBox(authors). If we provide -1 as an argument in thesetSelectedIndex() method. The selected item is an index to the array of images. ItemListener { This is a dialog based application example.addItemListener(this). For more information .Created by dovari. If we select a name. The constructor of the JComboBox takes a string array of novelists. We add an ItemListener to our combobox. an image is displayed in the label.blogspot. display = new JLabel().sudheerkiran@gmail. a combobox and a button. A label. public class ComboBox extends JDialog implements ActionListener. combobox. We have six names of famous novelists in our combobox. In the event handler. we have three components.

The JProgressBar widget provides a horizontal or vertical progress bar. import java.swing.ActionListener. import javax. The initial and minimum values are 0. import javax.awt.Figure: JComboBox JProgressBar A progress bar is a widget that is used.blogspot. import . import java.awt.computertech-dovari.event. It is animated so that the user knows. that our task is progressing. and the maximum is 100. For more information http://www.awt.swing. when we process lengthy tasks.Dimension.BorderFactory.event.

Created by

import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.Timer;

public class ProgressBar extends JFrame {

ActionListener updateProBar; Timer timer; JProgressBar progressBar; JButton button;

public ProgressBar() {


JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));

For more information

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

progressBar = new JProgressBar();

progressBar.setMaximumSize(new Dimension(150, 20)); progressBar.setMinimumSize(new Dimension(150, 20)); progressBar.setPreferredSize(new Dimension(150, 20));


panel.add(progressBar); panel.add(Box.createRigidArea(new Dimension(0, 20)));

button = new JButton("Start"); button.setFocusable(false); button.setMaximumSize(button.getPreferredSize());

updateProBar = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) {

For more information

Created by

int val = progressBar.getValue(); if (val >= 100) { timer.stop(); button.setText("End"); return; }

progressBar.setValue(++val); } };

timer = new Timer(50, updateProBar);

button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (timer.isRunning()) { timer.stop(); button.setText("Start");

} else if (button.getText() != "End") { timer.start();

For more information

button.setText("Stop"); }

} });

panel.add(button); add(panel);

pack(); setDefaultCloseOperation(EXIT_ON_CLOSE); setResizable(false); setLocationRelativeTo(null); setVisible(true);


public static void main(String[] args) {

new ProgressBar();

For more information

Created by

} }

The example displays a progress bar and a button. The button starts and stops the progress.

progressBar = new JProgressBar(); Here we create the JProgressBar. The minimum value is 0, maximum 100 and the initial value is 0. These are the default values.

progressBar.setMaximumSize(new Dimension(150, 20));

progressBar.setMinimumSize(new Dimension(150, 20));

progressBar.setPreferredSize(new Dimension(150, 20)); These lines are for design purposes only. I want my examples to look nice. The default height on my box was only 14px which looked bad.

progressBar.setAlignmentX(0f); This line aligns both progress bar with the button. To the left.

panel.add(Box.createRigidArea(new Dimension(0, 20))); Here we put some rigid space between the two components.

button.setFocusable(false); Focus looks bad, better disable it.

timer = new Timer(50, updateProBar); The timer object launches updateProBar listener every 50ms. Inside that listener, we check, if the progress bar reached the value 100 and stop the timer, or update the progress bar.

if (timer.isRunning()) {

For more information



} else if (button.getText() != "End") {



} Clicking on the button starts or stops the progress. The text of the button is updated dynamically. It can have Start, Stop or End String values.

Figure: JProgressBar

JToggleButton is a button that has two states. Pressed and not pressed. You toggle between these two states by clicking on it. There are situations where this functionality fits well.

import java.awt.Color;

For more information

ActionEvent.event. import javax.Created by dovari.swing. import javax. import javax.ActionListener.Box.BoxLayout.awt. private JToggleButton . import java.swing.JToggleButton.swing.swing.swing.event. public ToggleButton() { For more information http://www. private JToggleButton green. import java.LineBorder. import javax.border. import javax. private JPanel display.sudheerkiran@gmail. import javax.computertech-dovari. import javax. public class ToggleButton extends JDialog implements ActionListener { private JToggleButton import java.awt.blogspot.

computertech-dovari.X_AXIS)). green. JPanel bottom = new JPanel().getMaximumSize()).setLayout(new BoxLayout(bottom.setLayout(new BoxLayout(leftPanel.blogspot. bottom.setMaximumSize(green. 20.addActionListener(this). blue = new JToggleButton("blue").addActionListener(this). red = new JToggleButton("red").Y_AXIS)). red. green = new JToggleButton("green").createEmptyBorder(20. BoxLayout. 20)).setMaximumSize(green. red.setBorder(BorderFactory. 20. For more information http://www.getMaximumSize()). leftPanel. bottom. .addActionListener(this). BoxLayout. blue. JPanel leftPanel = new JPanel().setTitle("JToggleButton").

0))).add(display).add(Box.Created by dovari.add(red) leftPanel. display.createRigidArea(new Dimension(20.createRigidArea(new Dimension(25. display. leftPanel.add(leftPanel). leftPanel. add(bottom) For more information http://www.add(Box.setPreferredSize(new Dimension(110. setResizable(false).createRigidArea(new Dimension(25. display.createGrayLineBorder()).setBackground(Color. bottom. pack(). leftPanel. display = new JPanel().com . leftPanel.setBorder(LineBorder. 7))).add(green).add(Box. 110)).add(blue).computertech-dovari. 7))). bottom. bottom.

int blue = color.getRed(). } public static void main(String[] args) { new ToggleButton().setLocationRelativeTo(null).computertech-dovari.getGreen(). For more information http://www. int red = color. setDefaultCloseOperation(JDialog.getActionCommand() == "red") { if (red == 0) { red = 255.getBackground(). setVisible(true).com . } public void actionPerformed(ActionEvent e) { Color color = display. int green = color.DISPOSE_ON_CLOSE). if (e.getBlue().blogspot.

sudheerkiran@gmail. } } if (e. } } if (e.blogspot. } } For more information http://www. } else { green = 0.Created by dovari.getActionCommand() == "green") { if (green == 0) { green = 255. } else { blue = 0.getActionCommand() == "blue") { if (blue == 0) { blue = } else { red = .computertech-dovari.

getGreen().getMaximumSize()). display. Here we create a toggle button and set an action listener to it. left panel and display panel. red. We make all three buttons of equal size. blue. int green = color. In the actionPerformed method. red = new JToggleButton("red").getBackground(). we use horizontal BoxLayout manager.getRed().getMaximumSize()).addActionListener(this). Color color = display. green and blue parts of the color value. int blue = color. green. The bottom panel is use to organize the left and display panels.getBlue(). The background color will depend on which togglebuttons we have pressed. The toggle buttons will toggle the red. red. we determine the current red. For this.blogspot.setMaximumSize(green.setMaximumSize(green.setBackground(setCol).Color setCol = new Color(red. This time we use vertical BoxLayout manager. For more information http://www. We set the background color of the display panel to black. green. Panels are bottom . The left panel will holt three toggle buttons. int red = color. blue).computertech-dovari. blue parts of the display background color. } } The example has three panels and three toggle buttons.

Here a new color is created and the display panel is updated to a new color.computertech-dovari.getActionCommand() == "red") { if (red == 0) { red = 255. } } We determine. and update the color part of the RGB value accordingly.blogspot. blue). display.sudheerkiran@gmail. Color setCol = new Color(red.setBackground(setCol). which button was toggled. green. Figure: JToggleButton For more information http://www.Created by . } else { red = if (e.

swing. import javax.BorderFactory. import javax. import javax. import java. import javax. check boxes.JList. It allows the user to select one or more items.JFrame.awt. list boxes etc. import javax.Font.computertech-dovari.sliders. we will describe several useful components. import java. import .ListSelectionEvent. import javax.Basic Swing components II Swing components are basic building blocks of an application.JScrollPane.BorderLayout.JPanel.UIManager.awt. import javax.swing. Buttons.JLabel.swing.swing. In this section of the tutorial.GraphicsEnvironment. Swing toolkit has a wide range of various widgets.blogspot.Dimension.awt. JList Component JList is a component that displays a list of objects.awt. For more information http://www.swing. import java.swing. Everything a programmer needs for his job.swing.swing. import java.

JPanel panel = new JPanel(). setDefaultCloseOperation(EXIT_ON_CLOSE).sudheerkiran@gmail.createEmptyBorder(20.event.getLocalGraphicsEnvironment(). public List() { setTitle("List").com . panel. 20. 20)). GraphicsEnvironment ge = GraphicsEnvironment. panel.setLayout(new BorderLayout()). private JList import javax. For more information http://www.ListSelectionListener.computertech-dovari.setBorder(BorderFactory.Created by dovari.swing. 20. public class List extends JFrame { private JLabel label.blogspot.

For more information http://www. label. label = new JLabel("Aguirre. pane. add(label.getViewport().setFont(font). } } }).com .PLAIN. pane.getSelectedValue(). panel. BorderLayout. JScrollPane pane = new JScrollPane().getAvailableFontFamilyNames().SOUTH). 12). 12)). Font font = new Font(name. der Zorn Gottes").computertech-dovari.String[] fonts = ge. Font.setFont(new Font("Serif". Font. 200)).add(pane).getValueIsAdjusting()) { String name = (String) list.PLAIN. label. list = new JList(fonts).setPreferredSize(new Dimension(250.blogspot.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (!e.add(list). list.

pack(). setVisible(true). The list component contains a list of all available font family names on our system. we will display a JList and a JLabel components.computertech-dovari. we have . } public static void main(String[] args) { new List().com add(panel). GraphicsEnvironment ge = GraphicsEnvironment. } } In our example. the label will be displayed in a font.getLocalGraphicsEnvironment(). setLocationRelativeTo(null).blogspot. For more information http://www.Created by dovari. If we select an item from the list.sudheerkiran@gmail.

list = new JList(fonts). JLabel component is not scrollable by default.getValueIsAdjusting()) { This code is quite confusing. Events in list selection are grouped. We create a JList . Why this weird name? No idea.PLAIN. label. public void valueChanged(ListSelectionEvent e) { if (!e. We must put the list into the JScrollPane to make it scrollable. We receive events for both selecting and deselecting. We get the selected item and set a new font for the label. Interesingly.blogspot. Here we obtain all possible font family names on our system.getViewport(). To filter only the selecting events. String name = (String) list.computertech-dovari. Font font = new Font(name.getSelectedValue(). Font.setFont(font).add(list).getAvailableFontFamilyNames(). For more information http://www. JScrollPane pane = new JScrollPane().String[] fonts = ge. 12). we use the getValueIsAdjusting() method. pane.

import javax.JScrollPane. we use JScrollPane .com Figure: JList JTextArea component A JTextArea is a multi-line text area that displays plain text.BorderLayout.BorderFactory.swing.swing.blogspot. import java. For more information http://www. For this task.JPanel.swing. import java. import javax. The component does not handle scrolling.sudheerkiran@gmail.Dimension. import javax. It is lightweight component for working with text. import javax.computertech-dovari.awt.JFrame.Created by dovari.swing.awt.

20)).swing. panel. area.JTextArea.setLineWrap(true). area. JScrollPane pane = new JScrollPane(). 8. setDefaultCloseOperation(EXIT_ON_CLOSE). 8.createEmptyBorder(8. JPanel panel = new JPanel(). 20.setLayout(new BorderLayout()).setBorder(BorderFactory.createEmptyBorder(20. JTextArea area = new JTextArea().blogspot. panel.import javax.setBorder(BorderFactory. 20. area.setWrapStyleWord(true).computertech-dovari. 8)). For more information http://www. public class TextArea extends JFrame { public TextArea() { setTitle("JTextArea").com .

com .blogspot.computertech-dovari. } public static void main(String[] args) { new TextArea(). JTextArea area = new JTextArea(). 300)).com pane. This is the constructor of the JTextArea component. setVisible(true). panel.getViewport().Created by dovari. setLocationRelativeTo(null). setSize(new Dimension(350.sudheerkiran@gmail.add(pane). For more information http://www. add(panel). } } The example shows a simple JTextArea component with an excerpt from Martin Luther King speech.add(area).

how is line going to be wrapped. we put the JTextArea component into the JScrollPane component. 8. To make the text scrollable.setBorder(BorderFactory.getViewport(). lines will be wrapped at word boundaries. if they are too long to fit the width. 8.setWrapStyleWord(true).area. Make the lines wrapped. In our case. Figure: JTextAra JTextPane component For more information http://www.setLineWrap(true).computertech-dovari.add(area).com . whitespaces. We put some border around the text in the component.blogspot. area. Here we specify. pane. area. 8)).createEmptyBorder(8.

IOException. public class TextPane extends JFrame { public TextPane() { setTitle("JTexPane").swing.swing. For more information http://www.swing. import import java.JScrollPane.BorderFactory.swing.awt. import JTextPane component is a more advanced component for working with text. import . import java.JTextPane.Dimension. It can display also html documents.JPanel.awt. setDefaultCloseOperation(EXIT_ON_CLOSE). import javax.blogspot.sudheerkiran@gmail.JFrame. The component can do some complex formatting operations over the text.BorderLayout.computertech-dovari.swing.Created by dovari. import java. import javax.

setBorder(BorderFactory. panel.blogspot.setPage("File:///" + cd + "test. try { textpane.getProperty("user.setEditable(false).setContentType("text/html").out.html").setLayout(new BorderLayout()). JScrollPane pane = new JScrollPane().setBorder(BorderFactory. textpane. String cd = System. textpane. panel.computertech-dovari. 8.JPanel panel = new JPanel().com . } catch (IOException e) { System. 20. 20)). 8. 20. JTextPane textpane = new JTextPane().println("Exception: " + e).dir") + "/". For more information http://www. 8)).createEmptyBorder(8.createEmptyBorder(20. } textpane.

setVisible(true).add(textpane).getViewport().Created by dovari. 320)).sudheerkiran@gmail. setSize(new Dimension(380. } } This is the html code. setLocationRelativeTo(null).com pane. that we are loading into the JTextPane component. <html> <head> For more information http://www. The component does not handle scrolling.computertech-dovari. add(panel). } public static void main(String[] args) { new TextPane(). panel.add(pane) .

</p> <br> <pre> JScrollPane pane = new JScrollPane(). </pre> For more information http://www. JTextPane textpane = new JTextPane().com .setEditable(false). textpane.<title>A simple html document</title> </head> <body> <h2>A simple html document</h2> <p> <b>JTextPane</b> can display html documents.computertech-dovari.blogspot. textpane.setContentType("text/html").

String cd = System.Created by dovari. Here we determine the current working directory of the user.dir") + "/".getProperty("user. The html document is located there.html"). } catch (IOException e) { System. Example shows formatting capabilities of the component.setPage("File:///" + cd + "test. textpane.computertech-dovari. set the content of the component to be a html document and disable editing.sudheerkiran@gmail.setContentType("text/html"). try { textpane. For more information http://www. 2007</small> </body> </html> In our example we show a JTextPane component and load a html document.println("Exception: " + e).blogspot.setEditable(false). We create a JTextPane component. JTextPane textpane = new JTextPane().com .com <br> <small>The Java Swing tutorial.out. textpane.

and may invoke changes on the model. This enables efficient handling of data and using pluggable look and feel at runtime.} We load a html document into the pane. typically user actions.computertech-dovari. a view and a cotroller. A . The model represents the data in the application.blogspot. The idea is to separate the data access and business logic from data presentation and user interaction. And finally the controller processes and responds to events. The traditional MVC pattern divides an application into three parts. The view is the visual representation of the data. Figure: JTextPane Java Swing model architecture Swing engineers created the Swing toolkit implementing a modified Model View Controller design pattern. For more information http://www. by introducing an intermediate component: the controller.

com . It would be an overkill to work with models directly in such simple situations.getValue().Created by dovari. For Swing developer it means. the access to the model is done behind the scenes. For such notifications. public int getValue() { return getModel().blogspot. In the Swing toolkit. There are two kinds of models in Swing toolkit. } For example the getValue() method of the JSlider component. we have different kinds of events. that we often need to get a model instance in order to manipulate the data in the component.computertech-dovari. there are some methods that return data without the model. For example the JList component has ListDataEvent andListSelectionEvent. Instead. A list component keeps a list of items. We have only one single event (ChangeEvent) for all notifications coming from the component. the stateful notification is used. The data models handle data. it is displaying. a default one is created.sudheerkiran@gmail. To query the state of the model. they work with. For more complicated components. The developer does not need to work with the model directly. we have two kinds of notifications. For convenience. This modified MVC is sometimes called a separable model architecture. • • state models data models The state models handle the state of the component. For example the button component hasDefaultButtonModel model For more information http://www. But there are exceptions. If we do not set a model for a The Swing toolkit uses a modified MVC design pattern. Because of this. every component has it's model. The Swing has single UI object for both the view and the controller. the Swing tookit provides some convenience methods like the previous one. • • lightweight notification stateful notification The lightweight notification uses a ChangeListener class. For example the model keeps track whether the component is selected or pressed. Even the basic ones like buttons.

event.ActionListener.swing. that the default model is created at the construction of the component.ActionEvent. icon).awt. import javax. } If we look at the JButton. // initialize init(text.JCheckBox. import java. The following example illustrates the model for a JButton. We can manage only the state of the button. import javax.JLabel. ButtonModel The model is used for various kinds of buttons like push buttons.JButton. check . we find out.public JButton(String text.DefaultButtonModel.swing.swing.JFrame. radio boxes and for menu items.blogspot. import javax.computertech-dovari.event. import javax. import javax.swing. import source file.swing.awt. For more information http://www. because no data can be associated with a push button. Icon icon) { // Create the model setModel(new DefaultButtonModel()).

panel. true) .ChangeEvent.swing. public class ButtonModel extends JFrame { private JButton ok. import import javax. ok = new JButton("ok").JPanel. private JLabel armed.blogspot. JCheckBox cb = new JCheckBox("Enabled". private JLabel pressed. private JLabel enabled. JPanel panel = new JPanel(). For more information http://www. import javax.swing.computertech-dovari.ChangeListener.Created by dovari.event. public ButtonModel() { setTitle("ButtonModel").sudheerkiran@gmail.setLayout(null).event.

setBounds(40. if (model.setText("Enabled: true"). 30. 25).setText("Armed: true").blogspot. else pressed.setText("Pressed: false").setText("Armed: false"). else enabled.setText("Pressed: true"). ok. } For more information http://www.isPressed()) pressed.getModel().addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { DefaultButtonModel model = (DefaultButtonModel) ok. if ( .isEnabled()) enabled. if (model.ok.setText("Enabled: false").isArmed()) armed. else armed.computertech-dovari. 80.

else ok. }). enabled = new JLabel("Enabled: true"). 100.blogspot. 25).setBounds(40.isEnabled()) ok. armed = new JLabel("Armed: false"). 120. } }).setBounds(40.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (ok.computertech-dovari. armed. 90. 25). cb. . cb.setBounds(180.sudheerkiran@gmail. 90. For more information http://www. 25). 150. 25).Created by dovari.setEnabled(false). enabled. 90. pressed = new JLabel("Pressed: false").setEnabled(true).setBounds(40. 90.

panel.add(cb). 250). panel. setLocationRelativeTo(null). setVisible(true). add(panel). panel.blogspot. check box and three labels.add(armed).com . } public static void main(String[] args) { new ButtonModel(). Whether it is pressed. we have a button. panel. disabled or armed. setSize(350. } } In our example.panel.add(enabled).add(pressed). For more information http://www. The labels represent three properties of the button.computertech-dovari. setDefaultCloseOperation(EXIT_ON_CLOSE).add(ok).

So we change the state of the .computertech-dovari.isEnabled()) ok. DefaultButtonModel model = (DefaultButtonModel) ok.Created by dovari.sudheerkiran@gmail. public void setEnabled(boolean b) { if (!b && model. else ok.setEnabled(false).setEnabled(true).isRollover()) { model. else ok.getModel(). whether the button is enabled or not. we call the setEnable() file. if (ok.blogspot. Here we get the default button model. } For more information http://www. We query the model. To enable the ok button.addChangeListener(new ChangeListener() { We use a lightweight ChangeListener to listen for button state changes.isEnabled()) enabled.setText("Enabled: false"). We update the label accordingly.setText("Enabled: true"). Where is the model? The answer lies in the AbstractButton. The check box enables or disables the button. if (model.setRollover(false). .DefaultButtonModel. we the Swing toolkit works with a model.event. In the following code example we will use our own button model. import javax.event.ActionListener.super.blogspot.setEnabled(b).awt. model. import java.setEnabled(b). that internally. Figure: ButtonModel Custom ButtonModel In the previous example. } The answer is. import java.awt. For more information http://www. The setEnable() is another convenience method for programmers. import javax.ButtonModel. we used a default button model.swing.ActionEvent.

swing. panel. public class ButtonModel2 extends JFrame { private JButton ok. private JLabel armed.JCheckBox.swing.JFrame.swing.Created by dovari.computertech-dovari. For more information http://www. import javax.JLabel. import javax. import import . private JLabel enabled.setLayout(null).swing.blogspot.sudheerkiran@gmail.JPanel. import javax. private JLabel pressed. JPanel panel = new JPanel().swing.JButton. public ButtonModel2() { setTitle("ButtonModel").

ok = new JButton("ok"); JCheckBox cb = new JCheckBox("Enabled", true);

ok.setBounds(40, 30, 80, 25);

cb.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { if (ok.isEnabled()) ok.setEnabled(false); else ok.setEnabled(true); } });

cb.setBounds(180, 30, 100, 25);

enabled = new JLabel("Enabled: true"); enabled.setBounds(40, 90, 90, 25); pressed = new JLabel("Pressed: false"); pressed.setBounds(40, 120, 90, 25);

For more information

Created by


= new JLabel("Armed: false");

armed.setBounds(40, 150, 90, 25);

ButtonModel model = new DefaultButtonModel() { public void setEnabled(boolean b) { if (b) enabled.setText("Pressed: true"); else enabled.setText("Pressed: false");

super.setEnabled(b); }

public void setArmed(boolean b) { if (b) armed.setText("Armed: true"); else armed.setText("Armed: false");

super.setArmed(b); }

For more information

public void setPressed(boolean b) { if (b) pressed.setText("Pressed: true"); else pressed.setText("Pressed: false");

super.setPressed(b); }



panel.add(ok); panel.add(cb); panel.add(enabled); panel.add(pressed); panel.add(armed);


For more information

Created by

setSize(350, 250); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); }

public static void main(String[] args) { new ButtonModel2(); } } This example does the same thing as the previous one. The difference is that we don't use a change listener and we use a custom button model.

ButtonModel model = new DefaultButtonModel() { We create a button model and overwrite the necessary methods.

public void setEnabled(boolean b) {

if (b)

enabled.setText("Pressed: true");


enabled.setText("Pressed: false");

For more information


} We overwrite the setEnabled() method and add some functionality there. We must not forget to call the parent method as well to procede with the processing.

ok.setModel(model); We set the custom model for the button.

JList models
Several components have two models. The JList component has the following models: ListModel andListSelectionModel. The ListModel handles data. And the ListSelectionModel works with the GUI. The following example shows both models.

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent;

import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout;

For more information

Created by

import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel;

public class List extends JFrame {

private DefaultListModel model; private JList list;

public List() {

setTitle("JList models");

model = new DefaultListModel(); model.addElement("Amelie");

For more information

list.addElement("Fargo").com .setSelectionMode(ListSelectionModel.addElement("Aguirre. 2.blogspot.setLayout(new BoxLayout(rightPanel. list. panel. model. list = new JList(model). der Zorn Gottes").addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { For more information http://www. JPanel panel = new JPanel(). JPanel rightPanel = new JPanel(). list. 2)). BoxLayout.SINGLE_SELECTION). leftPanel.computertech-dovari. rightPanel. model.createEmptyBorder(2.addElement("Exorcist").Y_AXIS)). JPanel leftPanel = new JPanel().setBorder(BorderFactory.addElement("Schindler list").setLayout(new BoxLayout(panel. 2.model. model.setLayout(new BorderLayout()).X_AXIS)). BoxLayout.

} } } }).setLeadSelectionIndex(index).getPoint()).showInputDialog("Rename item". if (text != null) newitem = text. model.Created by dovari.computertech-dovari. item). else return.sudheerkiran@gmail.locationToIndex(e.trim(). String text = JOptionPane. if (!newitem. For more information http://www. String newitem = if(e. newitem).blogspot.add(index.isEmpty()) { model.getSelectionModel().getElementAt(index).getClickCount() == 2){ int index = list. selmodel. ListSelectionModel selmodel = list.remove(index). Object item = .

20)). For more information http://www.setBorder(BorderFactory.setMaximumSize(removeall. add.createEmptyBorder(20. 20. JButton removeall = new JButton("Remove All"). 20. delete.add(list).setMaximumSize(removeall. leftPanel.showInputDialog("Add a new item"). pane. JButton delete = new JButton("Delete"). JButton add = new JButton("Add").getViewport().com .addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String text = JOptionPane.getMaximumSize()).blogspot.getMaximumSize()).getMaximumSize()). JButton rename = new JButton("Rename"). String item = null. leftPanel.add(pane).computertech-dovari.setMaximumSize(removeall. add. rename.JScrollPane pane = new JScrollPane().

computertech-dovari.trim(). delete.getMinSelectionIndex() if (text != null) item = text.getSelectionModel(). } }). } }).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { ListSelectionModel selmodel = list.addActionListener(new ActionListener() { For more information http://www. if (!item. if (index >= 0) model.blogspot.isEmpty()) model.remove(index). int index = selmodel.Created by . rename. else return.addElement(item).

int index = selmodel.showInputDialog("Rename item". item).trim().blogspot. if (text != null) { newitem = text.computertech-dovari. } else return. model. if (index == -1) return.public void actionPerformed(ActionEvent e) { ListSelectionModel selmodel = list. String text = . if (!newitem.getSelectionModel().getElementAt(index).getMinSelectionIndex().add(index.remove(index). } } }).isEmpty()) { model. For more information http://www. newitem). Object item = model. String newitem = null.

add(rename). rightPanel. } }).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { model. 0.Created by dovari.createRigidArea(new Dimension(0.add(delete).add(add). 20)).add(rightPanel). For more information http://www. rightPanel.clear(). panel. rightPanel. 0.4))).add( . rightPanel.add(removeall). rightPanel.add(Box.createRigidArea(new Dimension(0.4))).setBorder(BorderFactory. rightPanel.sudheerkiran@gmail.blogspot.createEmptyBorder(0.computertech-dovari.4))).add(leftPanel). rightPanel. panel.createRigidArea(new Dimension(0. rightPanel.add(Box.

We do not allow to input empty spaces into the list component.addElement("Aguirre.blogspot. 250).. setDefaultCloseOperation(EXIT_ON_CLOSE). We create a list model and add elements into it. model. The example is a bit larger. } public static void main(String[] args) { new List().computertech-dovari. setSize(350. setLocationRelativeTo(null). because we did some additional checks there. } } The example shows a list component and four buttons. The buttons control the data in the list component. .. model. model = new DefaultListModel().com . list = new JList(model).addElement("Amelie"). setVisible(true). der Zorn Gottes").add(panel). For more information http://www.

isEmpty()) model.getSelectionModel().com . we call the getSelectionModel() method This is a GUI work.g. 2. 2)). if (!item. 2. In order to delete an item from the list.computertech-dovari.SINGLE_SELECTION). if (text != null) item = text. ListSelectionModel selmodel = list.blogspot. list.addElement(item).sudheerkiran@gmail. So we must figure out the currently selected item.Created by dovari. it must be selected. The parameter of the constructor is the model. We create a list component. It makes no sense to add white spaces or null values into the list. if (index >= 0) model.remove(index). that contain at least one character other than white space. int index = selmodel.trim().setBorder(BorderFactory. We add only items that are not equal to null and are not empty. we have list.createEmptyBorder(2. e. so we use For more information http://www.setSelectionMode(ListSelectionModel. We also put some space around the list. This is the code. We put the list into the single selection mode. else return.getMinSelectionIndex(). that runs when we press the delete button. For this.

In a JTextPane component. So.BorderLayout.event. We called add().com .Dimension.awt. we have a StyledDocument for setting the style of the text data.event. And we used a list selection model in order to find out the selected item. import javax. For that we use the list data model. For more information http://www. remove() and clear() methods of the list data model to work with our data.a ListSelectionModel. import java.swing.ActionEvent.ActionListener. import java.awt.BorderFactory. Removing an item is working with data. Figure: List Models A document model This is an excellent example of a separation of a data from the visual representation. which is a GUI job. import java.computertech-dovari.awt. in our example we used both list models.blogspot.awt. import java.

StyleConstants.ImageIcon.swing.JButton. import javax.text. import import javax.blogspot. import javax.text. public DocumentModel() { setTitle("Document Model").JFrame.swing.JTextPane. import javax.swing. import javax.Created by dovari.sudheerkiran@gmail.Style. import javax. private JTextPane textpane.swing.swing.computertech-dovari.swing. public class DocumentModel extends JFrame { private StyledDocument doc.JToolBar. import javax.StyledDocument. For more information http://www. import javax. import .swing.

add(strib).png"). ImageIcon italic = new ImageIcon("italic.add(boldb).add(italb). JPanel panel = new JPanel(). add(toolbar. ImageIcon bold = new ImageIcon("bold. toolbar. ImageIcon underline = new ImageIcon("underline. toolbar.add(undeb).png"). JButton boldb = new JButton(bold).computertech-dovari.png").com . For more information http://www.setLayout(new BorderLayout()). JButton strib = new JButton(strike).blogspot.png").NORTH). toolbar. panel. toolbar. BorderLayout. ImageIcon strike = new ImageIcon("strike.JToolBar toolbar = new JToolBar(). JButton undeb = new JButton(underline). JButton italb = new JButton(italic).

setBorder(BorderFactory. style = textpane.Created by dovari.setUnderline(style. JScrollPane pane = new JScrollPane().createEmptyBorder(8.getStyledDocument().com panel. For more information http://www.computertech-dovari.setStrikeThrough(style. 20. 8. true). textpane = new JTextPane().createEmptyBorder(20. StyleConstants.addStyle("Italic".sudheerkiran@gmail. null). StyleConstants.addStyle("Underline". doc = . 20. 20)). null). true). textpane. true).setBorder(BorderFactory. null). style = textpane. StyleConstants. StyleConstants. 8. true).setItalic(style.addStyle("Bold". style = textpane. null).blogspot. 8)).setBold(style.addStyle("Strike". Style style = textpane.

computertech-dovari.getSelectionStart().getSelectionStart().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doc.getSelectionEnd() textpane. textpane.getSelectionStart(). textpane.boldb. false).com . } }). strib. italb.setCharacterAttributes(textpane. textpane.setCharacterAttributes(textpane.addActionListener(new ActionListener() { For more information http://www.getSelectionEnd() textpane.getSelectionStart(). } }). textpane.getStyle("Italic").getStyle("Bold").addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doc. false).blogspot.

} }).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doc. false). For more information http://www.getViewport().computertech-dovari.sudheerkiran@gmail.setCharacterAttributes(textpane. panel.add(pane).com . public void actionPerformed(ActionEvent e) { doc.Created by dovari.add(textpane).getSelectionStart().blogspot.getSelectionStart(). textpane.getStyle("Underline"). textpane. } }). textpane.getSelectionEnd() textpane.getStyle("Strike"). false).setCharacterAttributes(textpane. undeb. pane.getSelectionEnd() textpane.getSelectionStart().getSelectionStart().

Here we register a bold style for the text pane .getStyledDocument(). true). } public static void main(String[] args) { new DocumentModel(). } } The example has a text pane and a toolbar. In the toolbar. null). setLocationRelativeTo(null). A style is a set of text attributes. such as color. Here we get the styled document. size.blogspot.addStyle("Bold". we have four buttons. For more information http://www. The registered styles can be retrieved at any time. doc = textpane. which is a model for the text pane component.add(panel). that change attributes of the text. StyleConstants. setDefaultCloseOperation(EXIT_ON_CLOSE). setSize(new Dimension(380. setVisible(true). 320)). Style style = textpane.setBold(style.

getSelectionEnd() . Boolean value false means. Figure: Document model Drag and Drop in Swing In computer graphical user interfaces.getStyle("Bold"). the style and the boolean value doc.Created by dovari. where we apply the bold text. This means.blogspot. We get the length value by substracting the selection end and selection start values. length of the selection.textpane. the result is an underlined bold text.sudheerkiran@gmail. textpane. if the text is underlined and we make it bold.getSelectionStart(). we are not replacing an old style with a new one. The offset is the beginning of the text. textpane.computertech-dovari. drag-and-drop is the action of (or support for the action of) clicking on a virtual object and dragging it to a different location or onto another For more information http://www. The parameters are the offset.getSelectionStart().com .setCharacterAttributes(textpane. but we merge them. false). Here we change the attributes of the text.

A DataFlavor object provides information about the data being transferred. The transferred data can be of various type. In such cases. A Transferable encapsulates data being transferred. Drag and drop operation enables users to do complex things intuitively. The best way how to cope with this complexity is to create a small example for all situations.computertech-dovari. we drag and drop binary data. Usually. where the drag operation begins must have a DragSource object registered. And slowly make it to more complex examples. In .blogspot. The sheer amount of various classes involved with drag and drop operations in Java Swing toolkit might be overwhelming. or create various types of associations between two abstract objects. If we drag an image from one application to another. Data or some graphical objects.virtual object. we drag and drop a graphical component. we can drag and drop two things. it can be used to invoke many kinds of actions. A DropTarget is an object responsible for accepting drops in an drag and drop operation. (Wikipedia) Drag and drop functionality is one of the most visible aspects of the graphical user interface. Several Swing components have already a built-in support for drag and drop operations. a Swing programmer uses a TransferHandler to manage the drag and drop For more information http://www. The component. If we drag a tab in Firefox and move it to another place.

blogspot.swing.swing. We will work with built-in drag and drop support. setLayout(null).TransferHandler. public SimpleDnD() { setTitle("Simple Drag & Drop"). import javax.JButton.computertech-dovari. We will utilize aTransferHandler class. where there is no built-in support.JTextField. JButton button.Created by dovari.swing. For more information functionality. import javax. public class SimpleDnD extends JFrame { JTextField . import javax. A simple drag and drop example We will demonstrate a simple drag and drop example. the programmer has to create everything from scratch.swing.sudheerkiran@gmail. In situations. import javax.JFrame.

add(field). field. 50. button. 90.setDragEnabled(true).computertech-dovari. setDefaultCloseOperation(JFrame. setLocationRelativeTo(null). 25).blogspot. field = new JTextField(). For more information http://www. .EXIT_ON_CLOSE). 150.setBounds(200. 150). add(button). setSize(330. 25). 50.setTransferHandler(new TransferHandler("text")).setBounds(30. } public static void main(String[] args) { new SimpleDnD(). setVisible(true). button.button = new JButton("Button").

import java.MouseAdapter. The constructor takes a property name as a parameter. button. We can drag a text from the field and drop it onto the button.awt. We must enable . This time we will use an icon property.FlowLayout. we used a text property.setTransferHandler(new TransferHandler("text")). In the previous } } In our example we have a text field and a button. The text field has a built in support for dragging.blogspot. field. Figure: Simple drag & drop example Icon drag & drop Some of the Java Swing components do not have built in drag support.event.setDragEnabled(true). For more information http://www.sudheerkiran@gmail.awt.computertech-dovari. The TransferHandler is a class responsible for transfering data between components. JLabel component is such a component. We will drag and drop icons. import java.Created by dovari. We have to code the drag functionality ourselves.

com .ImageIcon.JLabel.JFrame.awt.blogspot. import javax.swing.awt.TransferHandler.swing. JPanel panel = new JPanel(new FlowLayout(FlowLayout. import javax.computertech-dovari. import javax.import java.event.swing.JComponent.JButton. public class IconDnD extends JFrame { public IconDnD() { setTitle("Icon Drag & Drop").swing. import javax.swing.MouseEvent. For more information http://www.swing. import java. import javax.MouseListener.JPanel. 15)).swing. import javax.LEFT. 50. import javax.event.

add(label1).png").com ImageIcon icon1 = new ImageIcon("sad.png"). For more information http://www. ImageIcon icon3 = new ImageIcon("crying. = new JLabel(icon3. JButton button = new JButton(icon2). label1.sudheerkiran@gmail. panel. MouseListener listener = new DragMouseAdapter(). JLabel.CENTER).setFocusable(false).computertech-dovari.setTransferHandler(new TransferHandler("icon")).addMouseListener(listener).CENTER). panel.blogspot. button. label1.setTransferHandler(new TransferHandler("icon")).Created by dovari.setTransferHandler(new TransferHandler("icon")).com . ImageIcon icon2 = new ImageIcon("plain.addMouseListener(listener). label2.add(button). JLabel label1 JLabel label2 = new JLabel(icon1. button. label2. JLabel.png").

exportAsDrag(c.computertech-dovari. pack().blogspot. handler. setVisible(true).COPY). e.getTransferHandler(). } } public static void main(String[] args) { new IconDnD(). } class DragMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent e) { JComponent c = (JComponent) e.EXIT_ON_CLOSE). TransferHandler.getSource(). } } For more information http://www. setLocationRelativeTo(null). add(panel).com . TransferHandler handler = c.add(label2).panel. setDefaultCloseOperation(JFrame.

button. we have two labels and a button.getSource(). In our case it is a label instance. label1.computertech-dovari.getTransferHandler(). We register a custom mouse adapter for both labels. handler. Each component displays an icon. Figure: Icon drag & drop example For more information http://www. Each of the three components has a TransferHandler class for an icon property. The two labels enable drag gestures. label2.setTransferHandler(new TransferHandler("icon")). TransferHandler handler = c.addMouseListener(listener). We get it's transfer handler object.exportAsDrag(c. MouseListener listener = new DragMouseAdapter(). The drag support is not enabled by default for the label.addMouseListener(listener).sudheerkiran@gmail. label1.Created by dovari. label2.COPY). We get the drag source. the button accepts a drop .setTransferHandler(new TransferHandler("icon")).setTransferHandler(new TransferHandler("icon")). The TransferHandler is needed for both drag sources and drag targets as well. e.blogspot. These code lines initiate the drag In the code example. And finally initiate the drag support with the exportAsDrag() method call. JComponent c = (JComponent) e. TransferHandler.

awt.Transferable.JScrollPane.swing.JList.swing.DefaultListModel. For more information http://www.datatransfer. import javax.TransferHandler. import javax. import .swing. There is a good reason for this.awt.swing. The comma separated text will be inserted into two or more rows.swing.datatransfer. One of them is a JList component. import java.JTextField. We don't know. import javax. or two or more rows.JFrame.DropMode.FlowLayout. import javax.JPanel. import java.swing.swing.blogspot. import javax. Text without a comma will go into one row.DataFlavor.Dimension. import java. import javax. So we must implement manually the drop support for the list component.Custom JList drop example Some components do not have a default drop support. import javax. import java. if the data will be inserted into one row.ListSelectionModel.awt. import javax.awt.swing.computertech-dovari.swing.

public ListDrop() { setTitle("ListDrop"). public class ListDrop extends JFrame { JTextField field. 150)).sudheerkiran@gmail. pane.setSelectionMode(ListSelectionModel.INSERT).setTransferHandler(new ListHandler()).com .blogspot. 15)).setDropMode(DropMode.SINGLE_SELECTION). For more information http://www. JScrollPane pane = new JScrollPane(). JList list = new JList(model).Created by dovari. list. JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT. list.setPreferredSize(new Dimension(180.computertech-dovari. list. model = new DefaultListModel(). DefaultListModel model.

setVisible(true).setPreferredSize(new Dimension(150.setDragEnabled(true). 25)).com . } private class ListHandler extends TransferHandler { public boolean canImport(TransferSupport support) { For more information http://www. field.add(pane). field.getViewport().blogspot. setDefaultCloseOperation(JFrame. add(panel). panel. panel.EXIT_ON_CLOSE). pack().add(field).add(list). pane.field = new JTextField(""). setLocationRelativeTo(null).computertech-dovari.

getTransferable().getTransferData(DataFlavor.blogspot. } For more information http://www.stringFlavor). } catch (Exception e) { return false.computertech-dovari. try { line = (String) transferable. String line. } return support.stringFlavor).isDataFlavorSupported(DataFlavor. } public boolean importData(TransferSupport support) { if (!canImport(support)) { return false. } Transferable transferable = .isDrop()) { return false.Created by if (!support.

trim()).setDropMode(DropMode. String[] data = line. list. int index = dl. If the text is comma separated. we have a text field and a list component. for (String item: data) { if (!item. If not. } } In the above example. } return true. The text in the text field can be dragged and dropped into the list.isEmpty()) model.getDropLocation().").DropLocation dl = (JList. the text will be inserted into one row. item. } } public static void main(String[] args) { new ListDrop().getIndex().DropLocation) support. the words will be split into rows.computertech-dovari.blogspot.split(". For more information http://www.add(index++.INSERT).com .JList.

list.isDrop()) { return false.getTransferable(). If the method returns Here we specify a drop mode. } return .INSERT specifies. } The importData() method transfers the data from the clipboard or from the drag and drop operation to the drop location. For more information http://www. public boolean importData(TransferSupport support) { . The DropMode.sudheerkiran@gmail. Transferable transferable = support. If we chose DropMode.computertech-dovari. we would drop new items onto the existing ones. that we are going to insert new items into the list component. public boolean canImport(TransferSupport support) { if (!support.Created by dovari. Here we filter out the clipboard paste operations and allow only String drop operations.setTransferHandler(new ListHandler()). We set a custom transfer handler class.INSERT.setDragEnabled(true).stringFlavor). field. } This method tests suitability of a drop operation.isDataFlavorSupported(DataFlavor..blogspot. We enable the drag support for the text field component. the drop operation is cancelled.

stringFlavor). String[] data = line.DropLocation dl = (JList. Figure: JList drop example The previous examples used components with built-in drag and drop support.split(".isEmpty()) model.add(index++. We retrieve our data. Next we are going to create a drag and drop functionality from scratch. for (String item: data) { if (!item.blogspot.").getIndex().computertech-dovari. For more information http://www. int index = dl.trim()). JList.DropLocation) support.The Transferable is the class. We retrieve the index. item. line = (String) transferable. where the data is bundled. } Here we split the text into parts and insert it into one or more rows. We get a drop location for the list. where the data will be inserted.getDropLocation().getTransferData( .

awt.awt.Color.DragSource. public class DragGesture extends JFrame implements DragGestureListener. import java. import java. DragGestureListener.awt. We will work with several classes needed to create a drag gesture.DnDConstants.Dimension. import java.awt.swing.awt.blogspot.Transferable.DataFlavor.awt.JPanel. import java. import javax. import Drag Gesture In the following example we will inspect a simple drag gesture.dnd. Transferable { For more information http://www.computertech-dovari.DragGestureListener. A DragSource. import javax.dnd. import java.Cursor. DragGestureEvent. import java.dnd.Created by dovari. import java.sudheerkiran@gmail.awt.dnd. Transferable.datatransfer.awt.datatransfer.awt. import .swing.DragGestureEvent. import java.

DnDConstants.setPreferredSize(new Dimension(120. pack().com .ACTION_COPY. For more information http://www.EXIT_ON_CLOSE). 15)). 120)). setDefaultCloseOperation(JFrame.LEFT. 50. panel.setBackground(Color. left.computertech-dovari.blogspot. add(panel). this).add(left). JPanel panel = new JPanel(new FlowLayout(FlowLayout. left.public DragGesture() { setTitle("Drag Gesture"). DragSource ds = new DragSource(). JPanel left = new JPanel().createDefaultDragGestureRecognizer( ds.

} For more information http://www.computertech-dovari. } public void dragGestureRecognized(DragGestureEvent event) { System. } public Object getTransferData(DataFlavor flavor) { return null. Cursor cursor = null.DefaultCopyDrop.ACTION_COPY) { cursor = DragSource.println("grag gesture"). } .startDrag(cursor. } public static void main(String[] args) { new DragGesture().com setLocationRelativeTo(null). setVisible(true).out.getDragAction() == DnDConstants. this).Created by dovari.sudheerkiran@gmail. if (event.

DragSource ds = new DragSource(). when we click on a component and move a mouse pointer. } public boolean isDataFlavorSupported(DataFlavor flavor) { return . The createDefaultDragGestureRecognizer() associates a drag source andDragGestureListener with a particular component.blogspot. The drag gesture is created. The example will show. The DragGestureListener will listen for drag gestures. Here we create a DragSource object and register it for the left panel. ds. The DragSource is the entity responsible for the initiation of the Drag and Drop operation. So the three necessary methods of the Transferable interface are left unimplemented. DnDConstants. The Transferablehandles data for a transfer operation. this). while the button is pressed.createDefaultDragGestureRecognizer(left. For more information http://www.ACTION_COPY. We will only demonstrate a drag gesture. In the example. } } This simple example demostrates a drag gesture. public class DragGesture extends JFrame implements DragGestureListener. Transferable { The DragGesture implements two interfaces.public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[0]. how we can create a DragSource for a component. we will not transfer any data.

The startDrag() method of the DragGestureEvent finally starts the drag operation.computertech-dovari. The cursor type and the Transferable object. We will specify two parameters. Cursor cursor = null.Created by dovari.ACTION_COPY) { cursor = public void dragGestureRecognized(DragGestureEvent event) { } The dragGestureRecognized() method responds to a drag gesture. } public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[0]. } For more information http://www. public Object getTransferData(DataFlavor flavor) { return . } event.getDragAction() == DnDConstants.startDrag(cursor. if (event.DefaultCopyDrop. this).

dnd. import java.awt. import java. we create a complex drag and drop example. import java.DragGestureListener. } The object that implements the Transferable interface must implement these three methods.awt. As I have already mentioned. import java. import java.datatransfer. we left these methods unimplemented for now. import java. import java.FlowLayout.public boolean isDataFlavorSupported(DataFlavor flavor) { return false.awt.awt.Dimension.awt.dnd.awt.dnd.UnsupportedFlavorException.dnd. import java.awt.awt.datatransfer.dnd. For more information http://www. import java.Color. We create a drag source a drop target and a transferable object.DropTarget. import java. import java.computertech-dovari.awt.awt.DnDConstants.DragGestureEvent. import java.DragSource. A complex drag and drop example In the following .DataFlavor.DropTargetAdapter.awt. import java.awt.Cursor.awt.

computertech-dovari.swing. import javax.sudheerkiran@gmail.blogspot.swing.Created by dovari.ActionListener. import import java. .event. public class ComplexExample extends JFrame implements DragGestureListener { JPanel panel. import javax.dnd. For more information http://www. public ComplexExample() { setTitle("Complex Example").awt. JPanel left.awt. panel = new JPanel(new FlowLayout(FlowLayout. 15)). import java.event. import javax.ActionEvent.JButton.JPanel. import javax.

setFocusable(false). left. openb.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JColorChooser clr = new JColorChooser(). 100)).setPreferredSize(new Dimension(100. Color. right. 100)).setBackground(Color.setBackground(color). left.JButton openb = new JButton("Choose Color"). } }).red). JPanel right = new JPanel(). Color color = clr. For more information http://www.blogspot. "Choose Color". right.setBackground(Color.setPreferredSize(new Dimension( .white).showDialog(panel.computertech-dovari.white). left = new JPanel(). openb. left.

sudheerkiran@gmail. setVisible(true). panel. panel. DnDConstants.getComponent().Created by new MyDropTargetListener(right).computertech-dovari. pack(). setLocationRelativeTo(null). add(panel).add(right). For more information http://www. panel. JPanel panel = (JPanel) .add(openb). this).createDefaultDragGestureRecognizer(left. } public void dragGestureRecognized(DragGestureEvent event) { Cursor cursor = null.blogspot. ds. DragSource ds = new DragSource().add(left).EXIT_ON_CLOSE). setDefaultCloseOperation(JFrame.

} For more information http://www.Color color = panel.blogspot. dropTarget = new DropTarget( .computertech-dovari.startDrag(cursor. null). DnDConstants. private JPanel panel.ACTION_COPY. public MyDropTargetListener(JPanel panel) { this. if (event. } class MyDropTargetListener extends DropTargetAdapter { private DropTarget dropTarget.panel = panel. } event.DefaultCopyDrop.getBackground(). new TransferableColor(color)).ACTION_COPY) { cursor = DragSource. this. true.getDragAction() == DnDConstants.

isDataFlavorSupported(TransferableColor. this.computertech-dovari.rejectDrop().Created by public void drop(DropTargetDropEvent event) { try { Transferable tr = event.dropComplete(true).getTransferData(TransferableColor.printStackTrace().colorFlavor)) { event.blogspot.colorFlavor).panel.getTransferable(). Color color = (Color) tr. event. } } For more information http://www.setBackground(color). if (event. } event.ACTION_COPY). } catch (Exception e) { e. return.acceptDrop(DnDConstants. .rejectDrop().sudheerkiran@gmail.

color = color.class. "A Color Object"). } For more information http://www. public TransferableColor(Color color) { this.stringFlavor. }.computertech-dovari.} public static void main(String[] args) { new ComplexExample(). } } class TransferableColor implements Transferable { protected static DataFlavor colorFlavor = new DataFlavor(Color.blogspot. Color color. protected static DataFlavor[] supportedFlavors = { . DataFlavor.

} public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException { if (flavor.Created by public DataFlavor[] getTransferDataFlavors() { return supportedFlavors.sudheerkiran@gmail.blogspot.equals(colorFlavor) || .stringFlavor)) return color. else throw new UnsupportedFlavorException(flavor).equals(DataFlavor. } public boolean isDataFlavorSupported(DataFlavor flavor) { if (flavor.computertech-dovari.stringFlavor)) return true. } For more information http://www. return false.equals(colorFlavor)) return color.equals(DataFlavor.toString(). else if (flavor.

The button displays a color chooser dialog and sets a color for the first panel.getTransferData(TransferableColor. public MyDropTargetListener(JPanel panel) { this. .isDataFlavorSupported(TransferableColor. We register a drop target listener with the right panel.colorFlavor). new TransferableColor(color)). A cursor and a Transferable object.startDrag(cursor. Transferable tr = event. new MyDropTargetListener(right).ACTION_COPY. dropTarget = new DropTarget(panel. We will add a drop target and a custom transferable object.panel = panel. } In the MyDropTargetListener we create a drop target object.colorFlavor)) { For more information http://www. The startDrag() method has two parameters. true.computertech-dovari. This example will enhance the previous one. The color can be dragged into the second panel. if (event. null).blogspot. Color color = (Color) tr.getTransferable().} The code example shows a button and two panels. event. this.

rejectDrop(). In the TransferableColor.Created by dovari.computertech-dovari. public Object getTransferData(DataFlavor flavor) For more information . In our case it is a color object. protected static DataFlavor colorFlavor = new DataFlavor(Color. this.stringFlavor.sudheerkiran@gmail. what data flavors we support. we reject it.class. In our case it is a custom defined color flavor and a pre-definedDataFlavor. If the conditions for a drag and drop operation are not fulfilled. Here we specify. }.blogspot. "A Color Object").setBackground(color).stringFlavor. we create a new DataFlavor object. } We get the data being transferred.acceptDrop(DnDConstants.panel. event. DataFlavor. return. protected static DataFlavor[] supportedFlavors = { colorFlavor. Here we set the color of the right panel.dropComplete(true). event.ACTION_COPY).

Figure: A complex example Painting in Swing For more information . else if (flavor. else throw new UnsupportedFlavorException(flavor). } Return an object for a specific data flavor.equals(DataFlavor.stringFlavor)) return color.toString().blogspot.throws UnsupportedFlavorException { if (flavor.computertech-dovari.equals(colorFlavor)) return color.

when we want to change or enhance an existing widget. 2D Vector Graphics There are two different computer graphics. curves or polygons to represent images. .computertech-dovari. Vector graphics is the use of geometrical primitives such as points. scaling. Both types of computer graphics have advantages and disadvantages. The painting is done within the paintComponent() method. In the painting process.blogspot. we use the painting API provided by the Swing toolkit. These primitives are created using mathematical equations.Created by dovari. The advantages of vector graphics over raster are: • • • smaller size ability to zoom indefinitely Painting is used. Or if we are creating a custom widget from scratch. filling or rotating does not degrade the quality of an image Types of primitives • • • • • • • points lines polylines polygons circles ellipses Splines Points For more information http://www.sudheerkiran@gmail. Vector and raster graphics. To do the painting. we use the Graphics2D object. Raster graphics represents images as a collection of pixels.

awt.Insets.Dimension.blogspot.swing.paintComponent(g).awt.JPanel. import javax. I used one point twice.computertech-dovari. import java. import java.swing. .JFrame. import javax.Color.awt. For more information http://www. import java. (Or I could not find it.Random.util. import java.The most simple graphics primitive is point.awt.Graphics. import java. public class Points extends JPanel { public void paintComponent(Graphics g) { super. import java. It is a single dot on the window. I used a drawLine() method.awt. there is no method to draw a point in Swing.) To draw a point.Graphics2D.

Created by

Graphics2D g2d = (Graphics2D) g;


for (int i=0; i<=1000; i++) { Dimension size = getSize(); Insets insets = getInsets();

int w = int h =

size.width - insets.left - insets.right; size.height - - insets.bottom;

Random r = new Random(); int x = Math.abs(r.nextInt()) % w; int y = Math.abs(r.nextInt()) % h; g2d.drawLine(x, y, x, y); } }

public static void main(String[] args) {

Points points = new Points();

For more information

JFrame frame = new JFrame("Points"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(points); frame.setSize(250, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } }

One point is difficult to observe. Why not paint 1000 of them. In our example, we do so. We draw 1000 blue points on the panel.

g2d.setColor(; We will paint our points in blue color.

Dimension size = getSize();

Insets insets = getInsets(); The size of the window includes borders and titlebar. We don't paint there.

int w =

size.width - insets.left - insets.right;

int h =

size.height - - insets.bottom;

Here we calculate the area, where we will effectively paint our points.

Random r = new Random();

int x = Math.abs(r.nextInt()) % w;

For more information

Created by

int y = Math.abs(r.nextInt()) % h; We get a random number in range of the size of area, that we computed above.

g2d.drawLine(x, y, x, y); Here we draw the point. As I already said, we use a drawLine() method. We specify the same point twice.

Figure: Points

A line is a simple graphics primitive. It is drawn using two points.

import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Graphics2D;

import javax.swing.JFrame; import javax.swing.JPanel;

For more information

public class Lines extends JPanel {

public void paintComponent(Graphics g) { super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g;

float[] dash1 = { 2f, 0f, 2f }; float[] dash2 = { 1f, 1f, 1f }; float[] dash3 = { 4f, 0f, 2f }; float[] dash4 = { 4f, 4f, 1f };

g2d.drawLine(20, 40, 250, 40);

BasicStroke bs1 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash1, 2f );

BasicStroke bs2 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash2, 2f );

For more information

Created by

BasicStroke bs3 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash3, 2f );

BasicStroke bs4 = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND, 1.0f, dash4, 2f );

g2d.setStroke(bs1); g2d.drawLine(20, 80, 250, 80);

g2d.setStroke(bs2); g2d.drawLine(20, 120, 250, 120);

g2d.setStroke(bs3); g2d.drawLine(20, 160, 250, 160);

g2d.setStroke(bs4); g2d.drawLine(20, 200, 250, 200);


For more information

public static void main(String[] args) {

Lines lines = new Lines(); JFrame frame = new JFrame("Lines"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(lines); frame.setSize(280, 270); frame.setLocationRelativeTo(null); frame.setVisible(true);

} }

In the example, we draw five lines. The first line is drawn using the default values. Other will have a different stroke. The stroke is created using the BasicStroke class. It defines a basic set of rendering attributes for the outlines of graphics primitives.

float[] dash1 = { 2f, 0f, 2f }; Here we create a dash, that we use in the stroke object.

BasicStroke bs1 = new BasicStroke(1, BasicStroke.CAP_BUTT,

BasicStroke.JOIN_ROUND, 1.0f, dash1, 2f ) This code creates a stroke. The stroke defines the line width, end caps, line joins, miter limit, dash and the dash phase.

For more information

we use the fillRect()method.JFrame.blogspot.awt. import javax.sudheerkiran@gmail. import . To fill rectangles with the current color.swing.Color. import java. we use the drawRect() method.awt.Graphics2D.swing. import javax.Graphics.JPanel.computertech-dovari. import Figure: Lines Rectangles To draw rectangles. For more information http://www.awt.Created by dovari.

90. 60). 60). 105. 90. 212.setColor(new Color(212. 90.drawRect(10. g2d.drawRect(250. g2d.drawRect(130. g2d. 90.paintComponent(g). 167. 15.blogspot. 90. g2d.drawRect(250. 90. 60). 60). 212)). g2d. 90. 105.drawRect(250. g2d. 195. g2d.setColor(new Color(125. 60). Graphics2D g2d = (Graphics2D) g. 60). 90.drawRect(10. 60). 60).drawRect(130. For more information http://www. g2d. 15. 15. g2d. g2d.public class Rectangles extends JPanel { public void paintComponent(Graphics g) { super.drawRect(10. 195. 90. 105. g2d. 195. g2d.drawRect(130.computertech-dovari. 90. 116)). 60). 60).fillRect(10. .

blogspot.sudheerkiran@gmail. g2d. 105.fillRect(10.computertech-dovari. g2d.fillRect(10.setColor(new Color(70. 123)).setColor(new Color(130. g2d. g2d. 98. 121.fillRect(250. g2d. g2d. 69)). 105.fillRect(130.Created by dovari. 60). 211. 60). 60).com g2d. 231)). g2d. g2d. 90. g2d. 60). 195.setColor(new Color(42. g2d. 60). 100.setColor(new Color(241.fillRect(130. 84)). . 179. 15. 146. 54)). 186)). 61)). 67. 195. 90. g2d. 60).setColor(new Color(217.fillRect(250. 90. 90. 15. g2d. 60). 90.fillRect(130. 105. 90.setColor(new Color(63.setColor(new Color(252. For more information http://www. g2d.

setLocationRelativeTo(null).add(rects).setDefaultCloseOperation(JFrame. } } In the example we draw nine colored rectangles. 195. 212.drawRect(10. . frame.g2d. 90.computertech-dovari. For more information http://www.blogspot. frame.setSize(360.setColor(new Color(31. 60). frame. JFrame frame = new JFrame("Rectangles"). g2d. 15.setColor(new Color(212.EXIT_ON_CLOSE). frame. 90. } public static void main(String[] args) { Rectangles rects = new Rectangles(). 60). g2d. 21. 300). 1)).fillRect(250. 212)).setVisible(true). frame.

60). we use the fillRect() .awt. g2d.sudheerkiran@gmail. import java. The first two parameters are the x and y values. . we can fill our graphics shapes with textures.computertech-dovari. We set the color of the outline of the rectangle to a soft gray color.awt. import java. we use the drawRect() method. For more information http://www.. Besides colors and gradients. The third and fourth are width and height. so that it does not interfere with the fill color. To draw the outline of the rectangle.awt.Created by dovari. 90.fillRect(10..blogspot.Graphics. import java. Figure: Rectangles Textures A texture is a bitmap image applied to the surface in computer graphics. To fill the rectangle with a color.Color.Graphics2D.

TexturePaint.computertech-dovari.Rectangle.image.IOException.swing. import java.awt. 212.awt. For more information http://www.BufferedImage. import javax.import java.awt.swing. public class Textures extends JPanel { public void paintComponent(Graphics g) { super.JPanel. import javax.setColor(new Color(212. import java. import javax.URL.ImageIO.paintComponent(g) .imageio. import java. import java.JFrame. 212)). Graphics2D g2d = (Graphics2D) g.

15. BufferedImage bimage2 = null. BufferedImage bimage5 = null. 60). URL url5 = ClassLoader. g2d. 60).png"). 60). 105. URL url3 = ClassLoader. For more information .sudheerkiran@gmail.getSystemResource("texture6. URL url6 = ClassLoader.png").getSystemResource("texture1.drawRect(130.png").png"). g2d.computertech-dovari.drawRect( g2d. 90. BufferedImage bimage4 = null. g2d. 90.getSystemResource("texture2.drawRect(250.getSystemResource("texture3. 60). g2d. 15.drawRect(130.blogspot. 90.drawRect(10. 90. URL url1 = ClassLoader.getSystemResource("texture4. URL url2 = ClassLoader. BufferedImage bimage3 = null. 60). BufferedImage bimage6 = null.png"). 15. BufferedImage bimage1 = null. 105.Created by dovari.png").getSystemResource("texture5. 90. 105.drawRect(250. g2d. 60). URL url4 = ClassLoader. 90.

Rectangle rect2 = new Rectangle(0. bimage6 = ImageIO. } catch (IOException ioe) { ioe.getHeight()). Rectangle rect3 = new Rectangle(0. bimage1. bimage3 = ImageIO. 0.getWidth(). } Rectangle rect1 = new Rectangle(0. bimage3.getHeight()).blogspot. bimage5 = ImageIO.getWidth(). bimage2. bimage2 = 0.getHeight()). bimage1. Rectangle rect4 = new Rectangle(0. 0. bimage4 = .getWidth().try { bimage1 = ImageIO. For more information http://www.

sudheerkiran@gmail.setPaint(texture2). bimage4. g2d. rect6). bimage5.getHeight()). 15.fillRect(130. bimage6. 0.getWidth(). TexturePaint texture1 = new TexturePaint(bimage1. rect5). 60). TexturePaint texture6 = new TexturePaint(bimage6. TexturePaint texture2 = new TexturePaint( . TexturePaint texture4 = new TexturePaint(bimage4. 90. 0.computertech-dovari. bimage6.setPaint(texture1). g2d. For more information bimage4.blogspot. rect3). g2d. rect1).getHeight()). bimage5.getWidth(). Rectangle rect6 = new Rectangle(0.Created by dovari. rect4). TexturePaint texture5 = new TexturePaint(bimage5. rect2). 15.fillRect(10. Rectangle rect5 = new Rectangle(0. 60). g2d. TexturePaint texture3 = new TexturePaint(bimage3.getHeight()). 90.getWidth().

For more information http://www. 15. 60). g2d.setPaint(texture4). 90. frame.setDefaultCloseOperation(JFrame. 105. g2d. frame.computertech-dovari.fillRect(250. g2d.setSize(360.EXIT_ON_CLOSE). 105.fillRect(250. } public static void main(String[] args) { Textures rects = new Textures(). 90.setPaint(texture6).fillRect(10.add(rects). 60).setPaint(texture5). 60).fillRect(130. .setPaint(texture3). frame. g2d. 60). JFrame frame = new JFrame("Textures"). 90.g2d. 90.setLocationRelativeTo(null).blogspot. frame. g2d. 210). g2d. g2d.

bimage1. Here we create a TexturePaint object..Created by dovari. Java Swing has aTexturePaint .getHeight()). g2d. we will draw six rectangles filled with different textures.fillRect(10.blogspot.png"). g2d. The rectangle is used to anchor and replicate the image. .com frame.setPaint(texture1). To work with textures.getWidth(). We read an image into the memory. 15.sudheerkiran@gmail. TexturePaint texture1 = new TexturePaint(bimage1. BufferedImage bimage1 = null. } } In our example. We get the size of the texture image.computertech-dovari.. 90. bimage1. Rectangle rect1 = new Rectangle(0.. The images are tiled. 60).setVisible(true)..getSystemResource("texture1. The parameters are a buffered image and a rectangle of the image. 0. bimage1 = ImageIO. URL url1 = ClassLoader. . rect1). For more information

import java. import javax.Graphics2D. import java. import java. gradient is a smooth blending of shades from light to dark or from one color to import java.Color.awt.GradientPaint.awt. import .awt. Figure: Textures Gradients In computer graphics.JFrame. For more information http://www. (answers.Here we apply the texture and fill the rectangle with it.blogspot.BasicStroke. gradients are used to create colorful backgrounds and special effects as well as to simulate lights and shadows. In 2D drawing programs and paint programs.computertech-dovari.Graphics.awt.awt.

computertech-dovari.JPanel.sudheerkiran@gmail.fillRect(20. g2d. true). g2d. GradientPaint gp2 = new GradientPaint(5.paintComponent(g).com . Color. 20. true). 5.Created by dovari. 2. public class Gradients extends JPanel { public void paintComponent(Graphics g) { super. Graphics2D g2d = (Graphics2D) 20. 20. 20. 300. 40). Color.setPaint(gp1).black. Color.setPaint(gp2). For more information http://www. GradientPaint gp1 = new GradientPaint( import javax. g2d.blogspot. Color.

2. } For more information http://www. 260.blogspot. 140.computertech-dovari. 2.fillRect(20.fillRect( Color. 0. 40). GradientPaint gp4 = new GradientPaint(25. true). Color. 25. 25. GradientPaint gp5 = new GradientPaint(0. 0. 300. 15. 300. GradientPaint gp3 = new GradientPaint(5. g2d.fillRect(20. Color. g2d. 40). 300. true). 200. 40). g2d.fillRect(20.setPaint(gp3).green.g2d. .setPaint(gp5).setPaint(gp4). g2d. 40). g2d. 80. Color. true). 20.

g2d. frame. frame. Color.EXIT_ON_CLOSE). 25.setSize(350. To work with gradients.setDefaultCloseOperation(JFrame. The gradient is activated calling the setPaint() method. 25.setPaint(gp5). we can get interesting results. JFrame frame = new JFrame("Gradients"). 350). we use Java Swing's GradientPaint class.setLocationRelativeTo(null). For more information .blogspot. frame. Color.add(gradients) true). } } Our code example presents five rectangles with gradients.By manipulating the color values and the starting end ending points. 15. frame.sudheerkiran@gmail. frame.Created by dovari. GradientPaint gp4 = new GradientPaint(25.computertech-dovari.setVisible(true).com public static void main(String[] args) { Gradients gradients = new Gradients().

import java.swing.computertech-dovari. For more information http://www.awt.Graphics. import java.awt.RenderingHints.Graphics2D.awt. import javax. We specify the string we want to draw and the position of the text on the window area.Figure: Gradients Drawing text Drawing is done with the drawString() method. import java.awt.Font.blogspot. import .

setRenderingHints(rh). Font. For more information http://www. Graphics2D g2d = (Graphics2D) g.VALUE_ANTIALIAS_ON).VALUE_RENDER_QUALITY).Created by dovari. g2d. public class Text extends JPanel { public void paintComponent(Graphics g) { . RenderingHints rh = new RenderingHints( RenderingHints.JPanel. 21).swing.KEY_ANTIALIASING. import javax.computertech-dovari.BOLD.put(RenderingHints.blogspot.sudheerkiran@gmail. RenderingHints.paintComponent(g). Font font = new Font("URW Chancery L". rh.KEY_RENDERING.

g2d. For more information http://www.drawString("But you shall shine more bright in these contents". 20. g2d. 60).drawString("Shall you pace forth. g2d.". 20. 120). g2d.g2d. g2d.20. 270).setFont(font).drawString("And broils root out the work of masonry. shall outlive this powerful rhyme.drawString("Nor Mars his sword. . and all oblivious enmity". g2d. besmear'd with sluttish time. nor the gilded monuments". g2d. 180). 20. 20. 20.drawString("Not marble.drawString("Of princes. 360)." . 150). 300). 20.computertech-dovari. 90). 210). g2d. your praise shall still " + "find room". 30).".".drawString("When wasteful war shall statues overturn.blogspot. g2d.". g2d. 20.drawString("Than unswept stone. 20. 20.drawString("That wear this world out to the ending doom. 240). g2d.drawString("Even in the eyes of all posterity". 20. g2d.drawString("The living record of your memory.". nor war's quick " + "fire shall burn".drawString("'Gainst death. 330).

com .drawString("So. RenderingHints rh = new RenderingHints( RenderingHints.computertech-dovari.setDefaultCloseOperation(JFrame. 20.". till the judgment that yourself arise. JFrame frame = new JFrame("Sonnet 55"). frame. 420).setSize(500. For more information http://www.setLocationRelativeTo(null).setVisible(true).EXIT_ON_CLOSE).Created by dovari. g2d. we draw a sonnet on the panel component. g2d. } public static void main(String[] args) { Text text = new Text(). 470). and dwell in lovers' eyes. 390).blogspot.". frame. frame.KEY_ANTIALIASING.add(text). 20. frame.drawString("You live in this. } } In our example.

VALUE_ANTIALIAS_ON).computertech-dovari. that actually draws the text. This is the code.setFont(font). This code is to make our text look better.blogspot.RenderingHints. rh. For more information http://www. We apply a technique called antialiasing.drawString("Not marble. Font font = new Font("URW Chancery L".put(RenderingHints. We choose a nice font for our text. . 30).VALUE_RENDER_QUALITY).setRenderingHints(rh). nor the gilded monuments". RenderingHints. g2d.BOLD. g2d. Font. 21).KEY_RENDERING. 20.

Each pixel represents a color at a given position. For more information http://www. or we can draw it using the Java 2D API. import java.Graphics.computertech-dovari. We can use components like JLabel to display an Figure: Sonnet 55 Images On of the most important capabililies of a toolkit is the ability to display images. import java.awt.Graphics2D. An image is an array of .Created by dovari.

JFrame frame = new JFrame("Image"). } public static void main(String[] args) { AnImage image = new AnImage().JFrame. Graphics2D g2d = (Graphics2D) g.jpg"). import javax.swing. 10.paintComponent(g). .swing. public class AnImage extends JPanel { public void paintComponent(Graphics g) { super. 10.JPanel.computertech-dovari. import javax. null). import javax.blogspot.import java.getImage(). For more information http://www.swing.awt. Image image = new ImageIcon("dumbier.ImageIcon.drawImage(image.Image.

frame.jpg"). 10. g2d.setVisible(true). 320) .sudheerkiran@gmail. For more information frame.setLocationRelativeTo(null).computertech-dovari.add(image). } } This example will draw an image on the panel. Image image = new ImageIcon("dumbier.EXIT_ON_CLOSE).getImage().setDefaultCloseOperation(JFrame. These two lines read and draw the image. frame. frame. null).Created by dovari.drawImage(image. frame. 10.setSize(380.

com . The rectangles serve as a dragging points. We must not use a layout manager. we will create a resizable component.awt. import java. that the component has focus. import java.event.MouseAdapter. diagrams and similar. package resizablecomponent. Resizable component Resizable components are most often used when creating charts. This way we know. where we can draw the component and start resizing. we need a panel with absolute positioning enabled.blogspot. In order to distinguish which component has a focus.awt. For more information http://www.Color. In order to create a component that can be freely dragged over a panel.Dimension. import java. import java. The most common resizable component is a chart in a spreadsheet application.Figure: Image Resizable components in Java Swing In this part of the Java Swing tutorial.event. when we create a chart in a OpenOffice application.computertech-dovari. we draw 8 small rectangles on the border of our resizable component. I have learnt to use resizable components from this blog. For example. we will create a component (a JPanel) that we can freely move over a parent window and resize.MouseEvent.awt. In our example.awt. The chart can be moved over the grid widget of the application and resized.

com import javax. 50.swing.setBounds(50. 150). resizer = new Resizable(area).swing.JPanel. import javax.Created by dovari. For more information http://www.add(resizer). private Resizable resizer.computertech-dovari.sudheerkiran@gmail.blogspot. area. . JPanel area = new JPanel() */ public class ResizableComponent extends JFrame { private JPanel panel = new JPanel(null). public ResizableComponent() { add(panel).white). panel. 200. /* ResizableComponent.setBackground(Color.

setVisible(true).EXIT_ON_CLOSE). setLocationRelativeTo(null). 300)).computertech-dovari.repaint().blogspot. addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { requestFocus(). rc. setSize(new Dimension(350. } } For more information . } public static void main(String[] args) { ResizableComponent rc = new ResizableComponent(). } }). resizer. setTitle("Resizable Component").setDefaultCloseOperation(JFrame.

We have already mentioned. The rectangles over the border will disappear. import java.awt. we grab focus and repaint the component.repaint(). import java. For more information http://www.sudheerkiran@gmail.Cursor. import java.computertech-dovari. resizer. . import java. addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { requestFocus().Color. we create a panel with absolute positioning.awt. private JPanel panel = new JPanel(null). If we press on the parent panel.awt. By providing null to the constructor.g outside the resizable component. } }).Component. package The ResizableComponent sets up the panel and the component.Created by dovari.awt.blogspot.Graphics. that we cannot use any layout manager. We must use absolute positioning for resizable component.

import javax.border. SwingConstants. import javax. int locations[] = { SwingConstants. import java. SwingConstants. SwingConstants.import java.SwingConstants. // ResizableBorder. SwingConstants.NORTH. int cursors[] = For more information http://www. import java.Rectangle.awt.Insets.NORTH_WEST.swing. SwingConstants.WEST.SOUTH_EAST }.SOUTH. public class ResizableBorder implements Border { private int dist = 8. .NORTH_EAST.MouseEvent.blogspot.computertech-dovari.EAST.awt.

N_RESIZE_CURSOR. int h) { For more information http://www.SW_RESIZE_CURSOR.W_RESIZE_CURSOR.NW_RESIZE_CURSOR. public ResizableBorder(int dist) { this. int y.sudheerkiran@gmail. } public boolean isBorderOpaque() { return false. Cursor. Cursor. Cursor. int x. Cursor. Graphics g. Cursor.Created by dovari.dist = dist. dist.computertech-dovari.SE_RESIZE_CURSOR }. } public Insets getBorderInsets(Component component) { return new Insets(dist. .E_RESIZE_CURSOR. Cursor. Cursor. } public void paintBorder(Component component.NE_RESIZE_CURSOR.S_RESIZE_CURSOR. int w.blogspot. dist).com { Cursor.

i < locations. y + dist / 2. g. h. g.computertech-dovari. h .dist). dist.setColor(Color.1). y.1. w .drawRect(x + dist / 2.drawRect(rect. int y. rect.NORTH: return new Rectangle(x + w / 2 . int w.1. locations[i]). rect.fillRect(rect.x. int h.width .height .setColor( .y. rect.x.setColor(Color.1).hasFocus()) { for (int i = 0.dist.y. } } } private Rectangle getRectangle(int x. For more information rect. i++) { Rectangle rect = getRectangle(x. dist).height .width . y.g. g. g. rect. int location) { switch (location) { case SwingConstants. rect. g.dist / 2.WHITE). w.BLACK).length. if (component.

dist).dist.EAST: return new Rectangle(x + w .sudheerkiran@gmail. case SwingConstants.SOUTH: return new Rectangle(x + w / 2 . case SwingConstants. dist. y + h / 2 .com case SwingConstants. dist. dist). case SwingConstants. y + h .blogspot. y. y + h / 2 . dist). dist). dist). case SwingConstants. dist). dist.NORTH_WEST: return new Rectangle(x. dist. dist. y + h . case SwingConstants.Created by dovari.dist.dist. } public int getCursor(MouseEvent me) { For more information http://www. case SwingConstants. y + h .WEST: return new Rectangle( .SOUTH_WEST: return new Rectangle(x.computertech-dovari. dist.dist.dist. dist). } return null. dist.SOUTH_EAST: return new Rectangle(x + w .dist / 2. y.dist / 2.NORTH_EAST: return new Rectangle(x + w .dist.dist / 2.

Component c = me. h.getHeight().NORTH_EAST.NORTH_WEST.SOUTH. int h = c. SwingConstants.getComponent().MOVE_CURSOR. locations[i]). for (int i = 0.length. int w = c. w.blogspot.EAST. i < locations.NORTH. SwingConstants. } return Cursor. 0. if (rect. SwingConstants. SwingConstants. int locations[] = { SwingConstants.getPoint())) return cursors[i]. i++) { Rectangle rect = getRectangle( . SwingConstants.contains(me. } } The ResizableBorder is responsible for drawing the border of the component and determining the type of the cursor to use. SwingConstants.SOUTH_WEST.WEST.computertech-dovari. For more information http://www.getWidth().

height .blogspot. w.x. These locations are grabbing points.BLACK).hasFocus()) { for (int i = 0. In the paintBorder() method. } } The eight rectangles are drawn only in case that the resizable component has currently focus.y.length.height .computertech-dovari. where we will draw rectangles.x. g.width .1). y.setColor(Color.dist. rect. rect. The upper code draws the outer border of the component. h. w . rect.drawRect(x + dist / 2. g. For more information SwingConstants. rect.SOUTH_EAST }.1). g.WHITE).y. if (component. These are locations.dist). rect. we draw the border of the resizable component.sudheerkiran@gmail.drawRect(rect. g. y + dist / 2. h .setColor(Color. . rect. g.Created by dovari.setColor(Color.fillRect( . i++) { Rectangle rect = getRectangle(x. where we can grab the component and resize it. locations[i]). i < locations.

awt. import java.event. import public class Resizable extends JComponent { public Resizable(Component comp) { this(comp.MouseInputListener.JComponent. import java. new ResizableBorder(8)). package resizablecomponent.BorderLayout.swing.Point.MouseEvent.event.awt. import java.Finally.swing. import java. import java. import java. the getRectangle() method gets the coordinates of the rectangles and the getCursor() methods gets the cursor type for the grab point in question. import javax.computertech-dovari.event.awt.MouseInputAdapter.awt.Rectangle. For more information http://www. import .swing. // Resizable.

com .blogspot. add(comp). setCursor(Cursor. } private void resize() { if (getParent() != null) { ((JComponent)getParent()).com } public Resizable(Component comp.getPredefinedCursor(border. For more information http://www.computertech-dovari. addMouseMotionListener(resizeListener). addMouseListener(resizeListener). ResizableBorder border) { setLayout(new BorderLayout()). } } MouseInputListener resizeListener = new MouseInputAdapter() { public void mouseMoved(MouseEvent me) { if (hasFocus()) { ResizableBorder border = (ResizableBorder)getBorder().getCursor(me))). setBorder(border).revalidate().sudheerkiran@gmail.Created by dovari.

requestFocus(). } public void mouseDragged(MouseEvent me) { if (startPos != null) { For more information http://www. repaint(). } private int cursor. startPos = me.} } public void mouseExited(MouseEvent mouseEvent) { setCursor(Cursor.getPoint().blogspot.getDefaultCursor()).computertech-dovari. private Point startPos = . public void mousePressed(MouseEvent me) { ResizableBorder border = (ResizableBorder)getBorder().getCursor(me). cursor = border.

Created by dovari. resize(). startPos = me. y + .getPoint().getX() .S_RESIZE_CURSOR: if (!(h + dy < 50)) { setBounds( int x = getX(). } break.blogspot. int dy = me.dy < 50)) { setBounds(x. case Cursor. int h = getHeight(). w. h . switch (cursor) { case Cursor. y. int w = getWidth().startPos.startPos.getY() .N_RESIZE_CURSOR: if (!(h .computertech-dovari.sudheerkiran@gmail. w. For more information http://www.dy). h + dy).x. int y = getY(). int dx = me.y.

h).E_RESIZE_CURSOR: if (!(w + dx < 50)) { setBounds(x. case Cursor.dx.dx < 50) && !(h . w . y.computertech-dovari.dy < 50)) { For more information http://www. case Cursor. resize().dx < 50)) { setBounds(x + dx. } break. startPos = me. resize().com . h). } break. case Cursor.resize(). w + dx.blogspot. y.NW_RESIZE_CURSOR: if (!(w .W_RESIZE_CURSOR: if (!(w .getPoint(). } break.

dy < 50)) { setBounds(x. startPos = new Point(startPos.sudheerkiran@gmail. } break. case Cursor. } break.SW_RESIZE_CURSOR: if (!(w .com setBounds(x + dx. w + dx. } break.dy).getY()). case Cursor. h + dy). w . startPos. w . me. y. resize(). startPos = new Point(me.NE_RESIZE_CURSOR: if (!(w + dx < 50) && !(h . y + dy.computertech-dovari. h .y).x.Created by dovari. For more information http://www.blogspot.getX(). h . resize().dx < 50) && !(h + dy < 50)) { setBounds(x + dx.dy).com .dx.dx. resize(). y + dy.

} break. } setCursor(Cursor. dy). startPos = me.MOVE_CURSOR: Rectangle bounds = getBounds().case Cursor. setBounds(bounds). h + dy). } } public void mouseReleased(MouseEvent mouseEvent) { For more information http://www. y. resize().getPredefinedCursor(cursor)).computertech-dovari.SE_RESIZE_CURSOR: if (!(w + dx < 50) && !(h + dy < 50)) { setBounds(x.translate(dx. resize().com .blogspot. case Cursor. bounds.getPoint(). w + dx.

computertech-dovari. } }.sudheerkiran@gmail. The revalidate() method will cause the component to be redrawn.blogspot. MouseInputListener resizeListener = new MouseInputAdapter() { public void mouseMoved(MouseEvent me) { if (hasFocus()) { ResizableBorder border = (ResizableBorder)getBorder().com startPos = null.getCursor(me))). } For more information http://www. } The Resizable class represents the component.Created by dovari. after we have resized the .getPredefinedCursor(border. } } The resize() method is called.revalidate(). setCursor(Cursor. private void resize() { if (getParent() != null) { ((JComponent)getParent()). that is being resized and moved on the window.

The cursor type changes only if the component has focus.getPoint(). public void mousePressed(MouseEvent me) { ResizableBorder border = (ResizableBorder)getBorder().getCursor(me). repaint(). int y = getY(). int h = getHeight(). int x = getX(). give focus to the component and redraw it.y. For more information http://www. int dy = me. int dx = me. we change the cursor. } If we click on the resizable component.blogspot. cursor = border. startPos = me.startPos.getX() . int w = getWidth(). when we hover the cursor over the grip points. get the starting point of dragging. requestFocus().com .x.startPos.getY() .} We change the cursor type.computertech-dovari. In the mouseDragged() method.blogspot. Otherwise. we could make it so small. width and height of the component. we determine the x. that the component is not smaller than 50 px. w. case Cursor.N_RESIZE_CURSOR: if (!(h . y + dy. Figure: Resizable component For more information http://www. that we make during the mouse drag event.dy). resize(). } break.computertech-dovari. that we would eventually hide the component.Created by . y coordinates of the cursor.dy < 50)) { setBounds(x. For all resizing we ensure. h . We calculate the distances. The setBounds() method relocates and resizes the component.

swing. import java.JLabel. import javax.awt.Image.JFrame.swing.Box. The goal is to form the picture.event. import javax.ActionEvent. import java.ImageIcon. For more information http://www. import java.Dimension.awt.swing.swing.awt. It is cut into 12 pieces.blogspot. import . You can download the picture here.awt. we will create a simple puzzle game in Java Swing toolkit.awt.CropImageFilter.BorderLayout. import java.awt. import javax.JPanel.image. import javax. Puzzle We have an image of a Sid character from the Ice Age movie.ActionListener. import java. import java.awt. import javax.computertech-dovari.swing.The Puzzle in Java Swing In this chapter.JButton.GridLayout.image.FilteredImageSource. import java. import java.

{ public class Puzzle extends JFrame implements ActionListener { private JPanel centerPanel. private JButton button. int[][] pos.computertech-dovari. {9. 4. int width. private Image source. 7. {3. 2}.Created by dovari. private Image image. private JLabel label. 5}. 1.blogspot. For more information . 11} }. 8}. 10. public Puzzle() { pos = new int[][] { {0.sudheerkiran@gmail. height.

for ( int i = 0. 0)).getResource("icesid. For more information http://www. add(Box. BorderLayout. j < 3.centerPanel = new JPanel().computertech-dovari. width = sid.jpg")). 4. add(centerPanel.NORTH).com . i++) { for ( int j = 0. j++) { if ( j == 2 && i == 3) { label = new JLabel(""). 5)).getIconHeight().setLayout(new GridLayout(4.CENTER). height = sid.class. centerPanel.getIconWidth().createRigidArea(new Dimension(0.blogspot. BorderLayout. 0.add(label). source = sid. centerPanel. i < 4.getImage(). ImageIcon sid = new ImageIcon(Puzzle.

getSource(). setDefaultCloseOperation(JFrame. (width/3)+1. image = createImage(new FilteredImageSource(source.DISPOSE_ON_CLOSE). button.setIcon(new ImageIcon(image)). 275).add(button). centerPanel.sudheerkiran@gmail. } } } setSize(325. height/4))). setTitle("Puzzle"). setResizable(false). setLocationRelativeTo(null). button.Created by dovari.computertech-dovari. } For more information } else { button = new JButton(). new CropImageFilter(j*width/ . i*height/4. setVisible(true).addActionListener(this).blogspot.

int buttonX = button.getX(). int labelY = label. Dimension size = button. int buttonIndex = pos[buttonPosY][buttonPosX].getSource(). int labelX = label.getX().blogspot.height ) { For more information http://www.width. int buttonPosX = buttonX / size. int buttonPosY = buttonY / size.buttonY) == size. } public void actionPerformed(ActionEvent e) { JButton button = (JButton) e. int buttonY = button. if (labelX == buttonX && (labelY .getY().getSize().public static void main(String[] args) { new Puzzle().com .computertech-dovari.height.getY().

add(label. centerPanel. buttonIndex).buttonX) == size. centerPanel. centerPanel.buttonY) == -size.computertech-dovari. centerPanel.add(button.Created by int labelIndex = buttonIndex + 3. For more information http://www. .height ) { int labelIndex = buttonIndex .add(label.blogspot.validate(). centerPanel.3. buttonIndex).validate(). } if (labelX == buttonX && (labelY .sudheerkiran@gmail.remove(labelIndex). centerPanel. centerPanel.width ) { int labelIndex = buttonIndex + 1.remove(buttonIndex). } if (labelY == buttonY && (labelX .labelIndex).add(button.labelIndex).

centerPanel. buttonIndex).labelIndex).com .add(label.remove(buttonIndex).computertech-dovari. We move the buttons by clicking on them. } if (labelY == buttonY && (labelX . centerPanel.width ) { int labelIndex = buttonIndex .add(label.validate().labelIndex). centerPanel. Only buttons adjacent to the label can be moved.buttonX) == -size. labelIndex). centerPanel. centerPanel.validate().blogspot. } } } The goal of this little game is to form the original picture.remove(buttonIndex). pos = new int[][] { For more information http://www.add(button. centerPanel.add(button. centerPanel.centerPanel.1.

i++) { for ( int j = . ImageIcon sid = new ImageIcon(Puzzle. i < 4. 2}. 10. j < 3. 4.jpg")).addActionListener(this). 7. For more information http://www. {3. We use the ImageIcon class to load the image. centerPanel. These are the positions of the image parts. {6.Created by dovari.sudheerkiran@gmail. } else { button = new JButton() {0.add(button). 1.getResource("icesid. {9.getImage().add(label). for ( int i = 0. button. 5}. 11} }. 8}. centerPanel. j++) { if ( j == 2 && i == 3) { label = new JLabel(""). source = sid.class.

width. (width/3)+1.computertech-dovari. new CropImageFilter(j*width/3.image = createImage(new FilteredImageSource(source. height/4))).blogspot. } } } The code creates 11 buttons and one label.buttonY) == size. int buttonY = . Here we get the index of the button in the two dimensional array of the button positions. button.getY(). if (labelX == buttonX && (labelY .height ) { For more information http://www.height. int buttonPosY = buttonY / size. i*height/4.getX(). We crop the image into pieces and place them on the buttons. int buttonPosX = buttonX / size.getX(). int buttonIndex = pos[buttonPosY][buttonPosX]. y coordinates of the button that we hit and an empty label.getY(). y coordinates are important in the logic of the program.getSource(). The x. int labelX = label. We get the x.setIcon(new ImageIcon(image)). int buttonX = button. int labelY = label.

buttonY) == size. they share the x coordinate.add(button. centerPanel. centerPanel. centerPanel.computertech-dovari. If the button is right above the label.sudheerkiran@gmail. that is right above the empty . If it is above the label. Figure: Puzzle For more information http://www.validate().add(label. centerPanel. buttonIndex).height is true.remove(buttonIndex).blogspot. } In this case.Created by int labelIndex = buttonIndex + 3. we check if we clicked on the button. the equation (labelY .labelIndex).

The Tetris game In this chapter. Tetris The Tetris game is one of the most popular computer games ever created. we have seven different shapes called tetrominoes. Behind every computer game. So it is in Tetris. Tetris is available on almost every computer platform in lots of variations. It is modified and simplified. In this game. L-shape. Figure: Tetrominoes The development We do not have images for our tetris game. Z-shape. The original game was designed and programmed by a russian programmer Alexey Pajitnov in 1985. The object of the Tetris game is to move and rotate the shapes. so that they fit as much as possible. there is a mathematical . the row is destroyed and we score. Some ideas behind the game. • We use a Timer class to create a game cycle For more information http://www.blogspot.computertech-dovari. Tetris is called a falling block puzzle game. Since then. Line-shape. we will create a Tetris game clone in Java Swing. If we manage to form a row. The shapes are falling down the board. The following example is based on the C++ code example available at doc. Even my mobile phone has a modified version of the Tetris game.trolltech. Each of these shapes is formed with four squares. We play the tetris game until we top out. MirroredL-shape and a Square-shape. S-shape. we draw the tetrominoes using Swing drawing API.

import javax.blogspot.JFrame.BorderLayout. import javax. The game starts immediately. // • • • The tetrominoes are drawn The shapes move on a square by square basis (not pixel by pixel) Mathematically a board is a simple list of numbers I have simplified the game a bit. The score is the number of lines. We can pause the game by pressing the p key. public class Tetris extends JFrame { JLabel statusbar.swing. (It can be used to speed up the falling a bit.sudheerkiran@gmail. after it is launched.computertech-dovari. that we have removed.Created by dovari.) The game goes at constant speed. import package . no acceleration is implemented.swing.JLabel. so that it is easier to understand. The d key will drop the piece one line down. For more information http://www. The space key will drop the tetris piece immediately to the bottom.awt.

computertech-dovari. For more information http://www. add(statusbar. setDefaultCloseOperation(EXIT_ON_CLOSE). setTitle("Tetris"). . 400).setLocationRelativeTo(null). } public static void main(String[] args) { Tetris game = new Tetris().blogspot. } public JLabel getStatusBar() { return statusbar. Board board = new Board(this).start(). game.public Tetris() { statusbar = new JLabel(" 0"). setSize(200. add(board). BorderLayout.SOUTH).

board. We create a board on which we play the game. SShape.setVisible(true).blogspot.Math. Immediately. import java. For more information http://www. MirroredLShape }.com . ZShape. // Shape. TShape. public class Shape { enum Tetrominoes { NoShape. } } In the Tetris. LineShape.start() package game. SquareShape. The start() method starts the Tetris game.Created by file. We create a statusbar. import java.Random.util. we set up the game. after the window appears on the screen. LShape.

1 } }. 0 }. } public void setShape(Tetrominoes shape) { coordsTable = new int[][][] { { { 0. 0 }. setShape(Tetrominoes. { { 0. 1 } }. { 0. { 0. { 0. 0 }. private int[][][] coordsTable. { -1. { -1.computertech-dovari. { 0. 0 }.private Tetrominoes pieceShape. 0 }. 0 } }. -1 }. 0 }. { 0. 1 } }. For more information http://www. { 0. 0 }. 0 }. 0 }. public Shape() { coords = new int[4][2]. -1 }. { . { 1. { 0. { { 0. { 1. 0 }. { 0. 2 } }. private int coords[][]. { 1. { 0. 0 }.blogspot. 1 }.NoShape). { { -1. -1 }. { { 0.

-1 }. } public int x(int index) { return coords[index][0]. i < 4 . { . 0 }. 0 }. } public void setRandomShape() For more information http://www. ++j) { coords[i][j] = coordsTable[shape. }. i++) { for (int j = 0.blogspot. -1 }. 1 }. 1 } } { { -1. } public int y(int index) { return coords[index][1].ordinal()][i][j]. 0 }. for (int i = 0.Created by dovari. 1 } }. { 0. } private void setY(int index. { 0. 0 }. { 1. { 0.computertech-dovari.sudheerkiran@gmail. } private void setX(int { { 0. { 0. -1 }. -1 }. { 0. { { 1. { 0. } public Tetrominoes getShape() { return pieceShape. { 1. j < 2. int x) { coords[index][0] = x. int y) { coords[index][1] = y. } } pieceShape = shape. 1 } }.

coords[i][0]). for (int i=0. int x = Math. i++) { m = Math.abs(r. } public int minY() { int m = coords[0][1].min(m. } public int minX() { int m = coords[0][0].blogspot. } return m. i < 4. Tetrominoes[] values = Tetrominoes.values(). for (int i=0.nextInt()) % 7 + . i++) { For more information http://www.computertech-dovari. i < 4. setShape(values[x]).{ Random r = new Random().

++i) { result.setX(i. Shape result = new Shape().com m = Math. y(i)). result.pieceShape = pieceShape.SquareShape) return this. i < 4. result. -x(i)).sudheerkiran@gmail. } public Shape rotateRight() For more information http://www. for (int i = 0.min( .computertech-dovari. } return m.Created by dovari.blogspot. } public Shape rotateLeft() { if (pieceShape == Tetrominoes. coords[i][1]). } return result.setY(i.

x(i)). TShape. MirroredLShape }. SShape. ZShape. i < 4. } return result. Plus the empty shape called here NoShape.{ if (pieceShape == Tetrominoes. } } The Shape class provides information about a tetris piece. The Tetrominoes enum holds all seven tetris shapes.computertech-dovari. result. -y(i)). LShape.SquareShape) return this. for (int i = 0.setY( .pieceShape = pieceShape. LineShape. ++i) { result.setX(i.blogspot. result. Shape result = new Shape(). For more information http://www. enum Tetrominoes { NoShape. SquareShape.

1 }.NoShape). 0 }. 0 }. -1 }. { 1. { 0. 0 } }. -1 }. } This is the constructor of the Shape class. { 0. -1 }. { { 0. 0 }. 0 }. 1 } }. { 0.computertech-dovari. { 1. 0 }. 1 } }. -1 }. For more information http://www. { 0. { 0. 1 } } }. 0 }. coordsTable = new int[][][] { { { 0. { 1. { 0. 1 }.blogspot. { 0. -1 }. 0 }. { 0. 0 }. { 0. 1 } }. { -1. { public Shape() { coords = new int[4][2]. { 0. 0 }. { 0. -1 }. { 1. setShape(Tetrominoes. { 1. { { -1. { -1. { 0. 2 } }. { 0.Created by dovari. The coords array holds the actual coordinates of a tetris . { 0. { 0. 0 }. 0 }. { { 1. { { 0. -1 }. 0 }. 0 }. { { -1. 1 } }. { { 0. 1 } }. { { 0. 0 }.sudheerkiran@gmail. { 0. 0 }.

For example. represent a rotated S-shape. Note the use of the ordinal() method.blogspot. 1 } . numbers { 0. j < 2. an enum type is esencially an integer. -1 }. 0 }. 0 }. ++j) { coords[i][j] = coordsTable[shape.ordinal()][i][j].The coordsTable array holds all possible coordinate values of our tetris pieces. i++) { for (int j = 0. The following image will help understand the coordinate values a bit more. Unlike in C++.computertech-dovari. Figure: Tetris public Shape rotateLeft() For more information http://www. i < 4 . This is a template from which all pieces take their coordiate values. Java enums are full classes. In C++. { . The coords array saves the coordinates of the tetris piece. { 1. for (int i = 0. The following diagram illustrates the shape. And the ordinal() method returns the current position of the enum type in the enum object. } } Here we put one row of the coordiate values from the coordsTable to a coords array of a tetris piece. { 0.

setX(i. // Board. ++i) { result. } This code rotates the piece to the left. Looking at the previous image will help to understand the rotation. i < 4. result. The square does not have to be rotated. for (int i = package tetris. y(i)). For more information http://www.SquareShape) return this.setY(i. . } return result. Shape result = new Shape().pieceShape = { if (pieceShape == Tetrominoes.sudheerkiran@gmail.Created by dovari. That's why we simply return the reference to the current object. -x(i)).

Tetrominoes.Color.swing.import . For more information http://www. public class Board extends JPanel implements ActionListener { final int BoardWidth = 10. import javax.JPanel. import java.blogspot.swing.event.awt.ActionEvent.awt.Shape.Dimension.ActionListener.event. import java. import tetris. import javax. final int BoardHeight = 22.Graphics. import java.Timer.computertech-dovari.awt.swing. import java.event.awt.JLabel. import javax.event. import java. import java.

blogspot. boolean isFallingFinished = false. public Board(Tetris parent) { setFocusable(true). Shape curPiece. Tetrominoes[] Timer timer.sudheerkiran@gmail.computertech-dovari. timer. this). boolean isStarted = false. boolean isPaused = false. curPiece = new Shape(). int curY = 0.start(). int numLinesRemoved = 0. For more information http://www. int curX = . JLabel statusbar.Created by dovari. timer = new Timer(400.

computertech-dovari. newPiece(). } For more information http://www. } Tetrominoes shapeAt(int x. addKeyListener(new TAdapter()). int y) { return board[(y * BoardWidth) + x]. } else { oneLineDown(). } public void actionPerformed(ActionEvent e) { if (isFallingFinished) { isFallingFinished = false. board = new Tetrominoes[BoardWidth * BoardHeight].com .getHeight() / BoardHeight. } } int squareWidth() { return (int) getSize().getWidth() / BoardWidth. } int squareHeight() { return (int) getSize().statusbar = parent.getStatusBar(). clearBoard().blogspot. . numLinesRemoved = public void start() { if (isPaused) return. } private void pause() { if (!isStarted) return. isPaused = !isPaused. isFallingFinished = false. For more information http://www. timer. newPiece().computertech-dovari.start(). clearBoard(). isStarted = true.Created by dovari.

stop().blogspot. } public void paint(Graphics g) { super. int boardTop = (int) size.computertech-dovari. } else { timer. j < BoardWidth.if (isPaused) { timer.valueOf(numLinesRemoved)). } repaint().setText("paused"). statusbar.getHeight() . i < BoardHeight.paint(g).BoardHeight * squareHeight(). for (int i = 0. Dimension size = getSize().setText(String. statusbar. ++i) { for (int j = . ++j) { For more information http://www.start().

getShape()).sudheerkiran@gmail. i < 4.y(i).x(i).computertech-dovari. 0 + j * squareWidth(). shape).com .NoShape) drawSquare(g.i .blogspot. } } if (curPiece. ++i) { int x = curX + curPiece.y . BoardHeight . 0 + x * squareWidth(). drawSquare(g. curPiece.Created by dovari.curPiece.NoShape) { for (int i = 0. if (shape != Tetrominoes.getShape() != Tetrominoes.1) * squareHeight(). boardTop + i * squareHeight().1). int y = curY .com Tetrominoes shape = shapeAt(j. } } } private void dropDown() { For more information http://www. boardTop + (BoardHeight .

} private void clearBoard() { for (int i = 0.computertech-dovari. curY . i < BoardHeight * BoardWidth. } pieceDropped().com . curX.1)) break.blogspot.NoShape.1)) pieceDropped(). while (newY > 0) { if (!tryMove(curPiece. } For more information http://www. curX. newY = curY. ++i) board[i] = Tetrominoes. } private void oneLineDown() { if (!tryMove(curPiece. newY .

Created by private void pieceDropped() { for (int i = 0.1 + curPiece.minY().y(i).sudheerkiran@gmail. curX = BoardWidth / 2 + 1. curY = BoardHeight .com .getShape(). For more information http://www. i < 4. ++i) { int x = curX + curPiece. board[(y * BoardWidth) + x] = curPiece. } removeFullLines(). if (!isFallingFinished) newPiece().blogspot.curPiece.setRandomShape(). } private void newPiece() { curPiece. int y = curY .computertech-dovari.x(i).

computertech-dovari. curX. curX = newX. int newX.NoShape) return false. isStarted = false.NoShape). int newY) { for (int i = 0. int y = newY .setShape(Tetrominoes. if (shapeAt(x.blogspot.stop(). y) != Tetrominoes. ++i) { int x = newX + newPiece.y(i). curY)) { curPiece. if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight) return false. } curPiece = newPiece. statusbar.if (!tryMove( . } } private boolean tryMove(Shape newPiece.setText("game over").x(i).newPiece. For more information http://www. timer. i < 4.

break. for (int i = BoardHeight . return true.NoShape) { lineIsFull = false. } private void removeFullLines() { int numFullLines = 0. i) == Tetrominoes.sudheerkiran@gmail. } } if (lineIsFull) { ++numFullLines.blogspot.Created by dovari. i >= . repaint().com curY = newY. for (int j = 0. ++j) { if (shapeAt(j. --i) { boolean lineIsFull = true.computertech-dovari. For more information http://www. j < BoardWidth.

For more information http://www. j < BoardWidth. new Color(204.valueOf(numLinesRemoved)).setShape(Tetrominoes. 102). 102. repaint().blogspot. 204). int x. k + 1).1. new Color(204. 102). curPiece. ++j) board[(k * BoardWidth) + j] = shapeAt(j. 102). 102. Tetrominoes shape) { Color colors[] = { new Color(0. 204. k < BoardHeight . 0.computertech-dovari. new Color(102. new Color( . int y.for (int k = i. } } private void drawSquare(Graphics g. new Color(102. 102.setText(String.NoShape). isFallingFinished = true. statusbar. 0). } } } if (numFullLines > 0) { numLinesRemoved += numFullLines. ++k) { for (int j = 0. 204. 204).

computertech-dovari.ordinal()]. 204).drawLine(x + 1. x + squareWidth() . y + 1). squareWidth() . y).1. x + squareWidth() .1.1.setColor(color. 204. g. g. y + squareHeight() .com . y + squareHeight() . g. x + squareWidth() . x. } For more information http://www.setColor(color. g. 0) }.drawLine(x + squareWidth() . g. new Color(218.1). squareHeight() .1. y + squareHeight() .setColor(color). g. y). y + squareHeight() .drawLine(x.drawLine(x. g.1. y + 1. 170. y.2. Color color = colors[shape.1.fillRect(x + 1.brighter()).Created by dovari.2). new Color(102.darker()).

For more information http://www. curY).class TAdapter extends KeyAdapter { public void keyPressed(KeyEvent e) { if (!isStarted || curPiece.blogspot.VK_LEFT: tryMove(curPiece.computertech-dovari.1.getShape() == Tetrominoes. } if (isPaused) . switch (keycode) { case KeyEvent. } int keycode = e.getKeyCode(). curX . return.NoShape) { return. if (keycode == 'p' || keycode == 'P') { pause().

break. case KeyEvent.Created by dovari. case KeyEvent.VK_SPACE: dropDown(). case 'd': oneLineDown().blogspot. break.sudheerkiran@gmail. curX.rotateLeft().rotateRight(). case break. break. break. case KeyEvent. break.VK_RIGHT: tryMove(curPiece.VK_UP: tryMove(curPiece. } For more information http://www. curX. curY). curY). curY).com .computertech-dovari. break. curX + 1. case 'D': oneLineDown().VK_DOWN: tryMove(curPiece.

.start(). numLinesRemoved = 0. curY = file. we have the Board. . we have removed so far. isPaused = false.blogspot. setFocusable(true). timer = new Timer(400. isFallingFinished = false. if the tetris shape has finished falling and we then need to create a new shape. The numLinesRemoved counts the number of lines. The isFallingFinished variable determines. For more information http://www... From now. isStarted = false. This is where the game logic is located.computertech-dovari. The curX and curY variables determine the actual position of the falling tetris shape. We must explicitely call the setFocusable() method. the board has the keyboard input. We initialize some important variables. curX = 0. . timer. this).} } } Finally.

NoShape) drawSquare(g. shape). } } The actionPerformed() method checks if the falling has finished. we draw the all objects on the board.blogspot. Inside the paint() .Created by dovari. boardTop + i * squareHeight(). if (shape != Tetrominoes. for (int i = 0. the timer calls theactionPerformed() method each 400 ms. j < BoardWidth. The painting has two steps. ++i) { for (int j = 0.computertech-dovari. newPiece().i . a new piece is created. i < BoardHeight.sudheerkiran@gmail. BoardHeight . ++j) { Tetrominoes shape = shapeAt(j.1). the falling tetris piece goes one line down. If so. } else { oneLineDown(). public void actionPerformed(ActionEvent e) { if (isFallingFinished) { isFallingFinished = false. If not. For more information Timer object fires one or more action events after a specified delay. In our case. 0 + j * squareWidth().

} } In the first step we paint all the shapes.y(i). or remains of the shapes. All the squares are rememberd in the board array. if (curPiece. private void dropDown() { int newY = curY. curPiece. 0 + x * squareWidth(). We access it using the shapeAt() method. boardTop + (BoardHeight .computertech-dovari.blogspot.getShape() != Tetrominoes. } } In the second step.y .getShape()). int y = curY . drawSquare(g.NoShape) { for (int i = . we paint the actual falling piece. i < 4. ++i) { int x = curX + curPiece.1) * squareHeight(). while (newY > 0) { For more information http://www.curPiece. that have been dropped to the bottom of the board.x(i).

i < BoardHeight * BoardWidth. For more information if (!tryMove(curPiece.Created by dovari. This is later used at collision detection. } The clearBoard() method fills the board with empty NoSpapes.sudheerkiran@gmail.x(i). private void pieceDropped() { for (int i = 0. } pieceDropped(). ++i) { int x = curX + curPiece.computertech-dovari. i < 4. We simply try to drop the piece one line down until it reaches the bottom or the top of another fallen tetris piece.1)) break. curX. the piece is dropped to the bottom. ++i) board[i] = Tetrominoes. .blogspot. private void clearBoard() { for (int i = 0. } If we press the space key. newY .

we try to create a new piece. This is the job of the removeFullLines() method. curX = BoardWidth / 2 + 1.getShape(). the board holds all the squares of the pieces and remains of the pieces that has finished falling. if we can remove some lines off the board.setRandomShape().int y = curY . For more information http://www. When the piece has finished falling.1 + curPiece. board[(y * BoardWidth) + x] = curPiece. } The pieceDropped() method puts the falling piece into the board array. } removeFullLines().blogspot. if (!isFallingFinished) newPiece(). More precisely.y(i).computertech-dovari. private void newPiece() { curPiece. it is time to check.curPiece. Once again.minY().com . Then we create a new piece. curY = BoardHeight .

private boolean tryMove(Shape .NoShape) return false. For more information http://www. int y = newY . curX.y(i). The piece gets a new random shape.setShape( if (!tryMove(curPiece. if (shapeAt(x. If we cannot move to the initial positions.NoShape).newPiece. y) != Tetrominoes.x(i). int newX. ++i) { int x = newX + newPiece.setText("game over").Created by dovari. We top out.blogspot.computertech-dovari. We put game over string on the statusbar. int newY) { for (int i = 0. i < 4. the game is over.sudheerkiran@gmail. timer. statusbar. } } The newPiece() method creates a new tetris piece. if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight) return false. The timer is stopped. isStarted = false. curY)) { curPiece. Then we compute the initialcurX and curY values.stop().

blogspot.computertech-dovari. break. curY = .NoShape) { lineIsFull = false. j < BoardWidth. if it has reached the board boundaries or it is adjacent to the already fallen tetris pieces.1. --i) { boolean lineIsFull = true. } } For more information http://www. The method returns false. ++j) { if (shapeAt(j. i) == Tetrominoes. repaint().} curPiece = newPiece. curX = newX. for (int j = 0. } The tryMove() method tries to move the tetris piece. for (int i = BoardHeight . return true. i >= 0.

Tetris pieces have different colors.setColor(color. The control mechanism is implemented with a KeyAdapter. Notice. x + squareWidth() . After finding a full line we increase the counter. This is to simulate a 3D edge. If there is at least one full line. x. y. that the squares may be left floating above empty gaps. y + squareHeight() . y).1. g. for (int k = i. g. we use so called naive gravity.Created by dovari. For more information http://www. The left and top sides of a square are drawn with a brighter color. } } } Inside the removeFullLines() method. This is an inner class that overrides the keyPressed() method. This means. g. we check if there is any full row among all rows in the board. We move all the lines above the full row one line down. Similarly.sudheerkiran@gmail.computertech-dovari.drawLine(x. We control the game with a keyboard. the bottom and right sides are drawn with darker colors.brighter()).1. it is removed. This way we destroy the full line.drawLine(x. k < BoardHeight .com . j < if (lineIsFull) { ++numFullLines. ++k) { for (int j = 0. that in our Tetris game.blogspot. Each of the squares is drawn with the drawSquare() method. ++j) board[(k * BoardWidth) + j] = shapeAt(j. Every tetris piece has four squares. k + 1). y).

VK_RIGHT: tryMove( KeyEvent. Figure: Tetris For more information http://www. curX + . break. we try to move the falling piece one square to the left. If we pressed the left arrow key. curY).blogspot.

Sign up to vote on this title
UsefulNot useful