Basic Swing components
Swing components are basic building blocks of an application. Swing toolkit has a wide range of various widgets. Buttons, check boxes,sliders, list boxes etc. Everything a programmer needs for his job. In this section of the tutorial, we will describe several useful components.JLabel Component
JLabel
is a simple component for displaying text, images or both. It does not react to input events. import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MyLabel extends JFrame {
private Toolkit toolkit;
public MyLabel() {
setTitle("No Sleep");
String lyrics = "<html>It's way too late to think of<br>" +
"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, world<br>" +
"<br>" +
"I've always been too late<br>" +
"To see what's before me<br>" +
"And I know nothing sweeter than<br>" +
"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, world<br>" +
"Sleep in peace</html>";
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout(10, 10));
JLabel label = new JLabel(lyrics);
label.setFont(new Font("Georgia", Font.PLAIN, 14));
label.setForeground(new Color(50, 50, 25));
panel.add(label, BorderLayout.CENTER);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
add(panel);
pack();
toolkit = getToolkit();
Dimension screensize = toolkit.getScreenSize();
setLocation((screensize.width - getWidth())/2,
(screensize.height - getHeight())/2);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MyLabel mylabel = new MyLabel();
mylabel.setVisible(true);
}
}
In our example, we show lyrics of no sleep song from cardigans. We can use html tags in
JLabel
component. We use the <br> tag to separate lines. JPanel panel = new JPanel();We create a panel and set a
panel.setLayout(new BorderLayout(10, 10));
BorderLayout
manager. JLabel label = new JLabel(lyrics);Here we create the label component. We set it's font to plain georgia, 14 px tall. We also change the foreground color.
label.setFont(new Font("Georgia", Font.PLAIN, 14));
label.setForeground(new Color(50, 50, 25));
panel.add(label, BorderLayout.CENTER);We put the label into the center of the panel. We put 10px around the label.
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
add(panel);The panel is added to the frame component. We call the
pack();
pack()
method, which will resize the window, so that all components are visible. Figure: JLabel
JCheckBox
JCheckBox is a component that has two states. On and Off. It is a box with a label. If the check box is checked, it is represented by a tick in a box. A check box can be used to show/hide splashscreen at startup, toggle visibility of a toolbar etc.package zetcode;Our code example shows or hides the title of the window depending on its state.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class CheckBoxExample extends JFrame
implements ActionListener {
public CheckBoxExample() {
initUI();
}
public final void initUI() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
add(Box.createRigidArea(new Dimension(15, 20)));
JCheckBox checkbox = new JCheckBox("Show Title", true);
checkbox.setFocusable(false);
checkbox.addActionListener(this);
add(checkbox);
setSize(280, 200);
setTitle("JCheckBox example");
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
JCheckBox source = (JCheckBox) e.getSource();
boolean state = source.isSelected();
if (state) {
this.setTitle("JCheckbox example");
} else {
this.setTitle("");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CheckBoxExample ex = new CheckBoxExample();
ex.setVisible(true);
}
});
}
}
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));In this example, we use a
add(Box.createRigidArea(new Dimension(15, 20)));
BoxLayout
layout manager. We put some space there, so that the checkbox is not too close to the corner. JCheckBox checkbox = new JCheckBox("Show Title", true);Here we have a constructor for the checkbox. We provide text and state.
checkbox.setFocusable(false);We have disabled the focus for the checkbox. A
JCheckBox
that has a focus may be selected or unselected with a spacebar. JCheckBox source = (JCheckBox) e.getSource();From the event object, we get the source component. In our case is the a check box. We find out the selection state of the check box. Depending on the state of the check box, we show or hide the title of the window.
boolean state = source.isSelected();
if (state) {
this.setTitle("JCheckbox example");
} else {
this.setTitle("");
}
Figure: JCheckBox
JSlider
JSlider is a component that lets the user graphically select a value by sliding a knob within a bounded interval. Our example will show a volume control.package zetcode;In the code example, we show a
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderExample extends JFrame {
private JSlider slider;
private JLabel label;
ImageIcon mute = new ImageIcon(getClass().getResource("mute.png"));
ImageIcon min = new ImageIcon(getClass().getResource("min.png"));
ImageIcon med = new ImageIcon(getClass().getResource("med.png"));
ImageIcon max = new ImageIcon(getClass().getResource("max.png"));
public SliderExample() {
initUI();
}
public final void initUI() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));
setLayout(new BorderLayout());
panel.add(Box.createHorizontalGlue());
slider = new JSlider(0, 150, 0);
slider.setPreferredSize(new Dimension(150, 30));
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
int value = slider.getValue();
if (value == 0) {
label.setIcon(mute);
} else if (value > 0 && value <= 30) {
label.setIcon(min);
} else if (value > 30 && value < 80) {
label.setIcon(med);
} else {
label.setIcon(max);
}
}
});
panel.add(slider);
panel.add(Box.createRigidArea(new Dimension(5, 0)));
label = new JLabel(mute, JLabel.CENTER);
panel.add(label);
panel.add(Box.createHorizontalGlue());
add(panel, BorderLayout.CENTER);
pack();
setTitle("JSlider");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SliderExample ex = new SliderExample();
ex.setVisible(true);
}
});
}
}
JSlider
and a JLabel
. By dragging the slider, we change the icon on the label component. ImageIcon mute = new ImageIcon(getClass().getResource("mute.png"));Here we create an image icon.
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));Panel component has a horizontal
BoxLayout
. panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));We creare a 40px border around the panel.
panel.add(Box.createHorizontalGlue());We put resizable space to bo both sides, left and right. It is to prevent
JSlider
from growing to unnatural sizes. slider = new JSlider(0, 150, 0);This is a
JSlider
constructor. The parameters are minimum value, maximum value and current value. slider.addChangeListener(new ChangeListener() {We add a
...
});
ChangeListener
to the slider. Inside the listener, we determine the current slider value and update the label accordingly. panel.add(Box.createRigidArea(new Dimension(5, 0)));We place a 5px rigid space between the two components. They are too close to each other, when the slider is at the end position.
Figure: JSlider
JComboBox
Combobox is a component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.import java.awt.Component;In our example, we have three components. A label, a combobox and a button. The button closes the window. We have six names of famous novelists in our combobox. If we select a name, an image is displayed in the label.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;
public class ComboBox extends JDialog implements
ActionListener, ItemListener {
final String[] authors = {
"Leo Tolstoy", "John Galsworthy",
"Honore de Balzac", "Stefan Zweig",
"Boris Pasternak", "Tom Wolfe"
};
final String[] images = {
"tolstoy.jpg", "galsworthy.jpg", "balzac.jpg",
"zweig.jpg", "pasternak.jpg", "wolfe.jpg"
};
private JLabel display = null;
private JComboBox combobox = null;
private JButton button = null;
ImageIcon icon = new ImageIcon(
ClassLoader.getSystemResource("balzac.jpg"));
public ComboBox() {
setLayout(new BoxLayout(getContentPane(),
BoxLayout.Y_AXIS));
add(Box.createRigidArea(new Dimension(0, 35)));
display = new JLabel();
display.setPreferredSize(new Dimension(100, 127));
display.setMaximumSize(new Dimension(100, 127));
display.setAlignmentX(Component.CENTER_ALIGNMENT);
display.setBorder(LineBorder.createGrayLineBorder());
add(display);
add(Box.createRigidArea(new Dimension(0, 15)));
combobox = new JComboBox(authors);
combobox.setSelectedIndex(-1);
combobox.setPreferredSize(new Dimension(140, 22));
combobox.setMaximumSize(new Dimension(140, 22));
combobox.addItemListener(this);
add(combobox);
add(Box.createRigidArea(new Dimension(0, 15)));
button = new JButton("Close");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
button.addActionListener(this);
add(button);
setTitle("JComboBox");
setSize(300, 300);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new ComboBox();
}
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
JComboBox combo = (JComboBox) e.getSource();
int index = combo.getSelectedIndex();
display.setIcon(new ImageIcon(
ClassLoader.getSystemResource(images[index])));
}
}
}
public class ComboBox extends JDialog implementsThis is a dialog based application example.
ActionListener, ItemListener {
display = new JLabel();The display area is a simple
JLabel
. combobox = new JComboBox(authors);The constructor of the
combobox.setSelectedIndex(-1);
JComboBox
takes a string array of novelists. If we provide -1 as an argument in the setSelectedIndex()
method, no item to be selected. combobox.addItemListener(this);We add an
ItemListener
to our combobox. In the event handler, we get the selected index of the combobox and set an appropriate icon for the label. The selected item is an index to the array of images. Figure: JComboBox
JProgressBar
A progress bar is a widget that is used, when we process lengthy tasks. It is animated so that the user knows, that our task is progressing. TheJProgressBar
widget provides a horizontal or vertical progress bar. The initial and minimum values are 0, and the maximum is 100. import java.awt.Dimension;The example displays a progress bar and a button. The button starts and stops the progress.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
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() {
setTitle("JProgressBar");
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));
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));
progressBar.setAlignmentX(0f);
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) {
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();
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();
}
}
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));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.setMinimumSize(new Dimension(150, 20));
progressBar.setPreferredSize(new Dimension(150, 20));
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()) {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.
timer.stop();
button.setText("Start");
} else if (button.getText() != "End") {
timer.start();
button.setText("Stop");
}
Figure: JProgressBar
JToggleButton
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. package zetcode;The example has three panels and three toggle buttons. Panels are bottom panel, left panel and display panel. The bottom panel is use to organize the left and display panels. For this, we use horizontal
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class ToggleButtonExample extends JDialog
implements ActionListener {
private JToggleButton redButton;
private JToggleButton greenButton;
private JToggleButton blueButton;
private JPanel display;
public ToggleButtonExample() {
initUI();
}
public final void initUI() {
JPanel bottom = new JPanel();
bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
bottom.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
redButton = new JToggleButton("red");
redButton.addActionListener(this);
greenButton = new JToggleButton("green");
greenButton.addActionListener(this);
blueButton = new JToggleButton("blue");
blueButton.addActionListener(this);
blueButton.setMaximumSize(greenButton.getMaximumSize());
redButton.setMaximumSize(greenButton.getMaximumSize());
leftPanel.add(redButton);
leftPanel.add(Box.createRigidArea(new Dimension(25, 7)));
leftPanel.add(greenButton
);
leftPanel.add(Box.createRigidArea(new Dimension(25, 7)));
leftPanel.add(blueButton);
bottom.add(leftPanel);
bottom.add(Box.createRigidArea(new Dimension(20, 0)));
display = new JPanel();
display.setPreferredSize(new Dimension(110, 110));
display.setBorder(LineBorder.createGrayLineBorder());
display.setBackground(Color.black);
bottom.add(display);
add(bottom);
pack();
setTitle("JToggleButton");
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
Color color = display.getBackground();
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
if (e.getActionCommand().equals("red")) {
if (red == 0) {
red = 255;
} else {
red = 0;
}
}
if (e.getActionCommand().equals("green")) {
if (green == 0) {
green = 255;
} else {
green = 0;
}
}
if (e.getActionCommand().equals("blue")) {
if (blue == 0) {
blue = 255;
} else {
blue = 0;
}
}
Color setCol = new Color(red, green, blue);
display.setBackground(setCol);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ToggleButtonExample ex = new ToggleButtonExample();
ex.setVisible(true);
}
});
}
}
BoxLayout
manager. The left panel will holt three toggle buttons. This time we use vertical BoxLayout
manager. We set the background color of the display panel to black. The toggle buttons will toggle the red, green and blue parts of the color value. The background color will depend on which togglebuttons we have pressed. redButton = new JToggleButton("red");Here we create a toggle button and set an action listener to it.
redButton.addActionListener(this);
blueButton.setMaximumSize(greenButton.getMaximumSize());We make all three buttons of equal size.
redButton.setMaximumSize(greenButton.getMaximumSize());
Color color = display.getBackground();In the
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
actionPerformed
method, we determine the current red, green, blue parts of the display background color. if (e.getActionCommand().equals("red")) {We determine, which button was toggled, and update the color part of the RGB value accordingly.
if (red == 0) {
red = 255;
} else {
red = 0;
}
}
Color setCol = new Color(red, green, blue);Here a new color is created and the display panel is updated to a new color.
display.setBackground(setCol);
Figure: JToggleButton
In this part of the Java Swing tutorial, we have covered basic Swing components.
No comments:
Post a Comment