-1
我正在使用swing来制作带有JFrame的Java项目。我正试图调用非静态方法build(),它使用它的组件构建JFrame。但是,构建不能是静态的,因为我使用getClass(),它需要一个非静态方法。我不能让我的主要非静态,所以我怎么能称之为构建?这里是我的代码:如何从静态方法调用非静态方法?
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;
}
通过创建其持有者类的新实例'new MainUI()。build();' –
谢谢!有效。 –