-1

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;

}

1
  • 3
    by creating an instance of its holder class new MainUI().build(); Commented Apr 16, 2014 at 21:28

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.