import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("ButtonTest");
setSize(500,200);
//add panel to frame
ButtonPanel panel = new ButtonPanel();
add(panel);
}
}
class ButtonPanel extends JPanel
{
public ButtonPanel()
{
//create buttons
JButton YellowButton = new JButton("Yellow");
JButton BlueButton = new JButton("Blue");
JButton RedButton = new JButton("Red");
//add buttons to panel
add(YellowButton);
add(BlueButton);
add(RedButton);
//add button actions
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED);
//associate actions with buttons
YellowButton.addActionListener(yellowAction);
BlueButton.addActionListener(blueAction);
RedButton.addActionListener(redAction);
}
/*an action listener that sets the panel's background color*/
private class ColorAction implements ActionListener
{
private Color backgroundcolor;
public ColorAction(Color c)
{
backgroundcolor = c;
}
public void actionPerformed(ActionEvent event)
{
setBackground(backgroundcolor);
}
}
}
public class ButtonTest
{
public static void main(String[] args)
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
import java.awt.event.*;
import javax.swing.*;
class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("ButtonTest");
setSize(500,200);
//add panel to frame
ButtonPanel panel = new ButtonPanel();
add(panel);
}
}
class ButtonPanel extends JPanel
{
public ButtonPanel()
{
//create buttons
JButton YellowButton = new JButton("Yellow");
JButton BlueButton = new JButton("Blue");
JButton RedButton = new JButton("Red");
//add buttons to panel
add(YellowButton);
add(BlueButton);
add(RedButton);
//add button actions
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED);
//associate actions with buttons
YellowButton.addActionListener(yellowAction);
BlueButton.addActionListener(blueAction);
RedButton.addActionListener(redAction);
}
/*an action listener that sets the panel's background color*/
private class ColorAction implements ActionListener
{
private Color backgroundcolor;
public ColorAction(Color c)
{
backgroundcolor = c;
}
public void actionPerformed(ActionEvent event)
{
setBackground(backgroundcolor);
}
}
}
public class ButtonTest
{
public static void main(String[] args)
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
No comments:
Post a Comment