【问题标题】:How To Call JFrame from another Java class如何从另一个 Java 类调用 JFrame
【发布时间】:2013-06-10 07:31:17
【问题描述】:

我正在尝试做一个简单的 Jform 并从另一个类中调用它。 我想在服务器客户端应用程序中使用这个 Jframe,但我不知道如何从另一个类打开 JFrame 类。

就像用户必须选择的那样

1- 打开 Jframe。

2- 退出。

那么我做错了什么?

以下是代码:

名为 Calculas.java 的 Jframe 类

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author user
 */
public class Calculas extends javax.swing.JFrame {

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

        a1Text = new javax.swing.JTextField();
        a2Text = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        answer = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(87, 87, 87)
                        .addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(113, 113, 113)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton1)))
                .addContainerGap(86, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(60, 60, 60)
                .addComponent(jLabel1)
                .addGap(34, 34, 34)
                .addComponent(jButton1)
                .addContainerGap(140, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
int a;
a = Integer.parseInt(a1Text.getText()) + Integer.parseInt(a2Text.getText());
answer.setText("Answer" + a);

        // TODO add your handling code here:
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Calculas().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JTextField a1Text;
    private javax.swing.JTextField a2Text;
    private javax.swing.JLabel answer;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

名为 Test.java 的测试类

public class Test extends JFrame {
    public static void main(String args[])
    {
    Calculas CAL = new Calculas();
    CAL.Calculus();
}
}

【问题讨论】:

  • 只运行calculas 类。它已经有一个 main 方法。
  • @ZouZou 如果 OP 想要在另一个类中包含 Calculas 类并且需要对 Calculas 类的引用来处理其他事情,比如设置/获取属性,该怎么办?直接调用 Calculas.main 不会实现这一点 - 只是说
  • @MadProgrammer 好的,明白了 =)。 @JonathanLopez 您可以复制/粘贴 Calculas CAL = new Calculas(); 行下方的 main 方法,并将 Calculas 类的 new Calculas().setVisible(true); 行更改为 CAL.setVisible(true);(以便能够拥有 Nimbus 外观)。
  • 来问去......永远不会回来......

标签: java swing user-interface jframe


【解决方案1】:

如果这是幼稚的,请原谅我,因为我不是 Java 程序员...... 但是不就是因为需要设置可见吗?

Calculas CAL = new Calculas();
CAL.setVisible(true);

【讨论】:

    【解决方案2】:

    Calculas 的构造函数不显示 (setVisible) 框架。

    如果您想以这种方式与Calculas 类交互,您还应该调用CAL.setVisible(true)

    此外,按照约定,所有 Java 实例变量都应以小写字符开头并使用驼峰式约定

    【讨论】:

    • 其实它在Calculas类中已经有一个main来显示框架了。
    • 但是 OP 没有调用 Calculas.main,而是直接构建类。一般来说,您应该尝试通过 main 方法构造类,除非您尝试测试整个应用程序,这在问题中未指定;)
    • 我完全同意你的观点,但我认为 OP 是初学者,因为他只是复制/粘贴代码并尝试使用包含 main 的新类来启动它。
    【解决方案3】:

    在您当前的代码形式中,您可以在Test 类中调用Calculas 类的主要方法,或将代码移至Test 类。

    警告:扩展 JFrame 不是一个好主意。

    第一种选择:您不需要在测试中扩展 JFrame

      public class Test{
        public static void main(String args[])
        {
            Calculas.main(new String[0]);
        }
       }
    

    你没有在你的问题中提到你希望如何在控制台或另一个JFrame 或其他东西中选择关闭或打开......

    第二种选择:

    但如果我是你,我可以这样做:将外观代码包装在一个单独的方法中,然后从 Test 的 main 调用它。

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /**
     *
     * @author user
     */
    public class Calculas extends javax.swing.JFrame {
    
        /**
         * Creates new form Calculas
         */
        public Calculas() {
            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() {
    
            a1Text = new javax.swing.JTextField();
            a2Text = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            answer = new javax.swing.JLabel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(87, 87, 87)
                            .addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(113, 113, 113)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jButton1)))
                    .addContainerGap(86, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(19, 19, 19)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(a1Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(a2Text, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(answer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(60, 60, 60)
                    .addComponent(jLabel1)
                    .addGap(34, 34, 34)
                    .addComponent(jButton1)
                    .addContainerGap(140, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>                        
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    int a;
    a = Integer.parseInt(a1Text.getText()) + Integer.parseInt(a2Text.getText());
    answer.setText("Answer" + a);
    
            // TODO add your handling code here:
        }                                        
        public static setNimbusFeel(){
              /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Calculas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
    
        }
        // Variables declaration - do not modify                     
        private javax.swing.JTextField a1Text;
        private javax.swing.JTextField a2Text;
        private javax.swing.JLabel answer;
        private javax.swing.JButton jButton1;
        private javax.swing.JLabel jLabel1;
        // End of variables declaration                   
    }
    

    然后像这样测试类:

      public class Test{
        public static void main(String args[])
        {
            Calculas cal=new Calculas();
            //</editor-fold>
            Calculas.setNimbusFeel();
           /* Create and display the form */
           java.awt.EventQueue.invokeLater(new Runnable() {
              public void run() {
                new Calculas().setVisible(true);
              }
           });
          }
         }
    

    像这样:

    【讨论】:

      【解决方案4】:

      这是您可以使用的基本结构的示例:

      import java.awt.*;
      import javax.swing.*;
      
      
      
      class MyGui {
      
          private JFrame window = new JFrame("This is the title");
      
          public MyGui() {
              initComponents();
      
              window.setBounds(100, 50, 600, 400); //location, size
              window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              window.setVisible(true);
          }
      
          public void initComponents() {
              Container cp = window.getContentPane();
              cp.setLayout(new FlowLayout() );
              cp.add(new JLabel("Hello world") );
          }
      }
      
      
      public class MyProg {
          private static void createAndShowGUI() {
              new MyGui();
          }
      
         public static void main(String[] args) {
              //Schedule a job for the event dispatch thread:
              //creating and showing this application's GUI.
              SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                      createAndShowGUI();
                  }
              });
          }
      }
      

      在单独的文件中:

      MyGui.java

      import java.awt.*;
      import javax.swing.*;
      
      public class MyGui {
      
          private JFrame window = new JFrame("This is the title");
      
          public MyGui() {
              initComponents();
      
              window.setBounds(100, 50, 600, 400); //location, size
              window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              window.setVisible(true);
          }
      
          public void initComponents() {
              Container cp = window.getContentPane();
              cp.setLayout(new FlowLayout() );
              cp.add(new JLabel("Hello world") );
          }
      }
      

      MyProg.java

      import javax.swing.*;
      
      public class MyProg {
      
          private static void createAndShowGUI() {
              new MyGui();
          }
      
         public static void main(String[] args) {
              //Schedule a job for the event dispatch thread:
              //creating and showing this application's GUI.
              SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                      createAndShowGUI();
                  }
              });
          }
      }
      

      【讨论】:

        【解决方案5】:
         Calculas CAL = new Calculas();
          CAL.Calculus();
        

        也许,CAL.Calculas();我不懂java,但我意识到,对不起我的英语:)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多