Java - 如何从 Socket 更新 JProgressBar?

发布于 2024-12-21 08:32:42 字数 2872 浏览 1 评论 0原文

几周来我一直在尝试解决以下问题:(。在我的 Java 小程序 (MyApplet) 中,我有一个名为 btnSendToPC 的按钮方法,该方法应该通过打开的套接字将选定的文件内容从服务器发送到本地 PC。当我尝试实现一个 JProgressBar 来向用户显示该文件的数量已下载到本地 PC 时,就会出现问题。我在该网站上阅读了许多 JProgressBar 示例,但说实话,我仍然无法弄清楚。你帮助了我。以下是我的代码的一个非常简短的版本,包括所有主要部分。

//My Network class that opens a socket and reads bytes from the socket
public class TcpIp {

    protected Socket s = null;
    public DataInputStream dis = null;

    public TcpIp(InetAddress ipa, int port) {

        try { 
            s = new Socket(ipa.getHostAddress(), port);
        } catch (IOException ex) {
            System.out.println("Error opening socket!");
            return;
        }

        try { //Create an input stream.
            dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
        } catch (Exception ex) {
            System.out.println("Error creating input stream!");
        }

    }

    public synchronized byte[] readBytes() throws IOException {

        ByteArrayOutputStream getBytes = new ByteArrayOutputStream();

        int oneByte;

        while ((oneByte = dis.read()) != 124) {//Reads 1 byte from the InputStream and breaks on | character
            getBytes.write(oneByte);
        }

        return (getBytes.toByteArray());

    }
}

//My main Applet class that has the method for Send to PC button
public class MyApplet extends javax.swing.JApplet implements Runnable {

    public TcpIp gtp = null;
    private static String inGet;

    @Override
    public void run() {

        int i;

        byte[] in = new byte[10000024];

        try {
            Thread.sleep(1000);
            //pause gtp.readBytes so that server has enough time to receive name of the file to read,
            //to read its contents and send its contents back through socket
        } catch (InterruptedException ex) {
        }

        if ((gtp != null)) {

            try {
                in = gtp.readBytes();
            } catch (IOException ex) {
            }

            //Remove non-printing bytes.
            for (i = 0; i < in.length; i++) {
                if (in[i] < 0x20) {
                    in[i] = 0x20;
                }
            }

            inGet = new String(in);
        }
    }

    public void btnSendToPC() {

        //In here are commands that send name of the file to read. 
        //Server reads that file and sends its contents back through socket.

        try {

            FileOutputStream fout = new FileOutputStream(fn);
            BufferedWriter myOutput = new BufferedWriter(new OutputStreamWriter(fout));

            timer = new Thread(this);
            timer.start();

            try {
                timer.join();
            } catch (InterruptedException ex) {
            }

            myOutput.write(inGet)

            myOutput.close();
            fout.close();
        }

    }
}

I have been trying to fix the following problem for weeks :(. In my Java applet (MyApplet) I have a method, for a button, called btnSendToPC which is supposed to send selected file contents from server to local PC through an open socket. The problem occurs when I try to implement a JProgressBar that will show user how much of that file has been downloaded to local PC. I read many JProgressBar examples on this site but I honestly still can not figure it out. I would be very grateful if you helped me out. The following is a very short version of my code including all the major parts.

//My Network class that opens a socket and reads bytes from the socket
public class TcpIp {

    protected Socket s = null;
    public DataInputStream dis = null;

    public TcpIp(InetAddress ipa, int port) {

        try { 
            s = new Socket(ipa.getHostAddress(), port);
        } catch (IOException ex) {
            System.out.println("Error opening socket!");
            return;
        }

        try { //Create an input stream.
            dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
        } catch (Exception ex) {
            System.out.println("Error creating input stream!");
        }

    }

    public synchronized byte[] readBytes() throws IOException {

        ByteArrayOutputStream getBytes = new ByteArrayOutputStream();

        int oneByte;

        while ((oneByte = dis.read()) != 124) {//Reads 1 byte from the InputStream and breaks on | character
            getBytes.write(oneByte);
        }

        return (getBytes.toByteArray());

    }
}

//My main Applet class that has the method for Send to PC button
public class MyApplet extends javax.swing.JApplet implements Runnable {

    public TcpIp gtp = null;
    private static String inGet;

    @Override
    public void run() {

        int i;

        byte[] in = new byte[10000024];

        try {
            Thread.sleep(1000);
            //pause gtp.readBytes so that server has enough time to receive name of the file to read,
            //to read its contents and send its contents back through socket
        } catch (InterruptedException ex) {
        }

        if ((gtp != null)) {

            try {
                in = gtp.readBytes();
            } catch (IOException ex) {
            }

            //Remove non-printing bytes.
            for (i = 0; i < in.length; i++) {
                if (in[i] < 0x20) {
                    in[i] = 0x20;
                }
            }

            inGet = new String(in);
        }
    }

    public void btnSendToPC() {

        //In here are commands that send name of the file to read. 
        //Server reads that file and sends its contents back through socket.

        try {

            FileOutputStream fout = new FileOutputStream(fn);
            BufferedWriter myOutput = new BufferedWriter(new OutputStreamWriter(fout));

            timer = new Thread(this);
            timer.start();

            try {
                timer.join();
            } catch (InterruptedException ex) {
            }

            myOutput.write(inGet)

            myOutput.close();
            fout.close();
        }

    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一花一树开 2024-12-28 08:32:42

只需使用javax.swing.ProgressMonitorInputStream。为你做所有的辛苦工作。

Just use a javax.swing.ProgressMonitorInputStream. Does all the hard work for you.

雨后彩虹 2024-12-28 08:32:42

您的 TcpIp 类需要在其自己的线程中运行。然后您

SwingUtilities.invokeLater(new Runnable(){
  public void run(){
    progressBar.setValue(progressBar.getValue()+1);
  }
}

getBytes.write(oneByte); 之后

调用,但在执行此操作之前,您需要设置最大值。为此,您需要知道要读取多少字节。如果您不知道将接收多少字节,则进度条就没有意义。

我还建议不要在收到的每个字节上调用进度条更新。

Your TcpIp class needs to run in its own thread. Then you call

SwingUtilities.invokeLater(new Runnable(){
  public void run(){
    progressBar.setValue(progressBar.getValue()+1);
  }
}

after getBytes.write(oneByte);

But before you do this, you need to set a maximum. For that, you need to know how many bytes you want to read. If you don't know how many bytes will be received, a progressbar makes no sense.

I would also suggest not to call the progressbar update on every single byte received.

太阳男子 2024-12-28 08:32:42

您可以使用观察者或事件监听器更改进度条。

尝试观察者可观察来更改其他类的进度条。

You can change the progressbar using oberver or eventlistener.

Try observer-observable to change progressbar from other classes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文