我正在尝试用 Java 制作一个 GUI,使用的是以下几行:
public class GUIApp
{
DrawingPanel dp;
buttonPanel bp;
ova = Oval;
public GUIApp()
{
JFrame win = new JFrame("Drawing App");
dp = new DrawingPanel();
bp = new buttonPanel(this);
//Settings for panels and frame
ova = new Oval(100,100,100,100);
}
public void setOval(int c){
//Change color of oval
}
}
然后在我的 buttonPanel 类中我有这个:
public class ButtonPanel extends JPanel
{
private JButton btnRed, btnGreen, btnBlue;
public ButtonPanel(GUIApp d)
{
ButtonListener listener = new ButtonListener();
btnRed = new JButton("Red");
btnGreen = new JButton("Green");
btnBlue = new JButton("Blue");
btnRed.addActionListener(listener);
btnGreen.addActionListener(listener);
btnBlue.addActionListener(listener);
setBackground(Color.lightGray);
GridLayout grid = new GridLayout(3,1);
add(btnRed,grid);
add(btnGreen,grid);
add(btnBlue,grid);
}
private class ButtonListener implements ActionListener{
public void clickButton(ActionEvent event) {
Object location = event.getSource();
if (location == btnRed){
d.setOval(1);
}
else if(location == btnGreen){
d.setOval(2);
}
else if(location == btnBlue){
d.setOval(3);
}
}
}
}
但 netbeans 给出了内部 ButtonListener 类的错误,我不知道为什么。我也不知道如何从该类中正确调用 setOval 到 GUIApp 类。我做错了什么?
最佳答案
问题是,当您实现 ActionListener
时,您必须定义方法 actionPerformed(ActionEvent e)
;你还没有在你的 ButtonListener
类中这样做。您不能随意命名该方法(就像您对 clickButton
所做的那样),因此您应该将 clickButton
方法重命名为 actionPerformed
(并继续添加一个 @Override
注释)。
现在,为了从您的内部类中调用 d.setOval
,当 actionPerformed
方法被调用时,d
必须在范围内。有几种方法可以实现这一点:您可以使 d
成为您类的成员变量,或者您可以将 ButtonListener
定义为匿名类。
例如,如果您将 d
保存为成员变量,那么您的代码将如下所示:
public class ButtonPanel {
private GUIApp d;
public ButtonPanel(GUIApp d) {
this.d = d;
// The rest of your code here...
}
}
或者,您可以使用这样的匿名类:
public ButtonPanel(GUIApp d) {
ActionListener listener = new ActionListener(){
@Override
public void actionPerformed(ActionEvent event) {
Object location = event.getSource();
if (btnRed.equals(location)) {
d.setOval(1);
} else if (btnGreen.equals(location)) {
d.setOval(2);
} else if (btnBlue.equals(location)) {
d.setOval(3);
}
}
};
// The rest of your constructor code here ...
}
注意:请注意我还如何将 ==
的使用更改为 equals()
以实现对象相等。
关于java - Java 中的 GUI,监听器的私有(private)类不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3698195/