Zdravim, snazim se udelat jednoduchy program, ktery prepise text z textfieldu do labelu.
Protoze potrebuju opisovat po praci s vice ovladacimi prvky, tak to asi musim resit akci.
Kdyz priradim akci buttonu, neni problem. Kdyz ji ale dam textfieldu, tak to nic nedela. Pritom kdyz textfildu pridam KeyListener(keyReleased) tak to funguje.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Okno {
private JFrame frame;
private JTextField textField;
JLabel lblNewLabel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Okno window = new Okno();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Okno() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 248, 158);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
Action lblWrite = new AbstractAction("opsat text") {
@Override
public void actionPerformed(ActionEvent e) {
lblNewLabel.setText(textField.getText());
}
};
textField = new JTextField();
/* //funguje
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
lblNewLabel.setText(textField.getText());
}
});
*/
textField.setBounds(10, 11, 196, 20);
textField.setAction(lblWrite);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.setAction(lblWrite);
btnNewButton.setBounds(10, 42, 196, 23);
frame.getContentPane().add(btnNewButton);
lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(10, 76, 196, 14);
frame.getContentPane().add(lblNewLabel);
}
}
Poradite mi prosim, kde delam chyu a jak ji opravit?