要解决“ActionListener和ChangeListener更改paintComponent不起作用”的问题,您可以尝试以下方法:
boolean类型的isUpdated,并通过ActionListener或ChangeListener来更改该属性。private boolean isUpdated = false;
public void actionPerformed(ActionEvent e) {
// 更新isUpdated为true
isUpdated = true;
// 触发重绘
repaint();
}
public void stateChanged(ChangeEvent e) {
// 更新isUpdated为true
isUpdated = true;
// 触发重绘
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 在paintComponent中检查isUpdated的值
if (isUpdated) {
// 进行绘制操作
// ...
// 重置isUpdated为false
isUpdated = false;
}
}
ActionListener和ChangeListener的回调方法中,直接调用repaint()方法来触发重绘。public void actionPerformed(ActionEvent e) {
// 触发重绘
repaint();
}
public void stateChanged(ChangeEvent e) {
// 触发重绘
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 在paintComponent中根据需要进行绘制操作
// ...
}
请注意,paintComponent()方法默认是在需要重绘时自动调用的,因此请确保正确设置需要重绘的组件,并确保在需要时调用repaint()方法。