- 1). Open a new file with your preferred text editor, such as Notepad, or with your preferred Java integrated development environment (IDE).
- 2). Type "import javax.swing.*;" at the top of the file. This will import the basic Swing code that you need to create a graphical program for the "X" graphics system or for Windows.
- 3). Type:
"public class MyGuiProgram extends JFrame{
}"
to create the skeleton of your primary Java class, where "MyGuiProgram" is the name of your specific graphical Java program. - 4). Type "JPanel MyWindow = new JPanel();" in the first line of your class skeleton, where "MyWindow" is the name you will be using for your window component. Your code should now resemble:
"import javax.swing.*;
public class MyGuiProgram extends JFrame{
JPanel MyWindow = new JPanel();
}" - 5). Type:
"public MyGUIProgram(){
}" to create the skeleton of your class constructor below the line in which you declared a new JPanel. Your code should now resemble:"
import javax.swing.*;
public class MyGuiProgram extends JFrame{
JPanel MyWindow = new JPanel();
public MyGuiProgram(){
}
}" - 6). Type "setSize(x,y);" where X and Y are the desired dimensions of your Java program window in pixels in the first line of your class constructor. Below that, type "setContentPane(MyWindow);" so that your constructor resembles:
"public MyGuiProgram(){
setSize(100,100);
setContentPane(MyWindow);
}" - 7). Type:
"public static void main(){
MyGuiProgram Window = new MyGuiProgram();
Window.setVisible(true);
}"
where "Window" is the name you choose to refer to the window as in your main method, below your constructor. Your source code should now resemble:
"import javax.swing.*;
public class MyGuiProgram extends JFrame{
JPanel MyWindow = new JPanel();
public MyGuiProgram(){
setSize(100,100);
setContentPane(MyWindow);
}
public static void main(){
MyGuiProgram Window = new MyGuiProgram();
Window.setVisible(true);
}
}" - 8). Save your source file. Open a command line from your system's main menu, then type "cd" followed by the name of the directory in which you saved your source code.
- 9). Compile your Java source code with the command "javac MyGuiProgram.java," then type the command "java MyGuiProgram" to see your new Window.
- 10
Return to your source code file, and add the code to include your desired functionality into the program.