In this tutorial, I am going to show you how to create Toolbar using Java. Toolbars are used to display commonly used actions or controls.
Swing JToolBar provides a component that allows to maintain commonly used actions like aliment, save, changing fonts and etc..
Swing JToolBar Example :
MyFrameToolBarDemo.java
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class MyFrameToolBarDemo extends JFrame {
JToolBar toolbar;
JButton New, Open, Save;
JToggleButton Left, Center, Right;
JComboBox fonts;
ButtonGroup group;
MyFrameToolBarDemo() {
super("JToolbar Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
toolbar = new JToolBar();
New = new JButton(new ImageIcon(
"D:\\images\\NEW.GIF"));
Open = new JButton(new ImageIcon(
"D:\\images\\OPEN.gif"));
Save = new JButton(new ImageIcon(
"D:\\images\\SAVE.gif"));
Left = new JToggleButton(new ImageIcon(
"D:\\images\\LEFT.gif"));
Center = new JToggleButton(
new ImageIcon(
"D:\\images\\CENTER.gif"));
Right = new JToggleButton(new ImageIcon(
"D:\\images\\RIGHT.gif"));
group = new ButtonGroup();
group.add(Left);
group.add(Center);
group.add(Right);
fonts = new JComboBox();
fonts.addItem("Arial");
fonts.addItem("Times New Roman");
fonts.addItem("Comic Sans Ms");
toolbar.add(New);
toolbar.add(Open);
toolbar.addSeparator();
toolbar.add(Save);
toolbar.addSeparator();
toolbar.add(Left);
toolbar.add(Center);
toolbar.add(Right);
toolbar.addSeparator();
toolbar.add(fonts);
getContentPane().add(toolbar, BorderLayout.NORTH);
pack();
setVisible(true);
}
}
public class ToolBarDemo {
public static void main(String args[]) throws Exception {
new MyFrameToolBarDemo();
}
}
Output :
Font :
Happy Learning 🙂