Question

I am using swing to make a java project with JFrames. I am trying to call the non-static method build(), which builds the JFrame with its components. However, build can't be static because I am using getClass(), which requires a non-static method. I can't make my main non-static, so how can I call build? Here is my code:

public class MainUI {
public static void main(String[] args) {
    build(); // Calls build method
}
private void build() {
    // Builds JFrame
    JFrame frame = new JFrame();
    JPanel base = new JPanel();
    JLabel background = new JLabel();
    frame.setVisible(true);
    frame.setTitle("Space Age");
    frame.setSize(640,480);
    frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    frame.setAutoRequestFocus(false);
    frame.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    frame.setLocationRelativeTo(null);
    base.setSize(640,480);
    base.setAlignmentX(0.0F);
    base.setAlignmentY(0.0F);
    base.setBackground(new java.awt.Color(255,255,255));
    background.setSize(640,480);
    background.setAlignmentX(0.0F);
    background.setAlignmentY(0.0F);
    background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/path/image.png")));
    frame.add(base);
    frame.add(background);
}
// Variable declarations
private JFrame frame;
private JPanel base;
private JLabel background;

}

Was it helpful?

Solution

Just create an instance of the class:

MainUI mainUI = new MainUI();
mainUI.build();

You can't call a non-static method without an instance of the class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top