这是我到目前为止编写的代码,以及我收到的错误。我确定我之前已经完成过类似的代码而没有错误。我很确定我错过了一些愚蠢的东西,但我无法弄清楚或在网上找到任何东西。
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
JPanel mainPanel = new JPanel();
JButton editButton = new JButton("Edit");
JPanel.add(editButton);
}
错误:
Syntax error on token(s), misplaced construct(s) - for the underlined '.'
on the last line
Syntax error on token "editButton", VariableDeclaratorId expected after this
token - for the underlined parameter within the brackets on the last line.
最佳答案
您正在尝试将其用作静态 方法 - 您希望将编辑按钮添加到哪个面板?您需要在 mainPanel
上调用它:
mainPanel.add(editButton);
但是,您不能在类声明中这样做——这样的声明必须在方法或构造函数中。所以你可能想要:
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
JPanel mainPanel = new JPanel();
JButton editButton = new JButton("Edit");
public MyFrame() {
mainPanel.add(editButton);
}
}
或者可能将所有初始化放入构造函数中,并使变量成为最终变量和私有(private)变量:
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
private final JPanel mainPanel;
private final JButton editButton;
public MyFrame() {
mainPanel = new JPanel();
editButton = new JButton("Edit");
mainPanel.add(editButton);
}
}
关于Java JPanel.add(...) 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8202412/