我有一个按钮。我要在单击后更改背景。我的问题是按钮自动调用paintCompenent()。如何预防呢?我希望单击按钮后,该按钮将为蓝色,但仍为红色
package test;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ButtonDemo extends JButton implements ActionListener{
public ButtonDemo() {
this.setText("FUCK YOU");
this.addActionListener(this);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.RED);
}
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel contentPane = new JPanel();
frame.setContentPane(contentPane);
contentPane.add(new ButtonDemo());
frame.setSize(500, 500);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
this.setBackground(Color.BLUE);
}
}
您在paintComponent
替代中将背景设置为红色。
您完全不需要覆盖paintComponent
即可获得想要的效果。
这里是更新的代码。我添加了几行。
import java.awt.BorderLayout;
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;
import javax.swing.SwingUtilities;
public class ButtonDemo extends JButton
implements ActionListener {
private static final long serialVersionUID = 1L;
public ButtonDemo() {
this.setText("F*CK YOU");
this.setBackground(Color.RED);
this.addActionListener(this);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Button Demo");
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
frame.setContentPane(contentPane);
contentPane.add(new ButtonDemo());
frame.setSize(500, 500);
frame.setVisible(true);
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
this.setBackground(Color.BLUE);
}
}