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.
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: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(); } }
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:Code:JButton startButton = new JButton("Start");
The final code looks like this:Code:add(startButton);
Visually this is that it looks like:Code: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(); } }
Originally posted as Adding Buttons to your Interface
Last edited by John; 08-01-2010 at 10:30 AM.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks