java的gui,听众不工作的私人课程
-
02-10-2019 - |
题
我正在尝试在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
}
}
然后在我的纽扣班班班上,我有一个:
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给内buttristener类带来了一个错误,我不知道为什么。我也不知道如何正确地将该课程中的Setoval称为Guiapp课程。我究竟做错了什么?
解决方案
问题是当您实施时 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()
对于对象平等。
不隶属于 StackOverflow