Return to index

Part 4

For our final example, we will create a useful, reusable component. We will create a toggling button with a light inside to indicate its state. It is based on class JButton and shows how versatile the Swing components can be. You are welcome to change it or use it in your own projects.

Here is the source code for the toggling button with 'light' (class KToggleButton):

package projects.guicomps;

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

import java.lang.*;

public class KToggleButton extends JButton implements ActionListener {

boolean on=false;

 

// Constructor

public KToggleButton() {

super();

setUp();

}

 

// A second constructor

public KToggleButton(String s) {

super(s);

setup();

}

 

private void setup() {

ImageIcon onImage=new ImageIcon("on.gif");

ImageIcon offImage=new ImageIcon("off.gif");

setIcon(offImage);

setSelectedIcon(onImage);

setContentAreaFilled(false);

setBorderPainted(false);

setFocusPainted(false);

addActionListener(this);

}

 

public void actionPerformed(ActionEvent e) {

on=!on;

setSelected(on);

repaint();

}

 

public boolean isSelected() {

return on;

}

}

 

The design for KToggleButton takes advantage of the fact that the Swing JButton class can display an icon. We set a different icon for the state when the button is selected (pressed). These icons have been created by the TJI design team to resemble small blue LEDs. We avoid the usual look of a pressed JButton by setting the 'area filled' and 'border painted' properties with the following two method calls:

setContentAreaFilled(false);

setBorderPainted(false);

And here is the source code for class Example6 that uses an instance of class KToggleButton:

package projects.tjioo6;

 

import projects.guicomps.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Example6 extends JPanel {

// Constructor

public Example6() {

ToggleLightBox light=new ToggleLightBox();

 

KToggleButton button=new KToggleButton("Light");

button.addActionListener(light);

 

add(button);

add(new JLabel(" "));

add(light);

}

}

 

Finally, we suggest you take a look at the other learning resources that TJI provides, including :

* the sections on flow control, scope, operators etc.,

* the example projects entitled 'TJI's Guide to Swing'.

 

Download and run ...

You can download the source code for the example programs as a TJI project from the 'Resources' page of our website.

(c) Kinabaloo Software

Return to index