猿问

GridBagLayout 组件无法正确显示

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

    }

}


PIPIONE
浏览 102回答 1
1回答

一只名叫tom的猫

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);}
随时随地看视频慕课网APP

相关分类

Java
我要回答