JTextArea not displaying text

前端 未结 3 1527
梦谈多话
梦谈多话 2021-01-19 07:31

In my function for displaying text in textarea,i have written following lines of code but it is not displaying any text

        jTextArea1.setText( Packet +\         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-19 08:09

    Since your code snippet is just too small to give a correct answer I can think of:

    1. When you are inside the update of jTextArea, Packet is null? Can you check that.

    2. While calling this method is jTextArea has any text on it ? If none and Packet is null you wont see any result.

    Edit: As per comment:

    To append text use append, also read the tutorial

    Though I would expect setText to show the text atleast first time, see below a bare minimum example code:

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    
    public class TestJTextArea {
        static void init() {
            JFrame frame = new JFrame();
            frame.setLayout(new BorderLayout());
            final JTextArea textArea = new JTextArea();
            frame.add(textArea, BorderLayout.NORTH);
            final JTextField textField = new JTextField();
            frame.add(textField,BorderLayout.CENTER);
            JButton button = new JButton("Add");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    textArea.setText(textField.getText());
                }
            });
            frame.add(button,BorderLayout.SOUTH);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            init();
        }
    }
    

    And with that I also agree with @Hovercraft Full Of Eels that you may have a Swing threading issue, or just use append to append text

提交回复
热议问题