2010-07-27 167 views
0

我需要做,看起来像Java的制作方法画圆调用drawOval

public void drawCircle(int x, int y, int radius) 

,吸引与圆心和半径的圆圈画圆一个方法。 drawCircle方法需要调用drawOval。我不知道如何从drawCircle方法调用drawOval而不将Graphics传递给它。这可能吗?

继承人我有:

import java.awt.*; 
import javax.swing.*; 

class test 
{ 
    public static void main(String[] args) 
    { 
     JFrame frame = new JFrame("test"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     frame.getContentPane().add(new MyPanel()); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 
class MyPanel extends JPanel 
{ 

    MyPanel() 
    { 
     setBackground(Color.WHITE); 
     setPreferredSize(new Dimension(250,250)); 
    } 

    public void paintComponent(Graphics page) 
    { 
     super.paintComponent(page); 
     drawCircle(50,50,20); 
    } 

    private void drawCircle(int x, int y, int radius) 
    { 
     drawOval(x - radius, y - radius, radius*2, radius*2); 
    } 
} 
+0

为什么你必须通过传递图形来做到这一点? – 2010-07-27 23:47:32

+0

你不必在paintComponent中调用drawOval,比如g.drawOval(),其中g是Graphics? – Raptrex 2010-07-27 23:49:00

+0

通过“将图形传递给它”来引用Java库对象吗?发布更完整的代码。 – 2010-07-27 23:49:09

回答

3

您可以通过在Swing组件调用getGraphics()获得图形上下文。但我仍然会创建我的绘图方法来接受图形上下文。

例如

private void drawCircle(Graphics g, int x, int y, int radius) { 
    g.fillOval(x-radius, y-radius, radius*2, radius*2) 
} 

另外,

private void drawCircle(int x, int y, int radius) { 
    getGraphics().fillOval(x-radius, y-radius, radius*2, radius*2) 
} 

注意一个事实,即getGraphics()但是可以返回null。你最好在paint()方法内调用drawCircle()方法,并将它传递给Graphics上下文。

例如

public void paint(Graphics g) { 
    super.paint(g); 
    drawCircle(g, 10, 10, 5, 5); 
} 
+0

是的,但这是一个家庭作业问题。如果没有Graphics的话,那么我就告诉我的教授。 – Raptrex 2010-07-28 00:20:33

+0

谢谢,getGraphics()工作 – Raptrex 2010-07-28 00:33:06

+0

雅,即时通讯猜测它的返回null,当我在Windows上测试它,但是,它适用于OSX。 – Raptrex 2010-07-28 04:43:29

0
import java.awt.Shape; 
import java.awt.geom.Ellipse2D; 

public static Shape getCircle(final double x, final double y, final double r) { 

    return new Ellipse2D.Double(x 
      - r, y - r, r * 2d, r * 2d); 
} 

优点:

  • 您没有通过或获得图形上下文。
  • 您可以选择是否绘制或填充圆而不更改方法(例如,在paint()方法中执行g.draw(getCircle(x, y, r));g.fill...)。
  • 您使用AWT绘制方法语法来实际绘制/填充圆。
  • 你在双精度坐标中得到一个圆。

你说“drawCircle方法需要调用drawOval”,但也许你只是没有意识到替代。