Java Netbeans 覆盖 JPanel 中的paint() 方法 [英] Java Netbeans override paint() method in a JPanel

查看:34
本文介绍了Java Netbeans 覆盖 JPanel 中的paint() 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新手程序员
我想使用 Netbeans IDE 开发 Java 程序的 GUI

Hi I'm a newbie programmer
I want to develop a Java program's GUI using Netbeans IDE

使用 Netbeans GUI 构建器,
首先,我创建一个新的 JFrame 表单
然后,我从工具栏/调色板添加一个 JPanel

Using Netbeans GUI Builder,
First, I create a new JFrame Form
Then, I add a JPanel from the toolbar/palette

问题是,
如何覆盖新创建的 JPanelpaint() 函数?

Question is,
How can I override the paint() function of the newly created JPanel ?

我想在JPanel中绘制背景和一些球体,
我尝试使用 getGraphics() 函数来绘制和绘制,它可以完成工作,但是当我调用 repaint()

I want to draw a background and some spheres inside the JPanel,
I tried using getGraphics() function to paint and draw, it does the job, but it won't draw anymore when I call repaint()

我是否应该使用我的自定义 paint() 函数创建一个实现 JPanelJComponent 的新类?
(如果是这样,我如何使用 Netbeans GUI Builder 来做到这一点?)

Should I create a new class implementing JPanel or JComponent, with my custom paint() function, instead ?
(If it so, how can I do it with Netbeans GUI Builder?)

类似问题:

如何使用带有油漆(或重新油漆)的 jpanel

(但它不使用 Netbeans GUI Builder)

(but it doesn't use Netbeans GUI Builder)

推荐答案

通常的方法是创建自己的 JPanel 子类(例如 MyJPanel)并实现paint() 方法在那里.

The usual way to do this is to create your own JPanel subclass (e.g. MyJPanel) and implement the paint() method there.

实现该类后,切换到表单,选择面板,然后使用面板属性的代码"选项卡中的自定义创建代码"来创建 MyJPanel 的实例JPanel

After you implemented that class, switch to your form, select the panel and then use "Custom creation code" in the the "Code" tab of the panel's properties to create an instance of MyJPanel instead of JPanel

这有一个轻微的缺点,即每次您想访问在 MyJPanel 中定义但不在 MyJPanel>JPanel.如果您永远不需要这样做,这是最快的方法.

This has the slight disadvantage that you will need to cast the instance variable to MyJPanel each time you want to access methods that are defined in MyJPanel but not in JPanel. If you never need to do that, this is the quickest method.

如果您想访问面板类中的其他方法(每次不强制转换实例变量),删除现有的 JPanel 并使用新类添加Bean"会更容易.

If you want to access additional methods in your panel class (without casting the instance variable each time), it's easier to remove the existing JPanel and add a "Bean" using the new class.

这是通过单击调色板中的选择 Bean"按钮来完成的:

This is done by clicking on the "Choose Bean" button in the palette:

单击确定"后,您可以将面板放在表单上,​​NetBeans 将创建 MyJPanel 类型的实例变量(而不是 JPane),您可以访问该类中定义的所有方法.请注意,必须先编译该类,然后才能以这种方式添加它!

Once you click OK you can place the panel on your form and NetBeans will create an instance variable of the type MyJPanel (instead of JPane) and you can access all methods defined in that class. Note that the class must be compiled before you can add it that way!

这篇关于Java Netbeans 覆盖 JPanel 中的paint() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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