package cn.njupt.Swing;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonFrame extends JFrame {
private JPanel buttonPanel;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public ButtonFrame() {
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
//create buttons
JButton yellowButton = new JButton("yellow");
JButton blueButton = new JButton("blue");
JButton redButton = new JButton("red");
buttonPanel = new JPanel();
// add buttons to panel
buttonPanel.add(redButton);
buttonPanel.add(blueButton);
buttonPanel.add(yellowButton);
//add panel to frame
add(buttonPanel);
//create button action
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);
}
private class ColorAction implements ActionListener{
private Color backgroundColor;
public ColorAction(Color c) {
backgroundColor = c;
}
@Override
public void actionPerformed(ActionEvent arg0) {
buttonPanel.setBackground(backgroundColor);
}
}
}
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonFrame extends JFrame {
private JPanel buttonPanel;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public ButtonFrame() {
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
//create buttons
JButton yellowButton = new JButton("yellow");
JButton blueButton = new JButton("blue");
JButton redButton = new JButton("red");
buttonPanel = new JPanel();
// add buttons to panel
buttonPanel.add(redButton);
buttonPanel.add(blueButton);
buttonPanel.add(yellowButton);
//add panel to frame
add(buttonPanel);
//create button action
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);
}
private class ColorAction implements ActionListener{
private Color backgroundColor;
public ColorAction(Color c) {
backgroundColor = c;
}
@Override
public void actionPerformed(ActionEvent arg0) {
buttonPanel.setBackground(backgroundColor);
}
}
}