package com.supermap;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonTest {
public static void main(String []args){
EventQueue.invokeLater(new Runnable(){
public void run(){
ButtonFrame frame=new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class ButtonFrame extends JFrame{
public ButtonFrame(){
setTitle("ButtonTest");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
JButton yellowButton=new JButton("Yellow");
JButton blueButton=new JButton("Blue");
JButton redButton=new JButton("Red");
buttonPanel=new JPanel();
buttonPanel.add(yellowButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton);
add(buttonPanel);
ColorAction yellowAction=new ColorAction(Color.YELLOW);
ColorAction blueAction=new ColorAction(Color.BLUE);
ColorAction redActon=new ColorAction(Color.RED);
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redActon);
}
private class ColorAction implements ActionListener{
public ColorAction(Color c){
backgroundColor=c;
}
public void actionPerformed(ActionEvent event){
buttonPanel.setBackground(backgroundColor);
}
private Color backgroundColor;
}
private JPanel buttonPanel;
public static final int DEFAULT_WIDTH=300;
public static final int DEFAULT_HEIGHT=200;
}
JButton(String lable)
JButton(Icon icon)
JButton(String label,Icon icon)
构造一个按钮,标签可以是常规的文本
Component add(Component c)
将组件c添加到这个容器中
ImageIcon(String filename)
构造一个图标,他的图像存储在一个文件中
建议使用内部类:
注意每个按钮的处理过程都是一样的:
1.用标签字符串构造按钮
2.将按钮添加到面板上
3.用对应的颜色构造一个动作监听器
4.添加动作监听器
为了简化这些操作过程,可以设计一个辅助的方法:
public void makeButton(String name,Color backgroudColor){
JButton button=new JButton(name);
buttonPanel.add(button);
ColorAction action=new ColorAction(backgroudnColor);
button.addActionListener(action);
}
然后简化调用:
makeButton("yellow",Color.YEllOW);
makeButton("blue",Color.BLUE);
makeButton("red",Color.RED);
接着,进一步进行简化,请注意,ColorAction类只在makeButton方法中使用一次,因此可以将它设计为一个匿名类:
public void makeButton(String name,final Color backgroudColor){
JButton button=new JButton(name);
buttonPanel.add(button);
butotn.addActonListtener(new ActionLister(){
public void actionPerformed(ActionEvent event){
buttonPanel.setBackground(backgroundColor);
}
});
}
动态监听变得更加简单了,actionPerformed方法仅仅引用参数变量backgroundColor(与内部类中方为的所有局部变量一样,应该将参数声明为final)
781

被折叠的 条评论
为什么被折叠?



