2013-07-05 2 views
0

이 기본 코드와 관련된 질문이 있었지만 지금은이 코드를 사용하여 GUI textArea에서 결과를 가져와야합니다. 지금까지 한 일은 ive 이 textArea와 버튼을 디자인했지만 지금은 붙어 있습니다. 나는 그 방법을 모르겠다. 그 코드를 내가 GUI로 기본으로 사용하고 가능한 한 만들었다. 버튼을 클릭하고 텍스트 디스플레이에 답변을 표시한다. 내가 어딘가에이 기본 코드를 복사해야합니까 아니면 내가 할 필요가 있겠 어 완전히 다른 건 GUI의 내부? 예를 들어, jButtonActionPerformed에서 무엇을해야합니까 ... 미안 해요 에 이르기까지 미신입니다. 필자는 하루 종일 인터넷 검색을하고 있지만 이해하기가 어렵습니다. 여기 기본 코드에서 textArea GUI에 답변을 쓰는 ​​방법

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 


} 
} 

그리고

내가 텍스트 영역과 버튼을 생성 제외하고 지금까지 아무 것도 할 havent 한 GUI에 내 코드의 시작입니다 : 여기

는 기본 코드입니다.

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 
} 

답변

0

GUI 클래스의 경우 수정자를 "Public Static"으로 설정하여 다른 클래스에서 액세스 할 수 있도록합니다.

public static javax.swing.JTextArea jTextArea1; 

다른 클래스에서이 jTextArea1 값을 입력 할 수 있습니다. 당신이 다른 곳에 보관하기 위해 JTextArea에 입력 된 내용을 당신의 JTextArea에 데이터에 넣어하거나 읽으려면 질문에서이

NewJFrame.jTextArea1.append("text to append"); 
0

처럼 직접 액세스하여이 명확하지 않다. 두 가지 경우에 대해 답변 해 드리겠습니다.

데이터와 GUI를 묶는 우아한 방법은 데이터 모델 객체 (경우에 따라 클래스 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 요소의 이름 이 크게 GUI 코드의 가독성을 높이고 디버깅 및 훨씬 쉽게

  • 사용 Eclipse를 유지한다 - 당신의 jButton1btnSave 될 수있다 ("BTN"는 버튼의 약자)와 jTextArea1taVaraName 될 수있다 ("타"텍스트 영역을 의미) 자바 개발, 특히 GUI를 만들려는 경우. 그것은 Eclipse WindowBuilder이라는 플러그인과 함께 제공됩니다. 이것은 강력하고 사용하기 쉬운 양방향 Java GUI 디자이너입니다. 즉, (1) GUI 요소를 쉽게 드래그 앤 드롭하여 자동으로 코드를 생성 할 수 있습니다. (2) 코드의 일부를 수정하고 그에 따라 자동으로 변경되는 드래그 앤 드롭보기를보십시오.그것은 당신이 게시 한 것보다 훨씬 더 깔끔하고 종종 GUI 코드를 생성하고 모든 것을 수정할 수있게 해줍니다. (코드에 "do not modify"부분이 없습니다)

관련 문제