Skip to main content

help with buttons

1 reply [Last post]
podo
Offline
Joined: 2007-04-09
Points: 0

hello,
I'm new in java and i need some help with buttons and their actions.
I need to insert buttons to perform three actions (draw lines). can anybody help?

</p>
<p>import javax.swing.*;<br />
import java.awt.*;<br />
import java.awt.geom.*;<br />
import java.awt.event.*;</p>
<p>public class antras extends JApplet {</p>
<p>  private Rectangle2D Shape4;</p>
<p>  public antras () {<br />
  	setBackground( Color.black );<br />
    Shape4 = new Rectangle2D.Float (10.F, 10.F, 480.F, 280.F);</p>
<p>  }</p>
<p>  public void paint (Graphics g) {<br />
    Graphics2D g2D;<br />
    boolean Contained;</p>
<p>    g2D = (Graphics2D) g;<br />
    g2D.setColor(Color.white);<br />
    g2D.fill (Shape4);</p>
<p>    Contained = Shape4.intersectsLine (400., 10., 480., 70.);<br />
    //first action<br />
    g2D.setColor (Color.green);<br />
    g2D.drawLine (10, 100, 489, 100);</p>
<p>    //second action<br />
    g2D.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT,<br />
                                          BasicStroke.JOIN_ROUND,<br />
                                      1f, new float[] {2f},0f));<br />
    g2D.setColor (Color.green);<br />
    g2D.drawLine (10, 140, 490, 140);<br />
    //third action<br />
    g2D.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT,<br />
                                          BasicStroke.JOIN_ROUND,<br />
                                      1f, new float[] {5f},0f));<br />
    g2D.setColor (Color.green);<br />
    g2D.drawLine (10, 200, 490, 200);</p>
<p>  }<br />
}<br />

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
tarbo
Offline
Joined: 2006-12-18
Points: 0

You can have each action add/remove a specific shape from a collection of shapes to draw. A button would add or remove a shape and request a repaint.

[code]Collection shapes;

class ShapeAction extends AbstractAction {
Shape s;
ShapeAction(Shape s) {
super(String.valueOf(s));
this.s = s;
}
public void actionPerformed(ActionEvent evt) {
if (!shapes.remove(s)) {
shapes.add(s);
}
}
}[/code]

I haven't compiled the above, so there could be an obvious miss anywhere, but it should be about that simple. ;) Once you have your actions, you can build buttons for them; you could, for instance, build toggle buttons to reflect adding or removing shapes.

Your drawing code should be fairly straightforward:

[code]public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
for (Shape s : shapes) {
g2d.draw(shape); // or fill, if you like
}
}[/code]

Hope this helps. :)

PS: I've not given the strokes or other properties you may wish to see associated with the shapes. You can pretty much add all that in the ShapeAction constructor.