问题描述
importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;importjava.util.*;publicclassButtonTest{publicstaticvoidmain(String[]args){ButtonFrameframe=newButtonFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}}classButtonFrameextendsJFrame{publicButtonFrame(){setTitle("ButtonTest");setBounds(100,100,300,200);ButtonPanelpanel=newButtonPanel();add(panel);}}/**********classButtonPanelextendsJPanel{publicButtonPanel(){JButtonyellowButton=newJButton("yellow");JButtonblueButton=newJButton("blue");JButtonredButton=newJButton("red");add(yellowButton);add(blueButton);add(redButton);//********为每个颜色构造一个对象,并将这些对象设置为按钮监听器***ColorActionyellowAction=newColorAction(Color.YELLOW);ColorActionblueAction=newColorAction(Color.BLUE);ColorActionredAction=newColorAction(Color.RED);yellowButton.addActionListener(yellowAction);//为事件源添加监听器对象blueButton.addActionListener(blueAction);redButton.addActionListener(redAction);}classColorActionimplementsActionListener{publicColorAction(Colorc){backgroundColor=c;}publicvoidactionPerformed(ActionEventevent){setBackground(backgroundColor);}ColorbackgroundColor;}//ColorbackgroundColor;}*************/classButtonPanelextendsJPanelimplementsActionListener{publicButtonPanel(){JButtonyellowButton=newJButton("yellow");JButtonblueButton=newJButton("blue");JButtonredButton=newJButton("red");add(yellowButton);add(blueButton);add(redButton);yellowButton.addActionListener(this);blueButton.addActionListener(this);redButton.addActionListener(this);}publicvoidactionPerformed(ActionEventevent){JButtonbt=(JButton)event.getSource();if(bt==yellowButton)setBackground(Color.YELLOW);elseif(bt==blueButton)setBackground(Color.BLUE);elseif(bt==redButton)setBackground(Color.RED);}}
解决方案
解决方案二:
格式复制过来,就不好看了,大家见谅呀
解决方案三:
解决方案四:
建议楼主调好格式,去javase板块里发帖子
解决方案五:
importjava.awt.Color;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JPanel;publicclassButtonTest{publicstaticvoidmain(String[]args){ButtonFrameframe=newButtonFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}}classButtonFrameextendsJFrame{publicButtonFrame(){setTitle("ButtonTest");setBounds(100,100,300,200);ButtonPanelpanel=newButtonPanel();add(panel);}}classButtonPanelextendsJPanelimplementsActionListener{privateStringCMD_YELLOW="yellow";privateStringCMD_BLUE="blue";privateStringCMD_RED="red";publicButtonPanel(){JButtonyellowButton=newJButton(CMD_YELLOW);JButtonblueButton=newJButton(CMD_BLUE);JButtonredButton=newJButton(CMD_RED);add(yellowButton);add(blueButton);add(redButton);yellowButton.addActionListener(this);blueButton.addActionListener(this);redButton.addActionListener(this);}publicvoidactionPerformed(ActionEvente){if(CMD_YELLOW.equals(e.getActionCommand())){setBackground(Color.YELLOW);}elseif(CMD_BLUE.equals(e.getActionCommand())){setBackground(Color.BLUE);}elseif(CMD_RED.equals(e.getActionCommand()))setBackground(Color.RED);}}