这是一个简单的图形程序,它在屏幕上添加了一些星星。
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;
}
和 GStar 类:
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;
}
}
}
该程序运行良好,每当用户在画布上单击鼠标时,它都会使用 GStar 类构造函数来创建星形。但是,有一个问题:“JCheckBox 和 JButton 在视觉上永远不会改变!”。当我按下“清除”JButton 时,画布变为空,但按钮似乎没有切换。同样,该程序同时绘制填充和空星,但“填充”JCheckBox 始终保持选中状态,它不会改变。我在其他程序中使用的 JSlider 问题变得更大。滑块始终保持在初始位置,即使它在某种意义上起作用:它的值发生了变化。我使用 Eclipse,2011 版本和最新的 JRE 库(v.7u6 http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1637588.html)。我没有在互联网上找到足够的信息。问题是什么?感谢您的帮助!!acm 包可以从这里下载http://jtf.acm.org/acm.jar