Here is a simple graphics programs which adds some stars on the screen.
import acm.graphics.*;
import acm.program.*;
import java.awt.event.*;
import javax.swing.*;
/**
* This program creates a five-pointed star every time the
* user clicks the mouse on the canvas.
*/
public class DrawStarMap1 extends GraphicsProgram {
public void init() {
/* Initializes the mouse listeners */
addMouseListeners();
/* The check box starts out in the "on" position */
fillCheckBox = new JCheckBox("Filled");
fillCheckBox.setSelected(true);
add(fillCheckBox, SOUTH);
/* Clears the screen with a button */
add(new JButton("Clear"), SOUTH);
addActionListeners();
}
/* Called whenever the user clicks the mouse.*/
public void mouseClicked(MouseEvent e) {
GStar star = new GStar(STAR_SIZE);
star.setFilled(fillCheckBox.isSelected());
add (star, e.getX(), e.getY());
}
/* Removes all the graphical objects from the canvas */
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Clear")) removeAll();
}
/* Private constants */
private static final double STAR_SIZE = 20;
private JCheckBox fillCheckBox;
}
And the GStar class:
import acm.graphics.*;
/** Defines a new GObject class t:hat appears as a five-pointed star.
*/
public class GStar extends GPolygon {
/** Creates a new GStar centered at the origin with the specified
* horizontal width.
* @param width The width of the star
*/
public GStar(double width) {
double dx = width / 2;
double dy = dx * GMath.tanDegrees(18);
double edge = width / 2 - dy * GMath.tanDegrees(36);
addVertex(-dx, -dy);
int angle = 0;
for (int i = 0; i < 5; i++) {
addPolarEdge(edge, angle);
addPolarEdge(edge, angle + 72);
angle -= 72;
}
}
}
The program works fine and uses a GStar class constructor to create a star whenever the user clicks the mouse on the canvas. But, there is one problem: "The JCheckBox and JButton never change visually!". When I press the "Clear" JButton the canvas becomes empty but the button does not seem to toggle. Similarly the program draws both filled and empty stars but the "Filled" JCheckBox remains always selected, it doesn't change. The problem becomes even bigger with the JSlider I use in other programs. The slider remains always at the initial position, even if it works in some sense: its value changes. I use Eclipse, 2011 version and the latest JRE library (v.7u6 http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1637588.html). I haven't found sufficient info on the Internet. What is the problem? Thank you for your help!! The acm package can be downloaded from here http://jtf.acm.org/acm.jar