How to create a Frame with JPanel Class and Handle an Event using ActionListener Interface in Core Java

In this tutorial how to create a Frame with JPanel Class and Handle an Event using ActionListener Interface in Core Java is shown.

[themify_quote]

Code:

ButtonSettingBackground.java

import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

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

public class ButtonSettingBackground extends JPanel implements ActionListener
{
private JButton greenButton = new JButton(“Green”);
private JButton blueButton = new JButton(“Blue”);
private JButton redButton = new JButton(“Red”);

public ButtonSettingBackground()
{
add(greenButton);
add(blueButton);
add(redButton);

greenButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
}

public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
Color color = getBackground();

if(source == greenButton)
color = Color.green;
else if(source == blueButton)
color = Color.blue;
else if(source == redButton)
color = Color.red;

setBackground(color);
repaint();
}

public static void main(String args[])
{
JFrame frame = new JFrame(“ButtonTest”);
frame.setSize(300,200);

frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

Container contentPane = frame.getContentPane();
contentPane.add(new ButtonSettingBackground());

frame.show();
}
}

[/themify_quote]

Add a Comment

Your email address will not be published.