- Don't extend
Canvas
(or even use it), but do extend JPanel
.
- add the
JPanel
to the JFrame
- (win.add(this)
)
- Your button's are filling the panel, hiding the background. Give them a size
- Add them to the
JPanel
just using add(b1)
etc
- Don't override
paint
, but do override paintComponent
. And do it as follows:
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// your stuff here
- Don't set the size of the
JFrame
. Set the size of the JPanel
. Otherwise your JFrame
border absorbs some of the size, making your panel smaller than you may want. Do it as follows.
@Override
public Dimension getPreferredSize() {
return new Dimension(500,500);
}
You still have other logic to work out but this should get you started.
Style corrections
These are not critical to the execution of your code but important to learn.
- By convention, classes begin with an upper case character.
- Use the class name, not an instance when referring to static values.
win.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…