我是一个相对较新的 Java 图形程序员,这是我正在尝试的一个简单程序。这是完整的代码:分为 3 个类。
Class 1:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyPanelB extends JPanel
{
int x=0;
int y=0;
public void paintComponent(Graphics g)
{
x=x+1;
y=y+1;
setOpaque(false);
//setBackground(Color.cyan);
g.setColor(Color.red);
g.fillRect(x,y,x+1,y+1);
}
}
Class 2:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyFrameB implements ActionListener
{
MyPanelB p1;
public void go()
{
JFrame f1= new JFrame();
f1.setLocation(150,50);
f1.setSize(800,700);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p0= new JPanel();
p0.setBackground(Color.yellow);
p0.setLayout(new BorderLayout());
f1.add(p0);
p1= new MyPanelB();
p0.add(p1);
f1.setVisible(true);
Timer t = new Timer(200,this);
t.start();
}
public void actionPerformed(ActionEvent ev)
{
p1.repaint();
}
}
第三班(主班):
public class MyBMain
{
public static void main(String[] args)
{
MyFrameB m1= new MyFrameB();
m1.go();
}
}
如果我注释掉该声明设置不透明(假);在第一类中,我得到了(红色扩展矩形的)痕迹,但没有黄色背景。
否则我不会得到任何痕迹,但我会得到黄色背景。
我想要黄色背景和痕迹。
请随意修改我的代码,以便我同时获得跟踪和黄色背景。
我提供了完整的代码,以便人们可以轻松查看输出。
基本上,每次调用 PaintComponent() 方法时,您都需要重新绘制整个组件。这意味着您需要从 0 开始迭代到 x 的当前值。
所以你的paintComponent()方法应该类似于:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
x=x+1;
y=y+1;
for (int i = 0; i < x; i++)
{
g.setColor(getForeground());
//g.fillRect(x,y,x+1,y+1);
g.fillRect(i,i,i+1,i+1);
}
}
这意味着您不需要 panel0。我还更改了创建 panel1 的代码:
p1= new MyPanelB();
p1.setForeground(Color.RED);
p1.setBackground(Color.YELLOW);
f1.add(p1);
即使我为您发布的这段代码也不正确。 x/y 值不应在 PaintComponent() 方法中更新。尝试在代码执行时调整框架大小,看看为什么?
您的 ActionListener 应调用 panel1 类中的一个方法来更新该类的属性,以告诉 PaintComponent() 在调用时要迭代并绘制正方形多少次。 PaintComponent() 方法应该在我创建的循环中引用此属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)