我的问题是,当我按下按钮时,应该调用paintComponent,然后在JPanel上绘制一个图形,不幸的是,paintComponent在程序加载时绘制图形,在这种情况下该按钮是无用的。
我制作了程序的一个小版本,以便轻松快速地读取和检测问题。 这里的代码不是原始代码,但它演示了同样的问题。
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class TestPaint extends JPanel implements ActionListener {
private JButton button_1 = new JButton( "Draw Oval" );
public TestPaint() {
add(button_1);
}
@Override
public void actionPerformed(ActionEvent e) {
if ( e.getSource() == button_1 )
repaint();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(10, 10, 100, 100);
}
}
运行程序
import javax.swing.JFrame;
public class RunPaint {
public static void main(String[] args) {
TestPaint paint_g = new TestPaint();
JFrame frame = new JFrame("Testing");
frame.add(paint_g);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
最佳答案
作为一个简单的解决方案,您可以为您的类创建一个实例变量:
private Boolean buttonPressed = false;
然后在您的 actionListener 中将值设置为 true。
并在您的paintComponent()方法中添加如下代码:
if (buttonPressed)
g.drawOval(...);
更好(也更复杂的解决方案)是保留要绘制的对象的List
。最初列表将为空,当您按下按钮时,您将一个对象添加到列表中。然后绘制代码只是迭代列表来绘制对象。
查看Custom Painting Approaches以获得更多想法。示例代码并没有完全做到这一点,但它确实展示了如何从列表中进行绘制。
关于java - PaintComponent 自己进行绘画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27792237/