无法访问线程运行中的方法()

时间:2014-07-03 23:35:05

标签: java multithreading swing awt

我的代码是:

public class clientsocket extends JFrame implements Runnable {

    public JTextArea chatbox;

    public clientsocket() {
        getContentPane().setLayout(null);
        chatbox = new JTextArea();
        chatbox.setBounds(20, 36, 404, 187);
        getContentPane().add(chatbox);
    }

    void checkconnection() {

        clientsocket obj1 = new clientsocket();
        Thread t1 = new Thread(obj1);
        t1.start();
    }

    public void run() {
        System.out.println("Step4");
        String responseLine;
        try {
            while ((responseLine = br.readLine()) != null) {
                System.out.println(responseLine);
                ipaddr.setText(responseLine);
                if (responseLine.indexOf("*** Bye") != -1) {
                    break;
                }
            }
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }

    }

}

所有System.out.println()run()方法中都正常工作。但我无法在chatbox方法中更改run()的内容。

为什么我无法访问run()方法中的chatbox

1 个答案:

答案 0 :(得分:2)

这是设置GUI的方法。

enter image description here

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class clientsocket {

    public JTextArea chatbox;
    JPanel ui;

    public clientsocket() {
        ui = new JPanel(new BorderLayout(3, 3));
        // pad around the GUI
        ui.setBorder(new EmptyBorder(30, 20, 30, 20));

        // suggest a size in rows x cols
        chatbox = new JTextArea(12, 36);
        //chatbox.setBounds(20, 36, 404, 187); // set a border/cols instead
        ui.add(new JScrollPane(chatbox)); // default is CENTER
        getContentPane().add(ui);
    }

    public JComponent getUi() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            public void run() {
                clientsocket cs = new clientsocket();
                JFrame f = new JFrame("Chat Client");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                f.add(cs.getUi());

                f.pack(); // sets the GUI the smallest it can be to display the content
                f.setMinimumSize(f.getSize()); // enforce a mimimum size
                // See http://stackoverflow.com/a/7143398/418556 for demo.
                f.setLocationByPlatform(true);
                f.setVisible(true); // Should be last.
            }
        };
        SwingUtilities.invokeLater(r);
    }
}