2012-10-09 3 views
2

이것은 예상했던대로 거의 작동하는 코드입니다. 내가 문제에 들어가기 전에 코드를 보아라. 긴 코드는 나를 용서하되 자바 클래스처럼 붙일 수있다. NETBEANS JForm 디자이너를 사용하여 GUI를 얻는다. 왜 레이아웃이 작아지는 지 알지 못합니다

package test; 
import java.awt.event.*; 
import javax.swing.*; 
/** 
* 
* @author jackandjill 
*/ 
public class Summingup extends JFrame { 

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

    // <editor-fold defaultstate="collapsed" desc="Generated Code">       
    private void initComponents() { 

     jPanel1 = new javax.swing.JPanel(); 
     jLabel1 = new javax.swing.JLabel(); 
     jLabel2 = new javax.swing.JLabel(); 
     input1_tb = new javax.swing.JTextField(); 
     calculate_btn = new javax.swing.JButton(); 
     result_lbl = new javax.swing.JLabel(); 
     input2_tb = new javax.swing.JTextField(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     jLabel1.setText("Input 1"); 

     jLabel2.setText("Input 2"); 

     calculate_btn.setText("SUM"); 
     calculate_btn.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       calculate_btnActionPerformed(evt); 
      } 
     }); 

     result_lbl.setText("RESULT DISPLAYED HERE!"); 

     javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); 
     jPanel1.setLayout(jPanel1Layout); 
     jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(jPanel1Layout.createSequentialGroup() 
       .addContainerGap() 
       .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) 
        .addGroup(jPanel1Layout.createSequentialGroup() 
         .addComponent(jLabel1) 
         .addGap(18, 18, 18) 
         .addComponent(input1_tb)) 
        .addGroup(jPanel1Layout.createSequentialGroup() 
         .addComponent(jLabel2) 
         .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
          .addGroup(jPanel1Layout.createSequentialGroup() 
           .addGap(18, 18, 18) 
           .addComponent(result_lbl)) 
          .addGroup(jPanel1Layout.createSequentialGroup() 
           .addGap(18, 18, 18) 
           .addComponent(input2_tb))))) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
       .addComponent(calculate_btn) 
       .addContainerGap()) 
     ); 
     jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(jPanel1Layout.createSequentialGroup() 
       .addContainerGap() 
       .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) 
        .addGroup(jPanel1Layout.createSequentialGroup() 
         .addGap(1, 1, 1) 
         .addComponent(calculate_btn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
        .addGroup(jPanel1Layout.createSequentialGroup() 
         .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
          .addComponent(jLabel1) 
          .addComponent(input1_tb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
         .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
         .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
          .addComponent(jLabel2) 
          .addComponent(input2_tb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) 
       .addComponent(result_lbl) 
       .addContainerGap()) 
     ); 

     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() 
       .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addContainerGap() 
       .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
     ); 

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

    private void calculate_btnActionPerformed(java.awt.event.ActionEvent evt) {            
     // TODO add your handling code here: 
     InvalidValueException ive = new InvalidValueException(); 
     calculate_btn.addActionListener(ive); 
     //addActionListener 
    }            

    /** 
    * @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(Summingup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(Summingup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(Summingup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(Summingup.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 Summingup().setVisible(true); 
      } 
     }); 
    } 

    // Variables declaration - do not modify      
    public javax.swing.JButton calculate_btn; 
    public javax.swing.JTextField input1_tb; 
    public javax.swing.JTextField input2_tb; 
    private javax.swing.JLabel jLabel1; 
    private javax.swing.JLabel jLabel2; 
    public javax.swing.JPanel jPanel1; 
    public javax.swing.JLabel result_lbl; 
    // End of variables declaration     




class InvalidValueException implements ActionListener 
{ 

    public void actionPerformed(ActionEvent ae) 
    { 
     try 
     { 
      if(ae.getSource() == calculate_btn) 
      { 
       String input_1 = input1_tb.getText(); 
       String input_2 = input2_tb.getText(); 

       checkBlankInput(input_1,input_2); 

       validateInput(Integer.parseInt(input_1),Integer.parseInt(input_2)); 

       result_lbl.setText(calculate(Integer.parseInt(input_1),Integer.parseInt(input_2))); 

      } 
     } 

     catch (NumberFormatException excep) 
     { 
     result_lbl.setText("Invalid number"); 
     } 

     catch (BlankInputException excep) 
     { 
     result_lbl.setText(excep.getMessage()); 
     } 
     catch (InvalidInputException excep) 
     { 
     result_lbl.setText(excep.getMessage()); 
     } 
    } 



    public void checkBlankInput(String input1,String input2) throws BlankInputException 
    { 
     if (input1.length() == 0 ||input2.length() == 0) throw new BlankInputException(); 
    } 

    public void validateInput(int input1 , int input2) throws InvalidInputException 
    { 

     if (input1 + input2 > 100) 
     throw new InvalidInputException(); 
    } 

    public String calculate(int input1, int input2) 
    { 
     String res = ""; 
     while (true) 
     { 
      res = Integer.toString(input1 + input2); 
      break; 
     } 
     return res; 

    } 

} 
} 

class InvalidInputException extends Exception { 

public InvalidInputException() { 

super("Invalid number"); 

} 
} 
class BlankInputException extends Exception { 

public BlankInputException() { 

super("Input cannot be blank"); 

} 
} 

그래서이 코드는 기본적으로 GUI를 초기화하고 예외 처리를 많이하고있다, 내가 코드에 대한 간단한하자, 당신이 정확하게 답변을 더 명확하게 이해할 수 있도록 전체 코드를 참조하는 것이 참으로 중요합니다. 나는 내가 SUM 버튼 ONE 아직 시간이

변경없이 상기와 같은 이미지를 누르면 그래서 후 프로그램을

enter image description here

을 실행할 때 이 내가 얻을 레이아웃입니다

I를 누르면 SUM 버튼을 다시 누릅니다.

enter image description here

그래서 희망 두 번째로 당신은 보았다! 텍스트 필드의 길이가 점점 짧아지고 있습니다. 어디서부터 시작해야할지 모르겠다. 만약 내가 디버깅을 해달라고 부탁하면, 이미 했었지만 아직도 어떤 크기 축소도하지 않았다.

+0

"작게"작게 말할 때 "SUM"을 클릭 할 때마다 대화 상자가 축소됩니까? –

+0

@AaronDigulla 아니요. – noobprogrammer

답변

4

단추를 클릭 할 때 result_lbl 레이블의 텍스트가 짧아 지므로 텍스트 필드의 길이가 더 짧아집니다. 텍스트 필드의 길이는 항상 아래 레이블의 길이와 같습니다.

예를 들어 다음과 같이 지정된 수의 열이있는 텍스트 필드를 구성하면 문제를 해결할 수 있습니다.

input1_tb = new JTextField(20); 

아래 레이블에 어떤 일이 발생하는지에 관계없이 텍스트 필드의 길이에는 영향을 미치지 않아야합니다.

편집 :

why doesn't the button listener is not kicking in the first time? 

제거를이

calculate_btn.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      calculate_btnActionPerformed(evt); 
     } 
    }); 

private void calculate_btnActionPerformed(java.awt.event.ActionEvent evt) {            
    // TODO add your handling code here: 
    InvalidValueException ive = new InvalidValueException(); 
    calculate_btn.addActionListener(ive); 
    //addActionListener 
}    

이 라인으로 대체 :

calculate_btn.addActionListener(new InvalidValueException()); 

단추를 만든 후

+0

라벨이 범인이기 때문에 잘 보입니다. 그건 그렇고, 왜 버튼 리스너가 처음으로 발 차기는하지 않습니까? – noobprogrammer

+0

OMG !! 이것은 완벽한 해결책입니다 .. 그리고 NETBEANS에서 편집 할 수없는 코드를 편집하는 방법에 대해 궁금한 분들은 마우스 오른쪽 버튼을 클릭하고 컨텍스트 메뉴에서 customizecode를 클릭하고 Rempelos가 말한 것을 추가하십시오. – noobprogrammer

2

텍스트 필드는 결과 레이블이있는 동일한 세로 열에 추가됩니다. 결과 레이블의 크기가 변경되면 텍스트 필드에도 영향을줍니다.

코드에서 또 다른 이상한 점은 이미 등록한 ActionListener을 처리 할 때 InvalidValueExceptionActionListener으로 추가한다는 것입니다. 이 작업은 버튼을 누를 때마다 수행하면 안됩니다.

+0

예 Dan, 동의합니다 하지만 neatbeans가 코드에 수정을 할 수있는 옵션을 제공하지 않습니다. 이유는 무엇입니까? – noobprogrammer

+0

UI 디자이너가 직접 작성하지 말고 코드를 직접 작성하는 것이 좋습니다. –

관련 문제