为了账号安全,请及时绑定邮箱和手机立即绑定

GridBagLayout 组件无法正确显示

GridBagLayout 组件无法正确显示

PIPIONE 2023-07-19 14:54:46
我正在学习 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();    }}
查看完整描述

1 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

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


}


查看完整回答
反对 回复 2023-07-19
  • 1 回答
  • 0 关注
  • 101 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信