簡體   English   中英

組件無法使用GridBagLayout正確顯示

[英]The component doesn't display correctly with GridBagLayout

我正在學習Java swing,這對我非常困惑。 退出按鈕不顯示。 但是,如果我將textArea的代碼部分textArea按鈕的兩個部分之后,它將正確顯示。 所以為什么?

package exercise1;

import javax.swing.*;
import java.awt.*;

public class ChatClient {
    private JTextArea textArea;
    private JTextField textField;
    private JButton btnSend;
    private JButton btnQuit;
    private JFrame frame;
    private JPanel panel;
    private JScrollPane scrollPane;

    private void launchFrame() {
        panel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        textArea = new JTextArea(10, 50);
        scrollPane = new JScrollPane(textArea);
        c.gridx = 0;
        c.gridy = 0;
        c.gridheight = 3;
        panel.add(scrollPane, c);

        btnSend = new JButton("Send");
        c.gridx = 1;
        c.gridy = 0;
        c.anchor = GridBagConstraints.NORTH;
        panel.add(btnSend, c);

        btnQuit = new JButton("Quit");
        c.gridx = 1;
        c.gridy = 1;
        c.anchor = GridBagConstraints.NORTH;
        panel.add(btnQuit, c);


    }

    protected ChatClient() {
        frame = new JFrame("Chat Room");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        launchFrame();
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        ChatClient client = new ChatClient();
    }
}

簡單:您忘記了重置c.gridheight = 1; 添加JScrollPane之后。 如果不這樣做,發送按鈕將覆蓋退出按鈕。

private void launchFrame() {
    panel = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    c.fill = GridBagConstraints.HORIZONTAL;  // ** This is also worthwhile **

    textArea = new JTextArea(10, 50);
    scrollPane = new JScrollPane(textArea);
    c.gridx = 0;
    c.gridy = 0;
    c.gridheight = 3;
    panel.add(scrollPane, c);

    btnSend = new JButton("Send");
    c.gridx = 1;
    c.gridy = 0;
    c.gridheight = 1;  // ********* ADD THIS *********
    c.anchor = GridBagConstraints.NORTH;
    panel.add(btnSend, c);

    btnQuit = new JButton("Quit");
    c.gridx = 1;
    c.gridy = 1;
    c.anchor = GridBagConstraints.NORTH;
    panel.add(btnQuit, c);

}

暫無
暫無

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

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