chxch0106 chxch0106
关注数: 27 粉丝数: 35 发帖数: 367 关注贴吧数: 4
Java使用线程通过开始和停止按钮来读取很多数据 读取少量数据是可以完全可以做到的,但是数据很多(至少上千条的)就不行了。现在,开始和停止按钮都只能使用一次,我想点击开始就读取数据显示出来,然后点击停止就暂停,数据不消失,然后再点击开始,又可以开始继续读取数据,如此循环,请问如何做到呢??代码如下:[code=java]package mainGui; import java.awt.*; import java.awt.event.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextArea; import javax.swing.text.AbstractDocument.Content; @SuppressWarnings({ "unused", "serial" }) class Gui extends Thread { private boolean isPaused=true; private JFrame frame = new JFrame("Demo"); private Label name; private TextArea content; private JButton start=new JButton("start"); private JButton stop=new JButton("stop"); public Gui(){ frame.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); }}); frame.setLayout(null); frame.setSize(480,620); frame.setVisible(true); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setFocusable(false); start.setBounds(180, 520, 100, 50); stop.setBounds(300, 520, 100, 50); content=new TextArea(""); content.setBounds(10, 110, 460, 400); frame.add(content); frame.add(start); frame.add(stop); start.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { if (isPaused==true) { isPaused = false; stop.setEnabled(true); //notify(); } } }); stop.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { if (isPaused==false) { isPaused = true; stop(); }}}); start(); } @Override public void run() { while (true) { while(isPaused); File file=new File("F://text2.txt"); if(file.exists()&&file.isFile()){ try{ BufferedReader input=new BufferedReader(new FileReader(file)); String text; while((text=input.readLine())!=null){ content.append(String.format("%s%n", text)); } }catch(IOException e1){ e1.printStackTrace(); System.out.println("file error"); } } } } public static void main(String [] args){ Gui gui=new Gui(); } }[/code]
1 下一页