我在滚动窗格中使用JTextArea时出现问题。我可以从文本文件中读取,但内容都显示在一行上。我尝试了各种方法使用追加并试图打破这条线,但没有成功。
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class SplashScreen extends JFrame implements ActionListener
{
JButton mobile;
JButton browser;
JLabel welc;
JPanel home;
File file = new File("C:\\Users\\Jimbob\\Desktop\\DisWorkspace\\TrustWizard\\welcometwo.txt");
BufferedReader reader = null;
int lines = 10;
public String read()
{
String savetext = "";
try
{
reader = new BufferedReader(new FileReader(file));
String text = null;
while((text = reader.readLine()) != null)
{
savetext += text;
}
}
catch(IOException jim)
{
jim.printStackTrace();
}
return savetext;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource().equals(mobile))
{
MobileHome openB = new MobileHome();
this.dispose();
}
if(e.getSource().equals(browser))
{
BrowserHome openB = new BrowserHome();
this.dispose();
}
}
public SplashScreen()
{
super("Trust Wizard");
JTextArea homeText = new JTextArea(25, 30);
homeText.setText(read());
JScrollPane homeScroll = new JScrollPane(homeText);
welc = new JLabel("Welcome To The Trust Wizard");
home = new JPanel();
mobile = new JButton("Mobile Wizard");
browser = new JButton("Browser Wizard");
home.add(welc);
home.add(homeScroll);
home.add(mobile);
home.add(browser);
ImageIcon img = new ImageIcon("hand.jpg");
setIconImage(img.getImage());
mobile.addActionListener(this);
browser.addActionListener(this);
getContentPane().add(home);
home.repaint();
setSize(450, 530);
setVisible(true);
}
public static void main(String args[])
{
SplashScreen test = new SplashScreen();
}
}
答案 0 :(得分:5)
不要编写自己的方法来将数据加载到JTextArea中。
//homeText.setText(read());
相反,只需使用JTextArea API提供的read()方法:
FileReader reader = new FileReader( your file name here );
BufferedReader br = new BufferedReader(reader);
homeText.read( br, null );
br.close();
答案 1 :(得分:1)
请尝试附加text
text + "\n"
public String read() {
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
String text = null;
while((text = reader.readLine()) != null) {
builder.append(text + "\n");
}
} catch(IOException jim) {
jim.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return builder.toString();
}
还添加了finally
块来关闭BufferedReader
(以及其余部分的流)
答案 2 :(得分:0)
homeText.setLineWrap(true);
应该为你做到这一点。
将该行放在您创建homeText
变量的位置之后,然后您的文字将换行到JTextArea
的大小。
还在StringBuilder
循环中放置while
,而不是使用具有大量开销的字符串连接。