我无法让我的代码正常工作。我试图从input.txt文件中读取,但我不确定我做错了什么。我需要从输入文件中获取列出的项目并通过GUI显示它们。我也意识到我已经导入了很多不必要的软件包,但是我一直在做很多试验和错误来试图解决这个问题。
import java.awt.event.ActionEvent; //Next group of lines import various Java classes
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.text.*;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ReadTextFile extends JFrame
{
public static void main(String[] args) throws IOException {
//Creates Window
final JFrame frame = new JFrame();
frame.setSize(450, 300); //Sets size of the window
frame.setTitle("Read a Text File"); //Adds title to the GUI
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create labels and fields
JLabel Firstlbl = new JLabel("First Text Line");
final JTextField FirstField = new JTextField(20);
FirstField.setText("1st");
JLabel Secondlbl = new JLabel("Second Text Line");
final JTextField SecondField = new JTextField(20);
SecondField.setText("2nd");
JLabel Thirdlbl = new JLabel("Third Text Line");
final JTextField ThirdField = new JTextField(20);
ThirdField.setText("3rd");
JLabel ButtonLabel = new JLabel("Click button to read text from file.");
final JButton button = new JButton("Click Here");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4,2));
panel.add(ButtonLabel);
panel.add(button);
panel.add(Firstlbl);
panel.add(FirstField);
panel.add(Secondlbl);
panel.add(SecondField);
panel.add(Thirdlbl);
panel.add(ThirdField);
frame.add(panel);
class CalculateListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
String file_name = "/Users/diallodickerson/Documents/PRG 421/input.txt";
try {
ReadFile file = new ReadFile(file_name);
String[] arraylines = file.OpenFile();
int i;
for (i=0; i < arraylines.length; i++) {
System.out.println(arraylines[i]);
}
}
catch (IOException e) {
System.out.println( e.getMessage() );
}
}
}
ActionListener listener = new CalculateListener();
button.addActionListener(listener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}