Java examples for 2D Graphics:Transform
Translate coordinate to the center of paint area
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Main extends JFrame { public static void main(String[] args) { // TODO Auto-generated method stub Main opdr = new Main(); }/* ww w . j a v a 2s . c o m*/ public Main() { super("line"); setSize(600, 600); setTitle("2D Line"); setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel panel = new JPanel(new BorderLayout()); JPanel topPanel = new JPanel(new FlowLayout()); panel.add(topPanel, BorderLayout.NORTH); JLabel statusLabel = new JLabel("Draw a Line"); topPanel.add(statusLabel); JPanel centerPanel = new Opdracht2_2a(); panel.add(centerPanel, BorderLayout.CENTER); JPanel bottomPanel = new JPanel(new FlowLayout()); panel.add(bottomPanel, BorderLayout.SOUTH); setContentPane(panel); setVisible(true); } public class Opdracht2_2a extends JPanel { public Opdracht2_2a() { setPreferredSize(new Dimension(600, 400)); } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; int t = 7; g2.translate(getWidth() / 2, getHeight() / 2); if (t <= 8 && t >= 0) { int x = (int) ((20 * t) * (Math.cos(t))); int y = (int) ((20 * t) * (Math.sin(t))); g2.drawLine(0, 0, x, y); } else System.out.println("kan niet"); } } }