简体   繁体   中英

Java, NetBeans IDE and JTextField

it's a shame that my first question on SO is so stupid but i can't manage to get around this thing.

After hours of "distilling" i have reduced the issue to this:

Using Netbeans i've made a JFrame, and put a Jbutton1 and a JTextField(named sinonimo) in it. The idea is to use the text field to grab user input. so i set the onClick action of the button like this

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      

    System.out.println(sinonimo.getText());

}                  

Problem is: i can type anything in the text field, the getText() method will return only the string set in the "text" properties in Netbeans, it will never change.

Am i missing something huge about java? can someone point me in the right direction?

EDIT: while copying the complete code i found the problem: in the constructor of the frame, initComponents() was called two times, generating another copy of the textfield inaccessible from the MouseClicked event(i think). Now everything seem to work nicely, thank you guys for the lighting responses!

Using a JTextField, if you call getText() it will return null should the index be out of range or the Document is null. If you could post more code I could help further with this issue. With the following code this works perfectly fine.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test {

    public static void main(final String[] args) {
        final JFrame frame = new JFrame();
        final JButton button = new JButton("Print");
        final JTextField field = new JTextField();
        frame.setLayout(new BorderLayout());
        frame.add(button, BorderLayout.NORTH);
        frame.add(field, BorderLayout.SOUTH);
        frame.setVisible(true);
        frame.pack();
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(field.getText());
            }
        });
    }

}

From what I can see, until you post more code, is that either the method you print it from is not being used, the document is returning null or that the sinonimo instance was not added correctly and doesn't function how it should.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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