当前位置: 技术问答>java相关
为什么不会有结果呢一个小程序。。。。
来源: 互联网 发布时间:2015-01-11
本文导语: import java.awt.*; import java.awt.event.*; import javax.swing.*; class ButtonPanel extends JPanel implements ActionListener{ public ButtonPanel(){ yellowButton = new JButton("yellow"); blueButton = new JButton("blue"); redButton = new JButton("red"...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ButtonPanel extends JPanel implements ActionListener{
public ButtonPanel(){
yellowButton = new JButton("yellow");
blueButton = new JButton("blue");
redButton = new JButton("red");
add(yellowButton);
add(blueButton);
add(redButton);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getActionCommand();
Color color = getBackground();
if (source == yellowButton) color = Color.yellow;
else if (source == blueButton) color = Color.blue;
else if (source == redButton) color = Color.red;
setBackground(color);
repaint();
}
private JButton yellowButton;
private JButton blueButton;
private JButton redButton;
}
class ButtonFrame extends JFrame{
public ButtonFrame(){
setTitle("ButtonTest");
setSize(300,300);
addWindowListener(new WindowAdapter(){
public void WindowClosing(WindowEvent e){
System.exit(0);
}
});
Container contentPane = getContentPane();
contentPane.add(new ButtonPanel());
}
}
public class ButtonTest
{ public static void main(String[] args)
{ JFrame frame = new ButtonFrame();
frame.show();
}
}
import java.awt.event.*;
import javax.swing.*;
class ButtonPanel extends JPanel implements ActionListener{
public ButtonPanel(){
yellowButton = new JButton("yellow");
blueButton = new JButton("blue");
redButton = new JButton("red");
add(yellowButton);
add(blueButton);
add(redButton);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getActionCommand();
Color color = getBackground();
if (source == yellowButton) color = Color.yellow;
else if (source == blueButton) color = Color.blue;
else if (source == redButton) color = Color.red;
setBackground(color);
repaint();
}
private JButton yellowButton;
private JButton blueButton;
private JButton redButton;
}
class ButtonFrame extends JFrame{
public ButtonFrame(){
setTitle("ButtonTest");
setSize(300,300);
addWindowListener(new WindowAdapter(){
public void WindowClosing(WindowEvent e){
System.exit(0);
}
});
Container contentPane = getContentPane();
contentPane.add(new ButtonPanel());
}
}
public class ButtonTest
{ public static void main(String[] args)
{ JFrame frame = new ButtonFrame();
frame.show();
}
}
|
Object source=evt.getActionCommand()得到的是一个String.改成Object source=evt.getSource()就可以了
我帮你调试过了,给分!
我帮你调试过了,给分!