有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用awt。方法中的图形

我创建了一个名为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方法。现在,我尝试在一个名为Painting的类中的paintcomponent方法中实现它

//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书籍,找不到任何有帮助的

请注意,我不知道如何向该方法添加参数

多谢各位 汤姆


共 (2) 个答案

  1. # 1 楼答案

    If i want to draw 50 ovals on different places then i would have a problem with extensive code

    然后你会保留一个你想画的椭圆形的列表。参见Custom Painting Approaches,它在面板上绘制了一组矩形。代码所做的只是在ArrayList中循环以绘制矩形。只需要几行代码

  2. # 2 楼答案

    这里有几点需要注意:

    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);
       }
    }