0
我一直試圖花幾個小時嘗試將文本文件的內容加載到JTextArea中。我能夠將文本加載到控制檯中,但不能加入到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();
}
}
嘗試將行存儲在一個字符串中,然後textArea.setText()? – Giannis 2012-04-02 23:21:28
1)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 2)請學習常見的[Java命名約定](http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#73307)(具體用於名稱的情況)類,方法和屬性名稱並一致使用它。 – 2012-04-02 23:22:49
這是功課嗎? – Peter 2012-04-02 23:34:43