Re: Extract current text from JavaTextField
stevenruiz@gmail.com wrote:
Hello All,
I have a question regarding the JTextField. I have the below code
which is initiated when the user clicks on a start button from the
interface:
private JButton getStartButton() {
if (startButton == null) {
startButton = new JButton();
startButton.setBounds(new Rectangle(283, 66, 71, 22));
startButton.setText("Start");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
sStartPushed = true;
System.out.println(jTextField.getText());
System.out.println("actionPerformed()"); // TODO Auto-generated
Event stub
}
});
}
return startButton;
}
Inside of the action listener for this button, it prints out the text
for the textField associated with the button. Unfortunately, the text
it returns is not the current text that was just typed inside of it.
How do I get the current text? I have also tried
jTextField.getSelectedText() which does not get the current value
inside of the textField. Any comments or suggestions would be
appreciated.
As Sabine said, the problem lies in the code you are hiding from us.
Here is an SSCCE that uses your code and which does *not* have the
problem you describe.
----------------------------- 8< ------------------------------------
public class ButtonAndTextField {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ButtonAndTextField();
}
});
}
JTextField jTextField = new JTextField("Hello",10);
JButton startButton;
boolean sStartPushed = false;
ButtonAndTextField() {
JPanel p = new JPanel();
p.add(jTextField);
p.add(getStartButton());
JFrame f = new JFrame("ButtonAndTextField");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
// OP's method verbatim
private JButton getStartButton() {
if (startButton == null) {
startButton = new JButton();
startButton.setBounds(new Rectangle(283, 66, 71, 22));
startButton.setText("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sStartPushed = true;
System.out.println(jTextField.getText());
System.out.println("actionPerformed()");
}
});
}
return startButton;
}
}
----------------------------- 8< ------------------------------------
There's some things I find odd about getStartButton:
- The variable startButton should probably be local.
- Calling setBounds() is usually an evil thing to do.
- Why call setText() when you can use use new JButton("Start");
- Setting sStartPushed as a side effect feels intrinsically bad.
Surely that more naturally belongs in the actionListener.
--
RGB