Skip to content

Instantly share code, notes, and snippets.

@yukeehan
Created May 16, 2018 21:02
Show Gist options
  • Save yukeehan/fdff03874b97953a903a7ef82a1d75a6 to your computer and use it in GitHub Desktop.
Save yukeehan/fdff03874b97953a903a7ef82a1d75a6 to your computer and use it in GitHub Desktop.
Swing JBotton, JFrame , Jlabel and JTextFiled
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.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TFDemo implements ActionListener {
JTextField jtf;
JButton jbtnRev;
JLabel jlabPrompt, jlabContents;
TFDemo() {
// TODO Auto-generated constructor stub
JFrame jfrm = new JFrame("Use a Text Field");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(240, 120);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf = new JTextField(10);
jtf.setActionCommand("myTF");
JButton jbtnRev = new JButton("Reverse");
jtf.addActionListener(this);
jbtnRev.addActionListener(this);
jlabPrompt = new JLabel("Enter text:");
jlabContents = new JLabel("");
jfrm.add(jlabPrompt);
jfrm.add(jtf);
jfrm.add(jbtnRev);
jfrm.add(jlabContents);
jfrm.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("Reverse")) {
String orgStr = jtf.getText();
String resStr = "";
for(int i = orgStr.length()-1; i>=0; i--) {
resStr += orgStr.charAt(i);
}
jtf.setText(resStr);
}else
jlabContents.setText("you passed enter. text is " + jtf.getText());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TFDemo();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment