Advertisement
keiaa070500

swing demo

Dec 7th, 2024 (edited)
6
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | Source Code | 0 0
  1. import javax.swing.JFrame;
  2. import javax.swing.JLabel;
  3. import javax.swing.JTextField;
  4. import javax.swing.JButton;
  5. import java.awt.FlowLayout;
  6. import java.awt.event.ActionEvent;
  7. import java.awt.event.ActionListener;
  8. import javax.swing.SwingUtilities;
  9.  
  10. public class Swing_Basics_Demo {
  11.     private JFrame frame;
  12.     private JLabel label;
  13.     private JTextField textField;
  14.     private JButton button;
  15.    
  16.     public Swing_Basics_Demo() {
  17.         createGUI();
  18.     }
  19.    
  20.     private void createGUI() {
  21.         frame = new JFrame("Swing GUI Demo");
  22.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  23.         frame.setLayout(new FlowLayout()); // Arrange components in a row
  24.        
  25.         label = new JLabel("Hello! Please type your name here.");
  26.         frame.getContentPane().add(label);
  27.        
  28.         textField = new JTextField(20); // Set width
  29.         frame.getContentPane().add(textField);
  30.        
  31.         button = new JButton("Submit");
  32.         button.addActionListener(new ActionListener() {
  33.             @Override
  34.             public void actionPerformed(ActionEvent e) {
  35.                 String name = textField.getText(); // Store the user input in a String
  36.                 label.setText("Hello, " + name + "!"); // Update previous label
  37.                 textField.setText(""); // Clear the text field after submission
  38.             }
  39.         });
  40.         frame.getContentPane().add(button);
  41.        
  42.         frame.pack(); // Automatically set the size of the frame to fit its contents
  43.         frame.setVisible(true);
  44.     }
  45.    
  46.     public static void main(String[] args) {
  47.         SwingUtilities.invokeLater(new Runnable() { // Execute the Swing on the Event Dispatching Thread
  48.             @Override
  49.             public void run() {
  50.                 new Swing_Basics_Demo();
  51.             }
  52.         });
  53.     }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement