簡體   English   中英

將Label和TextField放在同一行中

[英]Put a Label and a TextField in a same row

我想在Java Swing中創建一個計算器,但遇到一個問題,我想將一個標簽和一個文本字段放在同一行中,而不是兩列,但放在同一行中,例如:數字1 :(標簽)(此處的文本字段)在同一行中行,對不起我的英語。

我的代碼:

private JPanel mainPan; //= new JPanel();
private JLabel title;
private JLabel nb1;
private JLabel nb2;
private JButton button;
private JTextField textField; //= new JTextField();

public Fenetre() {
    super ("Calculator");
    mainPan = new JPanel();
    title = new JLabel();
    nb1 = new JLabel();
    nb2 = new JLabel();
    button= new JButton();
    textField = new JTextField();

    setMinimumSize(new Dimension(400, 500));
    setSize(400, 500);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(Fenetre.EXIT_ON_CLOSE);
    setResizable(true);

    setIconImage(new ImageIcon("C:\\Users\\sidot\\Desktop\\download.png").getImage());

    mainPan.setBackground(Color.darkGray);
    mainPan.setLayout(new GridLayout(2,0));
    Border border = LineBorder.createBlackLineBorder();


    title.setText("Calculator 1.0");
    title.setFont(new Font("MONOSPACED", Font.PLAIN, 20));
    title.setForeground(Color.WHITE);
    title.setHorizontalTextPosition(JLabel.CENTER);
    title.setVerticalTextPosition(JLabel.BOTTOM);
    title.setBorder(border);
    mainPan.add(title);

    nb1.setText("Number 1");
    nb1.setFont(new Font("MONOSPACED", Font.BOLD, 15));
    nb1.setForeground(Color.WHITE);
    nb1.setHorizontalTextPosition(JLabel.LEFT);
    nb1.setVerticalTextPosition(JLabel.CENTER);
    nb1.setBorder(border);
    mainPan.add(nb1);

    nb2.setText("Number 2");
    nb2.setFont(new Font("MONOSPACED", Font.BOLD, 15));
    nb2.setForeground(Color.WHITE);
    nb2.setHorizontalTextPosition(JLabel.LEFT);
    nb2.setVerticalTextPosition(JLabel.CENTER);
    nb2.setBorder(border);
    mainPan.add(nb2);

    this.setContentPane(mainPan);
    this.setVisible(true);
}

我想在1號和2號后面有一個文本字段。 謝謝

JPanel的默認布局是FlowLayout 因此,您可以使用JPanel來保存標簽和文本字段:

JPanel rowPanel = new JPanel();
rowPanel.add( label1 );
rowPanel.add( textField1 );
mainPanel.add( rowPanel );

要點是,您可以將面板與不同的布局管理器和組件嵌套在一起,以實現所需的布局。 閱讀有關Layout Manger的swing教程中的部分,以獲得更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM