我正在尝试用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类。我做错了什么?
答案 0 :(得分:3)
问题在于,当您实施ActionListener
时,您必须定义方法actionPerformed(ActionEvent e)
;你没有在ButtonListener
课程中那样做过。您无法将该方法命名为您想要的任何内容(正如您使用clickButton
所做的那样),因此您应该将clickButton
方法重命名为actionPerformed
(并继续添加@Override
注释也是如此)。
现在,为了从内部类中调用d.setOval
,d
方法在调用actionPerformed
方法时必须在范围内。有几种方法可以实现此目的:您可以将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()
以实现对象相等。