【问题标题】:The component doesn't display correctly with GridBagLayout组件无法使用 GridBagLayout 正确显示
【发布时间】:2020-01-10 02:14:50
【问题描述】:

我正在学习 java swing,这让我很困惑。退出按钮不显示。但是,如果我将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();
    }
}

【问题讨论】:

  • 您不应该使用 3 的 gridHeight。您只有两行上的按钮,因此尝试指定一个组件来填充 3 行是行不通的。它不会引起问题,但是您的代码的“意图”具有误导性。 gridHeight 应该是 2。

标签: java swing layout-manager gridbaglayout


【解决方案1】:

简单:添加 JScrollPane 后您忘记重置 c.gridheight = 1;。如果不这样做,发送按钮将覆盖退出按钮。

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);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 2014-08-23
    相关资源
    最近更新 更多