I have been looking for the cause of this behavior in my code for quite some time. I don’t want to dive too deep into the Swing API to understand why this is happening. I would appreciate any information on the causes of this problem.
This is a simplified version of the application that I am writing, problems arise when I click the button for the first time, the image will not be drawn on the panel, but when I click on it for the second time, the image is perfect. Any drawing done will work correctly, but the original paint problem annoys me a lot. Thanks for any help! :)
public class ImageTester {
public static void main(String[] args) {
final JFrame window = new JFrame("Image Tester");
final JPanel pane = new JPanel();
JButton draw = new JButton("Draw");
JButton paint = new JButton("Paint");
Toolkit k = Toolkit.getDefaultToolkit();
final Image i = k.createImage("tester.jpg");
draw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println(pane.getGraphics());
pane.getGraphics().drawRect(5, 5, 15, 15);
pane.getGraphics().drawImage(i, 15, 15, null);
System.out.println("Performance");
}
});
paint.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
pane.add(draw);
pane.add(paint);
window.add(pane);
window.setVisible(true);
window.setSize(new Dimension(400, 400));
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
source
share