【问题标题】:Leaving a trace while painting on a transparent JPanel在透明的 JPanel 上绘画时留下痕迹
【发布时间】:2013-11-30 21:08:44
【问题描述】:

我是 Java 中相对较新的图形程序员,这是我正在尝试的一个简单程序。这是完整的代码:分为 3 个类。

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



    }
}

第 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();

    }
}

如果我注释掉语句 setOpaque(false); 在第 1 课中,我得到了一条(红色扩展矩形的)痕迹,但没有得到黄色背景。 否则我没有得到任何痕迹,但我确实得到了黄色背景。 我想要黄色背景和痕迹。 请随时修改我的代码,以便我同时获得跟踪和黄色背景。 我提供了完整的代码,因此可以轻松查看输出。

【问题讨论】:

    标签: java swing graphics awt paintcomponent


    【解决方案1】:

    基本上,每次调用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);
    

    即使我为您发布的这段代码也不正确。不应在 paintComponent() 方法中更新 x/y 值。尝试在代码执行时调整框架大小,看看为什么?

    您的 ActionListener 应该调用您的 panel1 类中的一个方法来更新该类的属性,以告诉 paintComponent() 在调用时迭代和绘制正方形的次数。 paintComponent() 方法应该在我创建的循环中引用此属性。

    【讨论】:

    • 感谢 camickr 的回答,很抱歉未能早点回复。但这并不是我想要的。在您修改后的程序中,我仍然没有从以前的 paintComponent() 调用中留下任何痕迹。我只是用一个 paintComponet() 调用来完成整个绘画。
    • @user3015246,没错。 Swing 的设计初衷不是留下痕迹。为了展示你的扩展方块,你需要从头开始重做整幅画。还有另一种选择,您可以通过绘制到 BufferedImage 来进行增量绘制。但是然后赢得 paintComponent() 方法,您仍然需要绘制整个图像。但这比从头开始重做整幅画更有效。有关此示例,请参见 Custom Painting Approaches 中的 DrawOnImage 示例。
    • 哦,我没有注意到您发布了答案。但这不是我想要的。例如,如果我注释掉 setOpaque(false); 它确实会留下痕迹。线。我唯一没有得到的是背景颜色。
    猜你喜欢
    • 2019-04-15
    • 1970-01-01
    • 2023-04-05
    • 2015-07-08
    • 2019-04-16
    • 2011-12-30
    • 2019-06-09
    • 1970-01-01
    • 2010-11-04
    相关资源
    最近更新 更多