Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Trying to make a button but don't know where to start

 
Mack Grill
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I'm trying to make a button that will change the color of the block when clicked.

Just need to know how to set the actionListener for the colors


here is the code that I'm working with:

 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Box would need a color field
in box's display(), 'g' would be set to that color before drawing
actionListener would change the respective box's color to whatever, and call repaint()
 
Mack Grill
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, don't use actionListener for this class?

Also, when you're saying that class Box will need a color field, are you saying to change all color values and replace them with set.Color statements?

side note: Just noticed that I didn't submit this in beginning java so my apologizes for that
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> So, don't use actionListener for this class?

actionListener is needed. from previous reply
"actionListener would change the respective box's color to whatever, and call repaint()"

> Also, when you're saying that class Box will need a color field...

look at the constructor
new Box(0 * boxSize , 0*boxSize, boxSize, boxSize, new Color(0* 255/ gridSize, 0* 255/ gridSize , 0));

unless Box() is a JButton and new Color(0* 255/ gridSize, 0* 255/ gridSize , 0) is used to set its background in the constructor, a field would be needed.

> are you saying to change all color values and replace them with set.Color statements?

are you trying to change the color of a single box/button when clicked, or are all boxes/buttons to be the same color when one of them is clicked?
if a single box/button, then you would need a color field, so that display(), which is method of Box(), can set g's color prior to painting/drawing
e.g.
let's say you want to change the color of (Box) b1 to (could be random color, anything) Color.RED
in the actionListener (after determining source is b1, if needed) the code would go something like this
b1.setColor(Color.RED); //or b1.setColor(color);// where 'color' is set some other way
repaint();// or Grid.this.repaint();//depends on how its set up
so, from repaint() which calls paint(), in turn calls b1.display(g);
and in dislpay(g), would be
g.setColor(color); //just previously set to Color.RED
g.fill/draw/whatever;//and it would be done in Color.RED



 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic