我正在与两个JPanels 一起工作。一个面板包含一个默认移动的移动球,另一个面板有两个JRadioButton标记为On和的 s Off。我坚持的部分是禁用和启用允许用户单击面板以重新定位球的MouseListener( )。P2.java我创建了函数turnOn并turnOff使用ActionListener( P1.java) 触发。这开始和停止球。我尝试使用removeActionListener,但是编译器会抛出我无法使用该方法的错误。
此外,在这个例子ItemListener中使用like会更容易,这样当已经选择它时它会被忽略?JRadioButton
P1.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class P1 extends JPanel
{
private JRadioButton on = new JRadioButton("On", true);
private JRadioButton off = new JRadioButton("Off");
public P1()
{
ButtonGroup group = new ButtonGroup();
group.add(on);
group.add(off);
add(on);
add(off);
ButtonHandler bh = new ButtonHandler();
on.addActionListener(bh);
off.addActionListener(bh);
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == on) turnOn();
if(ae.getSource() == off) turnOff();
}
}
public static void turnOn () {
Ball.dx = 1;
Ball.dy = 1;
}
public static void turnOff () {
Ball.dx = 0;
Ball.dy = 0;
}
}
P2.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class P2 extends JPanel implements MouseListener
{
public P2()
{
super();
addMouseListener(this);
}
public void mousePressed(MouseEvent e)
{
ball.x = e.getX();
ball.y = e.getY();
repaint();
}
...
}
项目的其余部分