import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SimplePaintingDemo extends JFrame {
private PaintingPanel paintPanel;
public SimplePaintingDemo() {
paintPanel = new PaintingPanel();
paintPanel.setBackground(Color.WHITE);
this.getContentPane().add(paintPanel);
JButton button = new JButton("SWAP");
this.getContentPane().add(button, BorderLayout.SOUTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
paintPanel.swap();
}
});
}
public static void main(String[] args) {
JFrame frame = new SimplePaintingDemo();
frame.setBounds(0, 0, 500, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class PaintingPanel extends JPanel {
private BufferedImage objectToBePainted;
private BufferedImage[] images;
private int index = 0;
public PaintingPanel() {
images = new BufferedImage[2];
images[0] = createImage(100, 100, Color.BLUE, Color.ORANGE);
images[1] = createImage(200, 80, Color.BLACK, Color.GREEN);
index = 0;
objectToBePainted = images[index];
}
//Methode zum Wechseln des angezeigten Bildes
public void swap() {
index = ++index%images.length;
objectToBePainted = images[index];
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (objectToBePainted!=null) {
g.drawImage(objectToBePainted, 20, 20, null);
}
}
//Hilfsmethode um Dummy Bilder zu erzeugen
private BufferedImage createImage(int w, int h, Color color1, Color color2) {
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(color1);
g.fillRect(0, 0, w, h);
g.setColor(color2);
g.fillOval(w/3, h/3, w, h);
g.dispose();
return img;
}
}
}