Button

We will add one button to our Application Window and connect it to event listener. Most common type of even listener is the Click event of a button.

We already have one blank window opened and we added Absolute Layout to this window.
Swing Layout

Adding button

Undder the components we have one JButton, click that and place it on our Application Window. To the left of our panel there is a section called Properties. We can manage properties options of our components using this panel.

For our window let us change the text written over it.

We will change the name of the variable to b1.
Swing button Properties

Adding Events

To our button we will add one event. This mean adding code which will be executed when we click the button.

Select the button on design panel and double click it. This code will be generated.
private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		JButton b1 = new JButton("Close window");
		b1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				// Our action code here. 
			}
		});
		b1.setBounds(171, 92, 89, 23);
		frame.getContentPane().add(b1);
	}
In above code we marked one area to write our code that will be executed once the button is clicked.

Close the window

We will add some code to close the window.
	b1.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent e) {
		 System.exit(0);
		}
	});
On click this will close our window.
Swing button close event
We created one window application and added one button to it. To the click event of this window we have added one line ( System.exit(0);) code to close the window.

Enable Disable a button

To Disable a button b1.
b1.setEnabled(false);
To Enable a button b1.
b1.setEnabled(true);


In next section we will learn how to read data from a text box and display the same when a button is clicked.

Button with Textfield and Lable

swing


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer