我的程序打开一个文件,允许您查看或编辑它,然后再次保存。到目前为止,我只有 GUI 布局。
因此,当我尝试编译程序时,出现以下错误:
FileChooser.java:26: error: <identifier> expected
fileChooser = newJFileChooser();
我得到了 ^^^ 错误四次,对于我初始化的每个组件一次。
FileChooser.java:39: error: invalid method declaration; return type required
public FileChooserGUI() {
尝试创建构造函数时出现此^^^ 错误。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
public class FileChooser extends JFrame { //JFrame is a container class in Swing
//declare all components and other variables
private JTextArea textArea; //b
private JButton openFileButton; //c
private JButton saveFileButton;
private JButton clearButton;
//Declare and initialize a JFileChooser object using JFileChooser's
//default constructor.
private JFileChooser fileChooser;
fileChooser = newJFileChooser();
//Declare and initialize a FileNameExtensionFilter object for .txt files.
private FileFilter fileFilter;
fileFilter = new FileNameExtensionFilter("text file", "txt");
//Set the JFileChooser object's current file filter by calling it's
//setFileFilter method and passing it the filter you created in e.
fileChooser.setFileFilter(fileFilter);
//constructor - initialize all components, add them to the container,
//create listener objects, register them to listen for events
public JFileChooserLabGUI() {
//call superclass constructor
super("File Chooser");
//initialize all components
textArea = new JTextArea();
openFileButton = new JButton("Open");
saveFileButton = new JButton("Save");
clearButton = new JButton("Clear");
//create and register the listener object with
//sources of events (the JButtons in this example)
listener = new JFileChooserListener();
openFileButton.addActionListener(listener);
saveFileButton.addActionListener(listener);
clearButton.addActionListener(listener);
//arrange components in the window
//Create a layout manager object and set this window's
//layout manager to it
textPanel = new JPanel();
textPanel.setLayout(new GridLayout(1,2));
textPanel.add(textArea);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,3,15,0));
buttonPanel.add(openFileButton);
buttonPanel.add(saveFileButton);
buttonPanel.add(clearButton);
this.setLayout(new GridLayout(3,1));
//Add components to the container
this.add(textPanel);
this.add(buttonPanel);
}//end of constructor
}//end of class
我还没有完成侦听器类,但我认为这与仅显示 GUI 以确保布局正确无关?
我注意到当我在同一行中声明和初始化时,我没有收到这四个错误。我初始化有什么问题吗?