[code=Java][/code]
package cn.com.lintl39227;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.*;
public class MusicPlayer
{
/**
* @param args
*/
public static void main(String[ ] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new MusicFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setOpacity(0.75f);
//frame.getContentPane().setBackground(Color.LIGHT_GRAY); //这样可以设置面板的背景色
frame.setVisible(true);
}
}
class MusicFrame extends JFrame
{
private JFileChooser chooser;
private JTextArea textArea;
private JMenuBar menuBar;
public Runnable r;
public Thread t;
public MusicFrame()
{
chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
textArea = new JTextArea("");
textArea.setLineWrap(true); //自动换行功能
textArea.setWrapStyleWord(true); //断行不断字功能
textArea.setFont(new Font("方正行楷_GBK", Font.PLAIN, 13));
textArea.setEditable(false);
add(textArea, BorderLayout.CENTER);
r = new display(chooser, textArea);
t = new Thread(r);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenuItem open = new JMenuItem("Open");
fileMenu.add(open);
open.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
work();
}
});
}
protected void work()
{
t.start();
}
}
class display implements Runnable
{
private JFileChooser chooser;
private JTextArea textArea;
public display(JFileChooser chooser, JTextArea textArea)
{
this.chooser = chooser;
this.textArea = textArea;
}
public void run()
{
int result = chooser.showOpenDialog(null); //打开一个选择对话框
if(result == JFileChooser.APPROVE_OPTION)
{
textArea.setText("");
try
{
File file = chooser.getSelectedFile();
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
line = in.readLine();
while(line != null)
{
textArea.append(line);
textArea.append("\n");
Thread.sleep(1000);
line = in.readLine();
}
in.close();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}
[code=Java][/code]
在第二次打开文档的时候就出错 请问该怎么解决呢?
谢谢
------解决方案--------------------------------------------------------
代码不是把文件内容显示在文本域吗? 没有读文本域啊?
------解决方案--------------------------------------------------------
我感觉是你那个work函数的毛病,因为你第一次点open的时候就调用了这个方法,t线程就运行了,你又点open,就是将运行中的线程又执行了一次start
------解决方案--------------------------------------------------------
- Java code
protected void work() { if(t.isAlive()){ t.stop(); } r = new display(chooser, textArea); t = new Thread(r); t.start(); }