package com.c4learn.swing;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JButtonDemo {
private JFrame mainFrame;
private JLabel headLabel;
private JLabel msgLabel;
private JPanel mainPanel;
public JButtonDemo() {
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(300, 300);
mainFrame.setLayout(new GridLayout(3, 1));
headLabel = new JLabel("JButton Class", JLabel.CENTER);
msgLabel = new JLabel("No Action", JLabel.CENTER);
mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout());
mainFrame.add(headLabel);
mainFrame.add(mainPanel);
mainFrame.add(msgLabel);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
JButtonDemo swingControlDemo = new JButtonDemo();
swingControlDemo.showButtonDemo();
}
private void showButtonDemo() {
JButton okButton = new JButton("OK");
JButton submitButton = new JButton("Submit");
JButton cancelButton = new JButton("Cancel");
//Listner for OK Button
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
msgLabel.setText("Ok Button clicked.");
}
});
//Listner for Submit Button
submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
msgLabel.setText("Submit Button clicked.");
}
});
//Listner for Cancel Button
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
msgLabel.setText("Cancel Button clicked.");
}
});
mainPanel.add(okButton);
mainPanel.add(submitButton);
mainPanel.add(cancelButton);
mainFrame.setVisible(true);
}
}
Output :
