gpt4 book ai didi

java - GridBagLayout 组件无法正确显示

转载 作者:行者123 更新时间:2023-11-30 01:46:18 24 4
gpt4 key购买 nike

我正在学习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();
}
}

最佳答案

简单:添加 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);

}

关于java - GridBagLayout 组件无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57834918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com