Java 组件没有';无法使用GridBagLayout正确显示

Java 组件没有';无法使用GridBagLayout正确显示,java,swing,layout-manager,gridbaglayout,Java,Swing,Layout Manager,Gridbaglayout,我正在学习JavaSwing,这让我很困惑。“退出”按钮不显示。但是,如果我将textArea的代码部分移动到按钮的两部分之后,它将正确显示。那为什么呢 package练习1; 导入javax.swing.*; 导入java.awt.*; 公共类聊天客户端{ 私人JTEXTEXTAREA textArea; 私有JTextField textField; 私人JButton btnSend; 私人JButton btnQuit; 私有JFrame; 私人JPanel小组; 私有JScrollPa

我正在学习JavaSwing,这让我很困惑。“退出”按钮不显示。但是,如果我将
textArea
的代码部分移动到按钮的两部分之后,它将正确显示。那为什么呢

package练习1;
导入javax.swing.*;
导入java.awt.*;
公共类聊天客户端{
私人JTEXTEXTAREA textArea;
私有JTextField textField;
私人JButton btnSend;
私人JButton btnQuit;
私有JFrame;
私人JPanel小组;
私有JScrollPane滚动窗格;
私有void启动框架(){
panel=newJPanel(newGridBagLayout());
GridBagConstraints c=新的GridBagConstraints();
textArea=新的JTextArea(10,50);
scrollPane=新的JScrollPane(textArea);
c、 gridx=0;
c、 gridy=0;
c、 网格高度=3;
panel.add(滚动窗格,c);
btnSend=新的JButton(“发送”);
c、 gridx=1;
c、 gridy=0;
c、 锚点=GridBagConstraints.NORTH;
面板。添加(BTN发送,c);
btnQuit=新的JButton(“退出”);
c、 gridx=1;
c、 gridy=1;
c、 锚点=GridBagConstraints.NORTH;
面板。添加(btnQuit,c);
}
受保护的聊天客户端(){
frame=新的JFrame(“聊天室”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
启动框架();
框架。添加(面板);
frame.pack();
frame.setVisible(true);
}
公共静态void main(字符串[]args){
ChatClient=new ChatClient();
}
}

简单:您忘记重置
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);

}

您不应该使用gridHeight为3。您只有两行上的按钮,因此尝试指定一个组件来填充三行将不起作用。这不会引起问题,但代码的“意图”是误导性的。网格高度应为2。