Simple Java program that demonstrate the JTextField, JButton, JFrame and JLabel!
SLVIKI
11:16 PM
0
This is a simple program that when we type a word in the Text Field it will give us the reversed word of that word after pressing the button. In order to do that I've used JFrame, JButton, JTextField and JLabel in this program.
Here is the java code of the program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | // Use a text field. import java.awt.*; import java.awt.event.*; import javax.swing.*; class TFDemo implements ActionListener { JTextField jtf; JButton jbtnRev; JLabel jlabPrompt, jlabContents; TFDemo() { // Create a new JFrame container. JFrame jfrm = new JFrame("Use a Text Field"); // Specify FlowLayout for the layout manager. jfrm.setLayout(new FlowLayout()); // Give the frame an initial size. jfrm.setSize(260, 140); // Terminate the program when the user closes the application. jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create a text field jtf = new JTextField(10); // set the action cmmand for the text field. jtf.setActionCommand("myTF"); // create the reverse button JButton jbtnRev = new JButton("Reverse"); // add action listeners. jtf.addActionListener(this); jbtnRev.addActionListener(this); // create the labels. jlabPrompt = new JLabel("Enter text: "); jlabContents = new JLabel(""); // add the components to the content pane. jfrm.add(jlabPrompt); jfrm.add(jtf); jfrm.add(jbtnRev); jfrm.add(jlabContents); // Display tht frame jfrm.setVisible(true); } // Handle action events. public void actionPerformed(ActionEvent ae) { if(ae.getActionCommand().equals("Reverse")) { // The reverse button was pressed. String orgStr = jtf.getText(); String resStr = ""; // reverse the string in the text field. for (int i=orgStr.length()-1; i >= 0; i--) resStr += orgStr.charAt(i); // store the reversed string in the text field. jtf.setText(resStr); } else // enter was pressed while focus was in the // text field. jlabContents.setText("You pressed ENTER. text is: " + jtf.getText()); } public static void main (String args[]) { // create the frame on the event dispatching thread. SwingUtilities.invokeLater(new Runnable() { public void run() { new TFDemo (); } }); } } |
Here is the output of that program.
If you have any questions, feel free to ask!
Enjoy!
No comments