大家给看一下怎么没有背景色!import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;class JButtonTest extends JFrame {
JButtonTest() {
JButton yellowButton = new JButton("yellow"); JButton blueButton = new JButton("blue"); JButton redButton = new JButton("red"); ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.blue);
ColorAction redAction = new ColorAction(Color.red); yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction); JPanel jp = new JPanel(); jp.add(yellowButton);
jp.add(blueButton);
jp.add(redButton);
jp.setLayout(new GridLayout(1, 3));
/*
 * add(yellowButton); add(blueButton); add(redButton);
 */
this.add(jp);
} class ColorAction implements ActionListener { private Color BackgroundColor; public ColorAction(Color c) { BackgroundColor = c;
} public void actionPerformed(ActionEvent e) { setBackground(BackgroundColor); } }
}public class TestAction { public static void main(String args[]) { JButtonTest jbt = new JButtonTest(); jbt.setLocation(300, 300);
jbt.setSize(300, 200);
jbt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbt.setLayout(new FlowLayout(FlowLayout.LEFT));
// jbt.pack();
jbt.setVisible(true);
}
}

解决方案 »

  1.   


    public void actionPerformed(ActionEvent e) { ((JButton)e.getSource()).setBackground(BackgroundColor); } 
      

  2.   

    我想让背景变一下颜色为什么Button变了!
      

  3.   

    因为你是把这个事件对像放在按钮里那里的,像你所需要的就要改一下。首先这个事件的源是Button,你要改变它们容器的颜色
    ((JButton)e.getSource()).setBackground(BackgroundColor);  就在这个地方改动一下就可以了。public void actionPerformed(ActionEvent e) {  Component frame = SwingUtilities.getRoot((JButton)e.getSource());
    ((JFrame)frame).getContentPane().setBackground(BackgroundColor);