我创建了一个名为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);
}
}
但这不起作用。我觉得它是测试中的太阳方法。我怎么能让这个工作?我查看了所有的java书籍,无法找到任何有用的东西。
请注意,我不在该方法中添加参数。
谢谢 汤姆。
答案 0 :(得分:2)
这里有几点需要注意:
super.paintComponent
方法本身内,否则请勿自行致电paintComponent
。paintComponent
方法并在那里绘制图形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);
}
}
答案 1 :(得分:2)
如果我想在不同的地方画50个椭圆,那么我会遇到大量代码的问题
然后,您将保留要绘制的椭圆的列表。请参阅Custom Painting Approaches,它在面板上绘制一堆矩形。所有代码都是循环遍历ArrayList来绘制Rectangle。只需要几行代码。