1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| import java.swing.*
import java.awt.*;
public class DrawingPanel extends JPanel {
/** Program entry point.
* @param args Arguments from the command line.
*/
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DrawingPanel(), BorderLayout.CENTER);
frame.setSize(500, 500);
frame.setVisible(true);
}
});
}
/** {@inheritDoc}
*/
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension size = getSize();
Insets insets = getInsets();
int width = size.width - (insets.left + insets.right);
int height = size.height - (insets.top + insets.bottom);
Graphics2D g2d = (Graphics2D)g.create(insets.left, insets.top, width, height);
try {
drawSomething(g2d, width, height);
}
finally {
g2d.dispose();
}
}
/** Render what you want onscreen.
* @param g The graphics context in which to draw.
* @param width The width of the drawing area.
* @param height The height of the drawing area.
*/
private void drawSomething(Graphics2D g, int width, int height) {
g.setColor(Color.BLUE);
g.fillRect(50, 50, 100, 100);
g.setColor(Color.RED);
g.drawRect(100, 100, 100, 100);
}
} |
Partager