I've started working on a project for my Java class - LAN gomoku/five in a row. The game board is represented by a 2-dimensional array filled with buttons (JButton). With the event handler (class clickHandler) I want to draw an oval on the button that I click (the parameter of a clickHandler object). My following code hasn't worked though (I don't know how to get rid of the null-value of variable g)... I'd appreciate any piece of advice. Thank You a lot.
class clickHandler implements ActionListener {
JButton button;
Dimension size;
Graphics g;
public clickHandler(JButton button) {
this.button = button;
this.size = this.button.getPreferredSize();
}
@Override
public void actionPerformed(ActionEvent ae) {
this.g.setColor(Color.BLUE);
this.g.fillOval(this.button.getHorizontalAlignment(), this.button.getVerticalAlignment(), this.size.width, this.size.height);
this.button.paint(this.g);
this.button.setEnabled(false);
}
}
(In a class that creates the GUI - the game board full of buttons - I assign each button a new Action Listener - an instance of clickHandler) this way:
gButton.addActionListener(new clickHandler(gButton));
You have to:
paintComponent(Graphics g)
method.Do override
getPreferredSize()
method, which will return onDimension
object and will help theLayout Manager
in placing yourJButton
on theContainer/Component
, by providing it one appropriate size.Make your circle code there.
add an onClickListener, and set a flag on the clicked button if it is clicked, and call it to repaint.
About the
Graphics
object: it's best to keep it in it'spaintComponent
method, and to use it only there. It will always get passed in on a repaint, and if you save it for other moments, strange things can happen (happy experimenting :) ).A small Example :