Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Java:Tutorial - Adding Buttons to your Interface


  • Please log in to reply
No replies to this topic

#1 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 11 January 2007 - 12:03 PM

This is the second of six tutorials that will show you how to create graphical user interfaces using java.

Prerequisites
You should have JDK installed and an editing environment you are comfortable with.
http://forum.codecall.net/java-tutorials/1703-java-tutorial-getting-started.html

You should also have read my previous tutorials:
INDEX

The Idea
In order for your program to be attractive, the user must be able to easily navigate through your program. By creating a GUI the user is presented with all the features of the program in a clear and coherent manner. Adding buttons to your interface allow for user interaction which is the reason for a GUI.

Solution
Since you already know how to create a window we are going to start off where we left off last time with the window code.
package cctuts;

import javax.swing.*;

public class InterfaceTwo extends JFrame{
	
	public InterfaceTwo(){
	   setSize(400,400);
	   setDefaultCloseOperation(EXIT_ON_CLOSE);
	   setVisible(true);
	}
	
	public static void main(String[] args){ 
		new InterfaceTwo();
	}
}

To add a button we add an “object” to the window. To do that we must define the object type, object name and instantiate the object (discussed in previous tutorials). In this case our button type is JButton, you can name the object what ever you want. I’ve decided to call it startButton. The JButton accepts a string paramenter and when you create the object in java the syntax of the line would look like this:
JButton startButton = new JButton("Start");
Which is a simple button that says “Start.” Althought we created the object, we need to add the object to the window, and the JFrame class allows us to use the add() method to do just that. add() accepts an object parameter and would look like this:
add(startButton);
The final code looks like this:
package cctuts;

import javax.swing.*;

public class InterfaceTwo extends JFrame{
	
	public InterfaceTwo(){
	   setSize(400,400);
	   JButton startButton = new JButton("Start");
	   add(startButton);
	   setDefaultCloseOperation(EXIT_ON_CLOSE);
	   setVisible(true);
	}
	
	public static void main(String[] args){ 
		new InterfaceTwo();
	}
}

Visually this is that it looks like:
Posted Image

Originally posted as Adding Buttons to your Interface

Edited by John, 01 August 2010 - 09:30 AM.

  • 0




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download