简体   繁体   English

我可以在静态上下文中以某种方式使用非静态变量吗?

[英]Can I somehow use a non-static variable in a static context?

I'm new in Java and I have some trouble with my code. 我是Java的新手,我的代码有些麻烦。

Is possible to use a non-static method, displayText.setText from JTextArea class in my static class Displaying ? 是否可以在我的静态类Displaying中使用 JTextArea类的非静态方法displayText.setText

Thanks a lot for any kind of help! 非常感谢您的任何帮助!

Here's my code: 这是我的代码:

public class GUI extends javax.swing.JFrame {
    Thread send, receive, abc;
    public String x;
    private String response, nonStaticString;

    public GUI() {
        initComponents();
        abc = new Thread(new Displaying());
        abc.start();
        receive = new Thread(new Receiving(this));
        receive.start();
    }

    private static class Displaying implements Runnable {

        private final ArrayList<String> myArray = new ArrayList();
        static BlockingQueue<String> queue = new LinkedBlockingQueue();
        String s;

        @Override
        public void run() {
            while (true) {
                try {
                    s = queue.take();
                    myArray.add(s);
                    for (String myArray1 : myArray) {
                        //System.out.println(myArray1);

                        displayText.setText(myArray);

                    }

                } catch (InterruptedException ex) {
                    Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    public void setStringToShow(String stringToShow) throws InterruptedException {
        this.response = stringToShow;
        //displayText.setText(response);
        Displaying.queue.put(stringToShow);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        sendButton = new javax.swing.JButton();
        getTheText = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        displayText = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        exitButtom = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        sendButton.setText("Send The Message!");
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        getTheText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getTheTextActionPerformed(evt);
            }
        });

        jLabel1.setText("Witam w komunikatorze kliencie 2");

        displayText.setEditable(false);
        displayText.setColumns(20);
        displayText.setRows(5);
        jScrollPane2.setViewportView(displayText);
        displayText.getAccessibleContext().setAccessibleParent(this);

        jLabel2.setText("Write something to your Friend");

        exitButtom.setText("Wyjscie");
        exitButtom.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtomActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 182, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addGap(85, 85, 85)
                        .addComponent(exitButtom))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(getTheText)
                            .addComponent(jScrollPane2)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(sendButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))))
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(exitButtom)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(47, 47, 47)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(getTheText, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sendButton)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        x = getTheText.getText();
        System.out.println("String: " + x);
        send = new Thread(new Sending(x));
        send.start();
        getTheText.setText("");

    }                                          

    private void getTheTextActionPerformed(java.awt.event.ActionEvent evt) {                                           
        getTheText.getText();
    }                                          

    private void exitButtomActionPerformed(java.awt.event.ActionEvent evt) {                                           
        System.exit(0);
    }                                          


    // Variables declaration - do not modify                     
    public javax.swing.JTextArea displayText;
    private javax.swing.JButton exitButtom;
    public javax.swing.JTextField getTheText;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    public javax.swing.JButton sendButton;
    // End of variables declaration                   

Make displayText a member of your GUI class and pass it to the constructor of the Displaying class. 使displayText成为GUI类的成员,并将其传递给Displaying类的构造函数。

But there's an other problem. 但是还有另一个问题。 You must not call SWING code from a non Swing thread. 您不得从非Swing线程调用SWING代码。 Have a look at SwingUtilities.invokeLater() about how to solve this problem. 查看有关如何解决此问题的SwingUtilities.invokeLater()

No you can't. 不,你不能。 The code will not compile. 该代码将无法编译。 Static methods "belong" to the class while non static variables belong to each instance of the class. 静态方法“属于”该类,而非静态变量则属于该类的每个实例。 When you are in the context of a class you can't know yet what the variable value will be and it might be different for several instances. 当您处于类的上下文中时,您仍然不知道变量值是什么,并且在某些实例中可能有所不同。

No, non - static variables/methods can't be used in static references. 不,非静态变量/方法不能在静态引用中使用。 As, non-static variables depends on the state of the object while static references don't. 因此,非静态变量取决于对象的状态,而静态引用则不然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM