调用构造函数,调用组件的私有初始化

时间:2014-08-18 22:20:55

标签: java swing

我刚刚发现netbeans有内置的swing工具,所以我正在玩它但遇到了一些麻烦。我如何从main方法调用初始化。因为没有main方法程序不会执行,但是有了它我不能只调用构造函数,或者不能只调用initComponents()因为它是私有的。我怎么能这样工作?

public static void main(String [] args){


}
/**
 * Creates new form password
 */
public password() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
...

1 个答案:

答案 0 :(得分:0)

正如@MadProgrammer已经提到的,你只需要创建一个类的实例,调用它的构造函数,如下所示:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;

@SuppressWarnings("serial")
public class Class extends JFrame
{
    private JButton btn;
    private JTextArea txtArea;

    public static void main(String[] a)
    {
        EventQueue.invokeLater(new Runnable() {
            public void run()
            {
                new Class();// Creating an instance of Class
            }
        });
    }

    public Class()
    {
        super("Title");

        initialize();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        pack();
        setLocationRelativeTo(null);
    }

    private void initialize()
    {
        btn = new JButton("Click me");
        txtArea = new JTextArea();

        add(btn, BorderLayout.NORTH);
        add(txtArea, BorderLayout.CENTER);
    }
}