In Swing use a (non-opaque) JComponent or a(n opaque) JPanel and override the
paintComponent method for custom graphics. Although you can use an AWT/heavyweight Canvas you may have problems later — see
Mixing heavy and light components for more.
The general idea for custom drawing is to set up the
paintComponent method to be ready to draw its enclosing classes state at any time and to adjust/change the state from within event code.
See the JComponent
paint method for perspective about the various painting methods and how they relate. You can override
paint and the other two but it is generally for more advanced work.
Lesson: Performing Custom Painting has basic concepts.
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class Drawing extends JPanel implements ActionListener {
Random seed = new Random();
Color color = Color.red;
public void actionPerformed(ActionEvent e) {
color = getColor();
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int cx = getWidth()/2;
int cy = getHeight()/2;
int d = 75;
g2.setPaint(color);
g2.fillOval(cx-d/2, cy-d/2, 75, 75);
}
private Color getColor() {
return new Color(seed.nextInt(0xffffff));
}
private JPanel getUIPanel() {
JButton button = new JButton("change");
button.addActionListener(this);
JPanel panel = new JPanel();
panel.add(button);
return panel;
}
public static void main(String[] args) {
Drawing test = new Drawing();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(test);
f.add(test.getUIPanel(), "Last");
f.setSize(400,400);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}