且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用ActionListener在JPanel上绘制形状?

更新时间:2023-12-05 09:22:16

我要做的第一件事是通读执行自定义绘画,以更好地了解绘画过程的工作原理.

The first thing I would do is have a read through Painting in Swing and Performing custom painting to better understand how the painting process works.

接下来,您需要了解JFrame是绘画的一个不好的选择.为什么?因为它是多层的.

Next you need to understand that JFrame is a bad choice for painting to. Why? Because it's multilayered.

JFrame包含一个JRootPane,其中包含一个JLayeredPanecontentPaneglassPaneJMenuBar,在您的示例中,它还包含一个JPanel.

A JFrame contains a JRootPane, which contains a JLayeredPane the contentPane, glassPane and the JMenuBar and in your example, it also contains a JPanel.

除了glassPane的(默认)例外,所有这些组件都是不透明的.

With the (default) exception of the glassPane, all these components are opaque.

虽然可以在paint方法中显示某些东西来显示它,但是如果其他任何组件自己绘制,则将其擦拭干净-这是因为Swing组件实际上可以彼此独立地绘制,并且先让父母自己绘画.

While it's possible to have something drawn in the paint method show it, if any of the other components paint themselves, it will be wiped clean - this is because Swing components can actually be painted independently of each other, with having to have the parent paint itself first.

更好的解决方案是从JPanel扩展并覆盖其paintComponent方法.

A better solution is to start by extending from JPanel and override its paintComponent method.

为简单起见,我也鼓励您也针对此类实现ActionListener,它将允许actionPerformed方法访问组件的属性,并且在您的情况下,调用repaint可以当您要更新用户界面时,触发绘画循环.

For simplicity, I'd also encourage you to implement the ActionListener against this class as well, it will allow the actionPerformed method to access the properties of the component and, in your case, call repaint to trigger a paint cycle when you want to update the UI.