【发布时间】:2017-07-18 08:37:24
【问题描述】:
我有一个包含JPanel 的框架,其中包含数字从1 到9 的JButton 按钮,当按下按钮时,它应该将其图标更改为预定义的图标。
当我初始化按钮时,我向每个按钮添加一个ActionListener,如下所示:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
// do something
}
}
所有按钮都在JPanel 内,其背景与它所在的框架一样。我的问题是,当按下按钮时,我应该在actionPerformed 内调用revalidate 和repaint 吗?
我之所以这样问,是因为有时在按下按钮时,带有按钮的面板的框架背景会变形。
请查看附图以了解我的意思。
按住数字 1 或数字 4 的按钮时,背景会变形。
这种情况并不总是发生,我不知道是什么原因造成的。
谢谢。
每个按钮都扩展了一个扩展 JButton 的类,该类具有以下方法:
public void paintComponent(Graphics g) {
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
ButtonModel m = getModel();
if (m.isPressed() || m.isSelected()) {
if (on != null)
on.paintIcon(this, g, 0, 0);
} else if (!isEnabled()) {
if (disabled != null)
disabled.paintIcon(this, g, 0, 0);
} else {
if (off != null)
off.paintIcon(this, g, 0, 0);
}
if (m.isPressed() || m.isSelected())
super.paintComponent(g);
}
【问题讨论】:
-
should I call revalidate and repaint inside actionPerformed when the button is pressed?!- 没有必要这样做。每当您更改按钮的属性时,Swing 都会为您执行此操作。所以你需要做的就是调用setIcon(...)方法。I am asking this because sometimes when pressing the buttons the background of the frame holding the panel that has the buttons gets distorted.- 这不应该发生,你必须有其他导致问题的自定义绘画。 -
@camickr 感谢您的回复,不幸的是,我的代码中除了按钮之外没有任何其他绘画,而且我没有调用 setIcon 方法,我使用的是 paintComponent(Graphics g) 并在其中我愿意:icon.paintIcon(this, g, 0, 0);
-
“我没有调用 setIcon 方法,我使用的是paintComponent(Graphics g),我在其中使用:icon.paintIcon(this, g, 0, 0);"。很可能您在
paintComponent()方法开始时删除了super.paintComponent(g)调用...或者其他什么,但要知道究竟是什么导致了问题,您应该发布一个有效的minimal reproducible example,但我同意@camickr你应该使用setIcon(...)方法 -
请不要在cmets中发布代码,而是edit您的问题添加它,很难阅读它。同样,提供一个有效的minimal reproducible example 来证明该问题。您的问题可能与您程序中的某些逻辑有关
-
super.paintComponent(g);你甚至没有阅读我上面的评论,那一行应该是你的paintComponent(...) {方法中的 first 行。而且我还建议您不要跳过每个if/while/ etc 语句的花括号