我的代码:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
public class TAFrame {
private JFrame mainFrame;
private JPanel mainPanel;
private JButton button;
private JTextArea textArea; //eclipse say Syntax error } expected
mainFrame = new JFrame("mainFrame");
mainPanel = new JPanel();
button = new JButton("click me");
area = new JTextArea(10, 15);
}
找不到解决方案,但我认为这很令人尴尬:/
最佳答案
我相信您想将一些代码放入构造函数中,如下所示:
public class TAFrame {
private JFrame mainFrame;
private JPanel mainPanel;
private JButton button;
private JTextArea textArea;
public TAFrame() {
mainFrame = new JFrame("mainFrame");
mainPanel = new JPanel();
button = new JButton("click me");
area = new JTextArea(10, 15);
}
}
问题在于您尝试在任何方法之外执行任意代码。声明字段后,您需要通过方法访问它。只能在同一行上初始化它,因此您可以执行以下操作:
public class TAFrame {
private JFrame mainFrame = new JFrame("mainFrame");
private JPanel mainPanel = new JPanel();
private JButton button = new JButton("click me");
private JTextArea textArea = new JTextArea(10, 15);
}
在这种情况下,我建议使用构造函数方法,但无论哪种方式,您都最需要构造函数,因为您可能想向按钮添加一个 Action 监听器(例如)。
关于java - 为什么 eclipse 会在这里生成语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18836259/