Java JFrame add controls to frame

Description

Java JFrame add controls to frame



import javax.swing.JFrame; 
import javax.swing.JButton; 
import java.awt.Container; 

public class Main { 
    public static void main(String[] args) { 
        JFrame frame = new JFrame("Adding Components to JFrame"); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        Container contentPane = frame.getContentPane(); 
        // Add a Close button 
        JButton closeButton = new JButton("Close"); 
        contentPane.add(closeButton); //  ww  w  .j av a 2  s .  c  o  m

        // Set the size of the frame 300 x 200 
        frame.setBounds(50, 50, 300, 200); 
        frame.setVisible(true); 
    } 
} 
// A simple Swing-based applet 
 
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.JPanel;

class Demo extends JPanel {

   public Demo() {
      // Create a text-based label.
      JLabel jlab = new JLabel("Press a button.");

      // Set the applet to use flow layout.
      setLayout(new FlowLayout());

      // Make two buttons.
      JButton jbtnAlpha = new JButton("Alpha");
      JButton jbtnBeta = new JButton("Beta");

      // Add action listener for Alpha.
      jbtnAlpha.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent le) {
            jlab.setText("Alpha was pressed.");
         }//  www  .  java  2  s  .c  om
      });

      // Add action listener for Beta.
      jbtnBeta.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent le) {
            jlab.setText("Beta was pressed.");
         }
      });

      // Add the buttons to the content pane.
      add(jbtnAlpha);
      add(jbtnBeta);

      // Add the label to the content pane.
      add(jlab);
   }

}

public class Main {
   public static void main(String[] args) {
      Demo panel = new Demo();

      JFrame application = new JFrame();

      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      application.add(panel);
      application.setSize(250, 250);
      application.setVisible(true);
   }
}



PreviousNext

Related