我无法将下面链接的代码完全按照我的意愿去做。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Gui {
static JFrame frame;
static JLabel label;
public static void main (String[] args) {
Gui gui = new Gui();
gui.go();
}
public void go () {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,300);
frame.setVisible(true);
MyDrawPanel panel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, panel);
label = new JLabel("I'm a label");
frame.getContentPane().add(BorderLayout.WEST, label);
JButton colorButton = new JButton("Change Colors");
ColorButtonListener colorButtonListener = new ColorButtonListener();
colorButton.addActionListener(colorButtonListener);
frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
JButton labelButton = new JButton("Change Label");
LabelButtonListener labelButtonListener = new LabelButtonListener();
labelButton.addActionListener(labelButtonListener);
frame.getContentPane().add(BorderLayout.EAST, labelButton);
}
}
class ColorButtonListener implements ActionListener {
JFrame frame = Gui.frame;
public void actionPerformed (ActionEvent event) {
frame.repaint();
}
}
class LabelButtonListener implements ActionListener {
JLabel label = Gui.label;
public void actionPerformed (ActionEvent event) {
if (label.getText() == "That hurt") {
label.setText("I'm a label");
} else {
label.setText("That hurt");
}
}
}
class MyDrawPanel extends JPanel {
public void paintComponent (Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int red = (int) (Math.random() * 256);
int green = (int) (Math.random() * 256);
int blue = (int) (Math.random() * 256);
Color startColor = new Color(red, green, blue);
red = (int) (Math.random() * 256);
green = (int) (Math.random() * 256);
blue = (int) (Math.random() * 256);
Color endColor = new Color(red, green, blue);
GradientPaint gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
g2d.setPaint(gradient);
g2d.fillOval(0, 0, this.getWidth(), this.getHeight());
}
}
有一个用于绘制圆的面板类,然后面板位于框架的中心区域。
标签位于框架的西部区域,两个按钮colorButton(位于南侧)和labelButton(位于东侧)应分别控制圆圈和标签。 2个类ColorButtonListener和LabelButtonListener实现ActionListener接口,并分别使用colorButton和labelButton注册。单击时的颜色按钮应绘制一个随机颜色的圆圈,单击时标签按钮应在文本“我是一个标签”和“那个受伤”之间切换。
现在,我遇到的问题是标签按钮。单击它时,它不仅会更改文本(按预期方式),还会重绘圆圈。此按钮不应重绘圆圈。颜色按钮按预期工作。
答案 0 :(得分:2)
这是因为如果新文本与旧文本不同,setText()
方法会在内部调用repaint()
。因此,无论何时单击该按钮都会导致颜色发生变化。
答案 1 :(得分:2)
问题是您无法控制何时可能发生重绘。每次调用paintComponent
时都无法更改颜色,而无法控制,只有当您想要并在paintComponent
方法中引用时才更改颜色,例如
class MyDrawPanel extends JPanel {
private Color startColor;
private Color endColor;
// And setters or some other way
// to randomise the colors
public void paintComponent (Graphics g) {
Graphics2D g2d = (Graphics2D) g;
GradientPaint gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
g2d.setPaint(gradient);
g2d.fillOval(0, 0, this.getWidth(), this.getHeight());
}
}