I have a jTextField , and I set it's value to a certain sum when I create the frame.
Here is the initiation code:totalTextField.setText(
itemsPriceText开发者_运维百科Field.getText() +
Float.toString(orderDetails.delivery)
);
This textfield should show a sum of items selected by the user.
The selection is done on a different frame, and both frames are visible / invisible at a time. The user can go back and forth and add / remove items.Now, every time i set this frame visible again, I need to reload the value set to that field
(maybe no changes were made, but if so, I need to set the new correct sum) .I'm quite desperate with it.
Can anyone please give me a clue? Thanks in advance! :)Before setting the frame visible again, one should update the fields with the new values / states.
something like:
jTextField.setText("put your text here");
jRadioButton.setSelected(!isSelected());
.
/* update all you need */
.
jFrame.setVisible(true);
The frame will come up with the new values / states.
Add a WindowListener to the frame. Then you can handle the windowActivated event and reset the text of the text field.
See How to Write Window Listeners.
Use a DocumentListener triggering the JTextField public void setText(String t)
Here an example with DocumentListener:
public class SetTextInJTextField extends JFrame implements DocumentListener {
JTextField entry;
JTextField entryToSet = new JTextField();
public SetTextInJTextField() {
createWindow();
entry.getDocument().addDocumentListener(this);
}
private void createWindow() {
JFrame frame = new JFrame("Swing Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void createUI(final JFrame frame) {
JPanel panel = new JPanel();
entry = new JTextField();
entryToSet = new JTextField();
LayoutManager layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layout);
panel.add(this.entry);
panel.add(entryToSet);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
public void setTextInTargetTxtField() {
String s = entry.getText();
entryToSet.setText(s);
}
// DocumentListener methods
public void insertUpdate(DocumentEvent ev) {
setTextInTargetTxtField();
}
public void removeUpdate(DocumentEvent ev) {
setTextInTargetTxtField();
}
public void changedUpdate(DocumentEvent ev) {
}
public static void main(String args[]) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SetTextInJTextField().setVisible(true);
}
});
}
}
inspired from: https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextFieldDemoProject/src/components/TextFieldDemo.java
related lesson: https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html
精彩评论