notes from Liang(2009), p.478
How to draw in Java:
1. create a class that extends JPanel
2. override paintComponent()
The paintComponent() is automatically invoked to paint graphics when the component is first displayed or whenever the component needs to be redisplayed.
import javax.swing.*;
import java.awt.Graphics;
import java.awt.*;
public class TestDrawPanel extends JFrame {
public TestDrawPanel()
{
JPanel dp = new DrawPanel();
dp.setBackground(Color.ORANGE);
add(dp);
// 3. add JPanel to the JFrame
}
public static void main(String[] args)
{
TestDrawPanel tdp = new TestDrawPanel();
tdp.setTitle("TestDrawPanel");
tdp.setSize(300,200);
tdp.setLocationRelativeTo(null);
tdp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tdp.setVisible(true);
}
class DrawPanel extends JPanel
{
// to draw, 1. create a class that extends JPanel
protected void paintComponent(Graphics g)
{
// 2. override the paintComponent()
//
super.paintComponent(g);
g.setColor(Color.RED);
g.drawLine(10,10, 70, 70);
g.drawRect(30,50 ,150, 100);
}
}
}
Keine Kommentare:
Kommentar veröffentlichen