Java从另一个类的主类调用方法

时间:2014-09-07 20:42:04

标签: java swing methods main invoke

同一个包中的两个类

具有公共静态和实例变量组合的主类。 它创建了一个名为instance的类的实例。

另一个类Login,而不是子类,它的业务,但我想从main调用guiInstance的方法。

问题是我似乎无法让它工作,我不能让Login类找到“gui”实例或类的任何方法,尽管它们是公开的。

我刚用我想要的配置创建了一个新包,显然我对调用方法的工作方式有错误的想法。

public class GUI {

    JPanel jp = new JPanel();

    public static void main(String[] args) {
        GUI instance = new GUI();
    }

    public void ping(){
        System.out.println("that worked");
    }
}


public class Login extends JPanel {

    /** Creates new form Login */
    public Login() {
        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() {

        jButton1 = new javax.swing.JButton();

        jButton1.setText("jButton1");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(112, 112, 112)
                .addComponent(jButton1)
                .addContainerGap(215, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addComponent(jButton1)
                .addContainerGap(231, Short.MAX_VALUE))
        );
    }// </editor-fold>

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
        instance.ping();
    }


    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    // End of variables declaration

}

1 个答案:

答案 0 :(得分:1)

您的GUI方法中有main()个实例,但您似乎无法创建Login的实例。我建议您将GUI实例传递给Login构造函数,因此在Login中添加类似的内容 -

private GUI gui = null;
public Login(GUI gui) {
  this.gui = gui;
  initComponents();
}

然后在main()你可以做类似的事情,

public static void main(String[] args) {
  GUI instance = new GUI();
  Login login = new Login(instance);
  // next I believe you need to make your Frame and components visible
}