Creating a JButton component in swing

By | April 28, 2012

Java swing provides a native look and feel that emulates the look and feel of several platforms.
Here i am going to create a Button and adding it to Frame.

For this first create a Jframe object,a JPanel object and a Container object

JFrame f = new JFrame();
JPanel panel1 = new JPanel();
Container con = f.getContentPane();

Then Create a button object and add this ti JPanel object

JButton panel1_but = new JButton();
panel1.add(panel1_but);

and finally add JPanel to JFrame

panel1.add(panel1_but);

This full code is given below

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class mainframe implements WindowListener
{
	JFrame f = new JFrame();
	Container con = f.getContentPane();
	JPanel panel1 = new JPanel();
	mainframe()
	{
		createpanel1();
		f.addWindowListener(this);
		f.setSize(900, 600);
		f.setVisible(true);
		f.setLocationRelativeTo(null);
		f.setResizable(false);    ///cannot maximize
	   	f.setVisible(true);
	}
	public static void main(String args[])
	{
		new mainframe();
	}
	private void createpanel1()
	{
		JButton panel1_but = new JButton();
		panel1_but.setBounds(new Rectangle(450,400,200,40));
		panel1_but.setText("Continue");

		panel1.add(panel1_but);
		panel1_but.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				//action to be performed....
			}
			}
		);
		panel1.setLayout(new BorderLayout());
		panel1.setBackground(Color.white);
		panel1.setVisible(true);
		con.add(panel1);
	}

	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowClosing(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
}
Website Pin Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google StumbleUpon Premium Responsive

Leave a Reply

Your email address will not be published. Required fields are marked *