0

ここで解決されたこの基本コードに関して以前にいくつか質問がありましたが、今私の問題は、このコードを取得して GUI textArea で結果を取得する必要があることです。これまでに行ったことは、textArea とボタンを設計したことですが、今は行き詰まっています。ベースとして使用したコードをGUIに変換し、ボタンをクリックして回答をテキストディスプレイに表示できるようにする方法がわかりません。この基本コードをどこかにコピーする必要があるのか​​ 、それともGUI内でまったく別のことをする必要があるのか​​ わかりませんか?たとえば、jButtonActionPerformed の下では、何をする必要がありますか? 私は一日中グーグルで検索しましたが、理解するのは難しいです。

ベースコードは次のとおりです。

import java.lang.String;
class Vara {              


    //Deklarerar variabler 

    private String name; 
    private double price; 
    private int antal;

    //tildela konstruktorer för de deklarerade variablerna 
    public Vara (String name, int antal, double price) { 
        this.name = name;
        this.antal = antal;
        this.price = price; 
    } // slut constructor

    public void setName(String name)  {  
        this.name = name; } 

    public void  setPrice (double price) { 
        this.price = price; } 

    public void setAntal (int antal)  {  
        this.antal = antal;  }

    public String getName() {    
        return this.name;} 

    public double getPrice() {   
        return this.price; } 

    public int getAntal() {    
        return this.antal; }     
}

//testklassen ska stå som en egen klass
   class Test {
       public static void main(String[] args){ 
        Vara var = new Vara("Banan",5, 12.5);


 System.out.println("Namnet är " +var.getName() +" och priset är " +var.getPrice() +" och antalet är "+var.getAntal() );// här slutar system.out


}
}

そして、これは GUI での私のコードの始まりです。これまでのところ、textArea とボタンを作成する以外は何もしていません。

public class NewJFrame extends javax.swing.JFrame {

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

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        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()
                .addContainerGap(29, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(69, 69, 69))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 361, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
      txtDisplay.setText(null);
       txtDisplay.append(String.valueOf(String)+"\n");  
       // 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration
}
4

2 に答える 2

0

あなたの質問から、データを自分に入れたいのか、JTextAreaそれとも別の場所に保存するために入力されたコンテンツを読みたいのかは明らかではありませJTextAreaん。どちらの場合もお答えします。

データと GUI を結び付ける洗練された方法は、データ モデル オブジェクト (この場合は class のインスタンスVara) を GUI オブジェクトに挿入することです。たとえば、以下のコードに示すように、GUI オブジェクトの作成時にこれを行うことができます。コードの新しい行ごとに「// CHANGED: ...」とコメントしました。

    public class NewJFrame extends javax.swing.JFrame {

      // CHANGED: store the model for this GUI
      private Vara vara;

      /**
      * Creates new form NewJFrame
      */
      public NewJFrame(Vara vara) { // CHANGED: provide the model for this GUI
        this.vara = vara; // CHANGED: store the model for this GUI
        initComponents();

        // CHANGED: set TextArea content according to the data in the
        // provided model object (if this is what you want)
        jTextArea1.setText(vara.getName());
    }

    ...
    ...
    ...

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        txtDisplay.setText(null);
        txtDisplay.append(String.valueOf(String)+"\n");  

        // CHANGED: read the entered text from the TextArea and store it as the
        // new name of the Vara object (if this is what you want to happen when
        // the user clicks on the button)
        vara.setName(jTextArea1.getText());
    }

    ...
    ...
    ...

      // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
      // End of variables declaration
}

より良いプログラマーライフのためのヒント:

  • コメントでもどこでも英語を使用

  • 常に適切な GUI 要素に名前を付けます。たとえば、your jButton1could be btnSave(「btn」は Button を表します) や your jTextArea1could be taVaraName(「ta」は TextArea を表します) - これにより、GUI コードの可読性が大幅に向上し、デバッグと保守がはるかに容易になります。

  • Java開発、特にEclipseにはEclipseを使用してください。GUIを構築したい場合。Eclipse WindowBuilderというプラグインが付属しています。これは「強力で使いやすい双方向 Java GUI デザイナー」であり、次のことができることを意味します。(1) GUI 要素を簡単にドラッグ アンド ドロップして、コードを自動的に生成します。(2) コードの任意の部分を変更すると、それに応じてドラッグ アンド ドロップ ビューが自動的に変更されます。投稿したものよりもはるかにクリーンで多くの場合短いGUIコードを生成し、すべてを変更できます(コードに「変更しない」部分はありません)

于 2014-03-22T05:22:14.953 に答える