web-dev-qa-db-ja.com

別のJavaクラスからJFrameを呼び出す方法

単純な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();
}
}
3
Jonathan Lopez

これがナイーブな場合は許してください。ImはJavaプログラマー....しかし、表示を設定する必要があるという理由だけではありませんか?

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

Calculasのコンストラクターは、フレームを表示しません(setVisible)。

この方法でCalculasクラスを操作する場合は、CAL.setVisible(true)も呼び出す必要があります。

また、慣例により、すべてのJavaインスタンス変数は小文字で始まり、キャメルケースの規則を使用する必要があります

3
MadProgrammer

現在のコード形式では、CalculasクラスのTestクラスのmainメソッドを呼び出すか、コードをTestクラスに移動できます。

警告:JFrameを拡張することは良い考えではありません。

最初の選択肢:テストでJFrameを拡張する必要はありません

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

コンソールまたは別のJFrameなどで、閉じるか開くかをどのように選択できるようにするかについて、質問で言及していません。

2番目の選択肢:

しかし、私があなたなら、次のようなことができます。ルックアンドフィールのコードを別のメソッドでラップし、これをTestのメインから呼び出します。

/*
 * 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);
          }
       });
      }
     }

このような:

3
pinkpanther

使用できる基本構造の例を次に示します。

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();
            }
        });
    }
}
1
7stud
_ Calculas CAL = new Calculas();
  CAL.Calculus();
_

たぶん、CAL.Calculas();わからないJavaでも、英語については申し訳ありません:)

0
Ebru