如何使用jpanel与油漆

如何使用jpanel与油漆

本文介绍了如何使用jpanel与油漆(或重绘)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是油漆/图形的新手,并且想知道如何将JPanel添加到我的代码中,使得整个图形将在JPanel上,而不是在JFrame上。

I'm a newbie to the paint/graphics and wonder how to add a JPanel to my code in such way that the entire graphics will be on a JPanel and not on the JFrame.

换句话说,我正在尝试创建一个允许我这样做的GUI:右边的
显示JPanel上行的良好移动左侧是
,添加一个JTextArea(在JPanel上),它将显示图形的协调性。

In other words, I'm trying to create a GUI that will allow me to do this:on the RIGHT side show the nice movement of the lines on a JPanelon the LEFT side, add a JTextArea (on a JPanel) that will show the coordination of the graphics.


  • 这是一个更大问题的简化,但我想这里的代码更容易理解。

谢谢!!!

(下图,移动行或只是运行代码)

(picture below, moving lines or simply run the code)

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JFrame;

public class Test extends JFrame implements Runnable
{
    private Line2D line;

public Test()
{
    super("testing");
    this.setBounds( 500, 500, 500, 500 );
    this.setVisible( true );
}

public void paint( Graphics g )
{
    Graphics2D g2 = (Graphics2D) g;
    g2.draw(line);
}

@Override
public void run()
{
    int x=50;
    while (true)
    {
        try
        {
            Thread.sleep( 50 );

            line = new Line2D.Float(100+x, 100+x, 250-x, 260+x%2);
            x++;
            repaint();
            if (x==5000)
                break;

        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}

public static void main (String args[])
{
    Thread thread = new Thread (new Test());
    thread.start();
}
}

推荐答案


  1. 而不是实现 Runnable ,建立一个 ActionListener ,调用 repaint()。从Swing 计时器调用它。

  2. 有两种方法可以做到这一点。


    • 扩展 JComponent JPanel

    • BufferedImage 中绘制并将其添加到 ImageIcon 中的 JLabel

  1. Instead of implementing Runnable, establish an ActionListener that calls repaint(). Call it from a Swing Timer.
  2. There are 2 ways to do this.
    • Extend a JComponent or JPanel
    • Draw in a BufferedImage and add that to an ImageIcon in a JLabel.






..问题是什么?哦,对,如果可以推断出问题是如何将其他组件与自定义绘制的组件结合起来? - 使用嵌套布局。请参阅。

如果使用 BufferedImage 支持商店,您可以将其放置在该示例中的图像中,除了您将忽略上面的 JTable ,以及 JSplitPane

If using a BufferedImage as backing store, you might place it like the image in that example, except that you would leave out the JTable above that, as well as the JSplitPane.

这篇关于如何使用jpanel与油漆(或重绘)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:10