如何使用带有油漆(或重绘)的jpanel [英] how to use jpanel with paint (or repaint)

查看:20
本文介绍了如何使用带有油漆(或重绘)的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 JPanel on 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,而是建立一个调用 repaint()ActionListener.从 Swing Timer 调用它.
  2. 有两种方法可以做到这一点.
    • 扩展一个 JComponentJPanel
    • 绘制 BufferedImage 并将其添加到 JLabel 中的 ImageIcon.
  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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆