In our previous example, we set up the GUI Frame inside of the main function. However, we want to move it to a different class so that we can separate out the logic of application from the interface.
This will allow multiple people to work on different parts of the application easier, make it easier to have more complex projects, and allow us to extend the application classes as we might need to.
Creating a Class for our GUI
So let’s see how we can edit our existing application to put it into a new class.
So first we’re going to create a new class, and create two class level variables, one for the button, and one for the frame. We’re also going to import the packages that we’ll need.
import javax.swing.*;
import java.awt.event.*;
public class SimpleSwingGUI2 {
JFrame frame;
JButton button;
}
Next, inside the constructor, we’ll initialize the window and open it. We can copy most of the code from the previous example.
public SimpleSwingGUI2() {
// create a JFrame, with a default size
frame = new JFrame();
frame.setSize(250,500);
frame.setLayout(null);
frame.setTitle("Sample Swing Frame");
// create a button to add to the frame
button = new JButton("Press Me");
button.setBounds(15, 100, 200, 20);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button.setText("Button was pressed");
}
});
frame.add(button);
frame.setVisible(true);
}
You might notice that I even kept the variable names the same as the previous example.
Forcing Visibility with a Method
Now in some cases, we won’t set the frame to be visible here. We might do it in another method like you see below.
public void setVisible() {
this.setVisible(true);
}
public void setVisible(boolean visible) {
frame.setVisible(visible);
}
Notice how I have an overloaded method which will call the setVisible()
. With either method eventually, the frame variable will be called. I overloaded it just to make it a little easier to work with.
Calling the Class
To call this class, we created a new class with a main method. In it, we create the class object, and depending upon if you use the setVisible()
method or not, you may call it here.
public class SimpleSwingGUI2App {
public static void main(String args[]) {
SimpleSwingGUI2 ssgui = new SimpleSwingGUI2();
}
}
Notice that you don’t have to import any packages here, since you are not using them here, rather it is the previous class that needs them, and that is where they are imported.
Setting up the GUI in Another Class was originally found on Access 2 Learn
One Comment
Comments are closed.