我正在嘗試使用網格佈局來製作GUI窗口。我添加了所有的組件並編譯,但運行時它不顯示任何內容。我試圖做一個簡單的佈局分組和堆疊像這樣。我的GUI窗口不顯示任何內容
{introduction message}
{time label
time input text}
{gravity label
gravity input text}
{answer label
answer text box}
{calculate button clear button}
這裏是我的代碼
import javax.swing.*;
import java.awt.*;
public class TurnerRandyFallingGUI extends JFrame
{
final int WINDOW_HEIGHT=500;
final int WINDOW_WIDTH=500;
public TurnerRandyFallingGUI()
{
setTitle("Falling Distance Calculator");
setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(1, 5));
//labels
JLabel introMessage = new JLabel("Welcome to the Falling distance"+
"calculator");
JLabel timeLabel = new JLabel("Please enter the amount of time "+
"in seconds the object was falling.");
JLabel gravityLabel = new JLabel("Enter the amount of gravity being "+
"forced onto the object");
JLabel answerLabel = new JLabel("Answer");
//text fields
JTextField fTime = new JTextField(10);
JTextField gForce = new JTextField(10);
JTextField answerT = new JTextField(10);
//buttons
JButton calculate = new JButton("Calculate");
JButton clr = new JButton("clear");
//panels
JPanel introP = new JPanel();
JPanel timeP = new JPanel();
JPanel gravityP = new JPanel();
JPanel answerP = new JPanel();
JPanel buttonsP = new JPanel();
//adding to the panels
//intro panel
introP.add(introMessage);
//time panel
timeP.add(timeLabel);
timeP.add(fTime);
//gravity panel
gravityP.add(gravityLabel);
gravityP.add(gForce);
//answer panel
answerP.add(answerLabel);
answerP.add(answerT);
//button panel
buttonsP.add(calculate);
buttonsP.add(clr);
setVisible(true);
}
public static void main(String[] args)
{
new TurnerRandyFallingGUI();
}
}
這將不起作用,因爲它不考慮JFrame的默認BorderLayout。 –
我認爲所有的面板都會根據GridLayout添加到JFrame中,一行五列 – olyanren
當你看上面的代碼時,你可以看到使用setLayout(new GridLayout(1,5))語句。如果您不指定佈局,JFrame的默認佈局是BorderLayout – olyanren