2014-01-06 44 views
0

我對Java非常陌生,我試圖將簡單的時間計算器放在一起。未出現JFrame組件

爲什麼add()方法只拋出我添加的最後一件事?當我運行該程序時,它只顯示「天」而不是文本框和年份標籤。

import javax.swing.*; 

public class TimeCalculator extends JFrame 

{ 

    public static void main(String[] args) 
    { 
     JOptionPaneMultiInput window = new JOptionPaneMultiInput(); 
     window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     window.setSize(300,500); 
     window.setVisible(true); 
    } 

     public TimeCalculator() 
    { 
     super("Time Calculator"); 

     JTextField yearsField = new JTextField(5); 
     JTextField daysField = new JTextField(5); 
     JTextField hoursField = new JTextField(5); 
     JTextField minutesField = new JTextField(5); 
     JTextField secondsField = new JTextField(5); 

     JLabel yearsLabel = new JLabel(); 
     JLabel daysLabel = new JLabel(); 
     JLabel hoursLabel = new JLabel(); 
     JLabel minutesLabel = new JLabel(); 
     JLabel secondsLabel = new JLabel(); 

     JCheckBox yearsCheckbox = new JCheckBox(); 
     JCheckBox daysCheckbox = new JCheckBox(); 
     JCheckBox hoursCheckbox = new JCheckBox(); 
     JCheckBox minutesCheckbox = new JCheckBox(); 
     JCheckBox secondsCheckbox = new JCheckBox(); 

     JLabel yearsCLabel = new JLabel(); 
     JLabel daysCLabel = new JLabel(); 
     JLabel hoursCLabel = new JLabel(); 
     JLabel minutesCLabel = new JLabel(); 
     JLabel secondsCLabel = new JLabel(); 

     JButton convertButton = new JButton(); 

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     yearsLabel.setText("Years"); 
     daysLabel.setText("Days"); 
     hoursLabel.setText("Hours"); 
     minutesLabel.setText("Minutes"); 
     secondsLabel.setText("Seconds"); 

     yearsCLabel.setText("Yr"); 
     daysCLabel.setText("D"); 
     hoursCLabel.setText("Hr"); 
     minutesCLabel.setText("Min"); 
     secondsCLabel.setText("Sec"); 

     convertButton.setText("Convert"); 
     convertButton.addActionListener(new java.awt.event.ActionListener() 
      { 
       public void actionPerformed(java.awt.event.ActionEvent evt) 
       { 
        //doConvert(evt); this will be added later once i figure everything out 
       } 
      }); 


      add(yearsField); 
      add(yearsLabel); 
      add(daysField); 
      add(daysLabel); 
    } 
} 
+0

也許你應該考慮使用'LayoutManager',也許是'GridLayout'。 –

+0

我認爲它們是重疊的。 –

回答

3

JOptionPaneMultiInputmain()提及不是發佈源代碼的一部分。考慮發佈SSCCE

答案:

當我運行該程序只顯示代替文本框 和多年標籤「天」。

TimeCalculator在問題中出現延伸JFrame。默認JFrame使用BorderLayout佈局。當使用BorderLayout時,add()方法不帶約束參數導致BorderLayout.CENTER約束添加組件。所以你把你的物體添加到BorderLayout的中心。隨後的每個add()都會替換之前添加的組件。最後,只剩下daysLabel

請參閱How to Use BorderLayout瞭解更多詳情。對於其他佈局管理器,請參閱A Visual Guide to Layout Managers,因爲您的框架中有許多控件,如果沒有其他嵌套面板,很難將其展開。