【问题标题】:Using awt.Graphics in a method在方法中使用 awt.Graphics
【发布时间】:2013-03-31 16:06:42
【问题描述】:

我创建了一个名为 Test 的类,很可能是我出错的地方。

import javax.swing.JPanel;
import java.awt.*;
public class Test extends JPanel {

Graphics grap;
public void sun()
{
    super.paintComponent(grap);
    grap.setColor(Color.YELLOW);
    grap.fillOval(0,0,20,20);
}
}

如您所见,我想使用一种方法在面板的左上角绘制一个黄色的“椭圆形”,但我没有使用 PaintComponent 方法。现在我尝试在我的 Paint 组件方法中实现它,该方法位于一个名为 Painting 的类中。

//import...;
public class Painting extends JPanel{

   protected void paintComponent(Graphics g)
   {
      Test test = new Test();

      test.sun();

   }

现在我创建了一个主窗口,它将创建一个面板并显示黄色椭圆形。

//import...
public class main extends JFrame{
    public static main(String [] args){

        JFrame window = new JFrame();
        window.add(new Painting());
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(100,100);
        window.setLocationRelativeTo(null);
        window.setVisible(true);

    }

}

但这不起作用。我有一种感觉,这是测试中的sun方法。我该如何让它工作?我查看了所有的 Java 书籍,但找不到任何可以提供帮助的内容。

请注意,我并没有给方法添加什么参数。

谢谢 汤姆。

【问题讨论】:

  • 什么是CelestialDisplayPanel
  • Test 中,grap 不会一直是null

标签: java swing jpanel java-2d paintcomponent


【解决方案1】:

这里有几点需要注意:

  1. 切勿自己调用 super.paintComponent,除非在被覆盖的 paintComponent 方法本身内。
  2. 如果你想做一些图形活动,那么重写paintComponent 方法并在那里绘制图形
  3. 当您覆盖paintComponent 方法时,该方法中的第一条语句应该是super.paintComponent(g)

现在,按照以上所有要点,您的代码现在应该是这样的:

public class Test extends JPanel {

 public void paintComponent(Graphics grap)
 {
    super.paintComponent(grap);
    grap.setColor(Color.YELLOW);
    grap.fillOval(0,0,20,20);
 }
}

你的Painting 类应该是这样的:

public class Painting extends JPanel{
   Test test;
   public Painting()
   {
     test = new Test();
     setLayout(new BorderLayout());
     add(test);
   }
}

【讨论】:

  • 如果我想在不同的地方绘制 50 个椭圆,那么我会遇到大量代码的问题
  • 您想在同一面板的不同位置绘制 50 个椭圆?
  • 然后您可以在Test JPanel 本身上执行此操作。
  • 谢谢。只是为了确保你不能用某种方法绘画?
  • 不,你不能。您应该始终覆盖paintComponent 方法。如果进行了一些更改,例如从外部更改坐标......然后调用 repaint ,Swing 将自行为您完成所有工作。
【解决方案2】:

如果我想在不同的地方绘制 50 个椭圆,那么我会遇到大量代码的问题

然后,您将保留要绘制的椭圆的列表。请参阅Custom Painting Approaches,它在面板上绘制了一堆矩形。代码所做的只是循环遍历 ArrayList 以绘制 Rectangle。只需要几行代码。

【讨论】:

    猜你喜欢
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2012-03-21
    • 2015-04-07
    • 1970-01-01
    相关资源
    最近更新 更多