Get value from JTextCompnent and convert it to upper case
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Main implements ActionListener {
JTextField jtf = new JTextField(10);
JButton jbtnGetTextUpper = new JButton("Get Text In Uppercase");
Main() {
JFrame jfrm = new JFrame("Demonstrate a Text Field");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(240, 140);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf.setActionCommand("TF");
jtf.addActionListener(this);
jbtnGetTextUpper.addActionListener(this);
jtf.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent ce) {
System.out.println("Text in real time: " + jtf.getText());
}
});
jfrm.add(jtf);
jfrm.add(jbtnGetTextUpper);
jfrm.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getActionCommand().equals("TF")) {
System.out.println("ENTER key pressed: " + jtf.getText());
} else {
String str = jtf.getText().toUpperCase();
System.out.println("Button pressed: " + str);
}
}
public static void main(String args[]) {
new Main();
}
}
Related examples in the same category