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.
Next you need to understand that JFrame
is a bad choice for painting to. Why? Because it's multilayered.
A JFrame
contains a JRootPane
, which contains a JLayeredPane
the contentPane
, glassPane
and the JMenuBar
and in your example, it also contains a JPanel
.
With the (default) exception of the glassPane
, all these components are opaque.
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.
A better solution is to start by extending from JPanel
and override its paintComponent
method.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…