2010-01-25 90 views
1

我无法得到这个椭圆在JFrame上绘图。在Jframe上绘图

static JFrame frame = new JFrame("New Frame"); 
public static void main(String[] args) { 
    makeframe(); 
    paint(10,10,30,30); 
} 

//make frame 
public static void makeframe(){ 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    JLabel emptyLabel = new JLabel(""); 
    emptyLabel.setPreferredSize(new Dimension(375, 300)); 
    frame.getContentPane().add(emptyLabel , BorderLayout.CENTER); 
    frame.pack(); 
    frame.setVisible(true); 
} 

// draw oval 
public static void paint(int x,int y,int XSIZE,int YSIZE) { 
    Graphics g = frame.getGraphics(); 
    g.setColor(Color.red); 
    g.fillOval(x, y, XSIZE, YSIZE); 
    g.dispose(); 
} 

该框架显示,但没有画任何东西。我在这里做错了什么?

回答

8

您已经创建了不静态方法重写paint方法。现在,其他人已经指出,你需要重写paintComponent等,但一个快速解决你需要这样做:

public class MyFrame extends JFrame{ 

    public MyFrame(){ 
      super("My Frame"); 

      //you can set the content pane of the frame 
      //to your custom class. 

      setContentPane(new DrawPane()); 

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

      setSize(400, 400); 

      setVisible(true); 
    } 

     //create a component that you can actually draw on. 
     class DrawPane extends JPanel{ 
     public void paintComponent(Graphics g){ 
      //draw on g here e.g. 
      g.fillRect(20, 20, 100, 200); 
     } 
    } 

    public static void main(String args[]){ 
      new MyFrame(); 
    } 

    } 

然而,正如有人指出的......画上一个JFrame是非常棘手的。最好使用JPanel。

+0

这是真正的问题。他的绘画方法从未被调用过。 – 2010-01-25 19:27:47

+1

答案显然是错误的:JFrame!是一个JComponent并且没有paintComponent。虽然您可以实施该方法,但在正常绘画过程中从未调用该方法。没有原来的优势;-) – kleopatra 2011-03-31 14:06:30

+0

@ kleopatra。绝对正确的是你。我已经改进了答案以反映你的观点。 – 2011-03-31 14:21:05

1

几个项目浮现在脑海中:

  1. 永不覆盖paint()方法,这样做的paintComponent(),而不是
  2. 你为什么在JFrame直接在画什么?为什么不扩展JComponent(或JPanel)并用它来代替?它提供了更大的灵活性
  3. JLabel的目的是什么?如果它位于JFrame的顶部并覆盖整个东西,那么您的绘画将隐藏在标签后面。
  4. 绘画代码不应该依赖paint()中传递的x,y值来确定绘图例程的起始点。 paint()用于绘制组件的一部分。在画布上画出你想要的椭圆。

另外,您没有看到JLabel,因为paint()方法负责绘制组件本身以及子组件。重写paint()方法是邪恶=)

0

要覆盖了错误的paint()方法,你应该重写名为的paintComponent这样的方法:

@Override 
public void paintComponent(Graphics g) 
+1

这是为什么upvoted? JFrame不是JComponent,因此没有paintComponent。 – csvan 2014-01-30 15:33:41

0

你需要重写一个现实的绘图方法,它实际上是为你的框架定日期。在你的情况下,你只是创建了不被Frame默认调用的自定义新方法。

所以你的方法改成这样:

public void paint(Graphics g){ 

}