When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one JPanel
. The benefit of extending Swing
components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a paint()
method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.
Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the DiceContainer
below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.
Here are the basic steps:
- Create a class that extends
JComponent
- Call parent constructor
super()
in your constructors
- Make sure you class implements
MouseListener
Put this in the constructor:
enableInputMethods(true);
addMouseListener(this);
Override these methods:
public Dimension getPreferredSize()
public Dimension getMinimumSize()
public Dimension getMaximumSize()
Override this method:
public void paintComponent(Graphics g)
The amount of space you have to work with when drawing your button is defined by getPreferredSize()
, assuming getMinimumSize()
and getMaximumSize()
return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.
And finally, the source code. In case I missed anything.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…