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书籍,找不到任何有帮助的
请注意,我不知道如何向该方法添加参数
多谢各位 汤姆
# 1 楼答案
然后你会保留一个你想画的椭圆形的列表。参见Custom Painting Approaches,它在面板上绘制了一组矩形。代码所做的只是在ArrayList中循环以绘制矩形。只需要几行代码
# 2 楼答案
这里有几点需要注意:
super.paintComponent
,除非在被重写的paintComponent
方法本身中调用李>paintComponent
方法并在那里绘制图形paintComponent
方法时,该方法中的第一条语句应该是super.paintComponent(g)
李>现在,从以上几点来看,你的代码应该是这样的:
你的
Painting
类应该是这样的: