package linedrawexample; import java.awt.*; import javax.swing.JFrame; import javax.swing.JPanel; public class LineDrawExample extends JFrame { public static void main(String[] args) { LineDrawExample frame=new LineDrawExample(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new MyPanel()); frame.setVisible(true); } } class MyPanel extends JPanel { @Override public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; g2.drawLine(0, 0, 100, 100); } } 要在JPanel里面画,不能直接在JFrame中用paint画,那样线会以窗体的左上角为起点,而不是可绘制区域的左上角。