我在下面的课程中使用了一些交互器。所有这些功能都完美无缺,即他们做我想做的事。但是,它们在视觉上不起作用。例如,当我按下旨在清除屏幕的 JButton 时,它会这样做,但 JButton 不会按下。这对于 JButton 来说很好,但对于 Radio Buttons 来说却是个问题。当我单击切换单选按钮时,我可以切换屏幕上的内容,但单选按钮的选择不会切换。为什么会这样?我已经盯着代码看了好几个小时,就是想不通。(我希望我的描述很清楚......这是代码......)。可以在此处找到 acm 库的文档。
package forces;
import java.util.*;
import javax.swing.*;
import acm.graphics.*;
import java.awt.event.*;
public class InteractiveClosedSystem extends ClosedSystem {
private GOval newMass;
private JRadioButton positiveRB;
private JRadioButton negativeRB;
public void init() {
masses = new ArrayList<Mass>();
add(new JButton("Clear"), SOUTH);
initRadioButtons();
addActionListeners();
addMouseListeners();
addKeyListeners();
}
private void initRadioButtons() {
// Radio button group for charge
ButtonGroup chargeBG = new ButtonGroup();
positiveRB = new JRadioButton("Positive");
negativeRB = new JRadioButton("Negative");
// Add all radio buttons to button group
chargeBG.add(positiveRB);
chargeBG.add(negativeRB);
// Set initial radio button selection
positiveRB.setSelected(true);
// Add all radio buttons to control bar
add(new JLabel(" Charge"), SOUTH);
add(positiveRB, SOUTH);
add(negativeRB, SOUTH);
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Clear")) {
masses.removeAll(masses);
removeAll();
}
}
public void mouseClicked(MouseEvent e) {
newMass = new GOval(e.getX(), e.getY(), 30, 30);
newMass.setFilled(true);
if (positiveRB.isSelected()) {
newMass.setColor(Mass.POSITIVE_COLOR);
} else {
newMass.setColor(Mass.NEGATIVE_COLOR);
}
add(newMass);
}
}