gpt4 book ai didi

java - 将文本文件加载到 JtextArea 中

转载 作者:行者123 更新时间:2023-12-01 15:27:35 25 4
gpt4 key购买 nike

我已经尝试了几个小时来尝试将文本文件的内容加载到 JTextArea 中。我可以将文本加载到控制台,但不能加载到 JTextArea 我不知道我做错了什么。任何帮助表示感谢!

程序的类

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;


public class LoadClass extends JPanel
{
JPanel cards;
private JPanel card1;
private JTextArea textarea1;
private int currentCard = 1;
private JFileChooser fc;

public LoadClass()
{
Font mono = new Font("Monospaced", Font.PLAIN, 12);

textarea1 = new JTextArea();
textarea1.setFont(mono);



card1 = new JPanel();
card1.add(textarea1);




cards = new JPanel(new CardLayout());
cards.add(card1, "1");


add(cards, BorderLayout.CENTER);



setBorder(BorderFactory.createTitledBorder("Animation here"));
setFont(mono);
}

public void Open()
{
textarea1 = new JTextArea();


JFileChooser chooser = new JFileChooser();
int actionDialog = chooser.showOpenDialog(this);
if (actionDialog == JFileChooser.APPROVE_OPTION)
{
File fileName = new File( chooser.getSelectedFile( ) + "" );
if(fileName == null)
return;
if(fileName.exists())
{
actionDialog = JOptionPane.showConfirmDialog(this,
"Replace existing file?");
if (actionDialog == JOptionPane.NO_OPTION)
return;
}
try
{

String strLine;
File f = chooser.getSelectedFile();
BufferedReader br = new BufferedReader(new FileReader(f));

while((strLine = br.readLine()) != null)
{
textarea1.append(strLine + "\n");

System.out.println(strLine);

}
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}

}

主程序

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class LoadMain extends JFrame
{

private LoadClass canvas;

private JPanel buttonPanel;
private JButton btnOne;



public LoadMain()
{

super("Ascii Art Program");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());
canvas = new LoadClass();

buildButtonPanel();

add(buttonPanel, BorderLayout.SOUTH);
add(canvas, BorderLayout.CENTER);

pack();
setSize(800, 800);
setVisible(true);

}
private void buildButtonPanel()
{
buttonPanel = new JPanel();

btnOne = new JButton("Load");


buttonPanel.add(btnOne);



btnOne.addActionListener(new btnOneListener());


}
private class btnOneListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == btnOne)
{
canvas.Open();
}
}
}


public static void main(String[] args)
{
new LoadMain();
}

}

最佳答案

public void Open()
{
textarea1 = new JTextArea();

将其更改为:

public void Open()
{
//textarea1 = new JTextArea(); // or remove completely

创建的第二个字段令人困惑。

关于java - 将文本文件加载到 JtextArea 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9985095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com