0
大家好,我試圖創建一個聊天會話GUI。我設法按照正確的順序排列所有組件。唯一的問題是,框架沒有響應,每當我嘗試調整窗口的大小時,組件保持相同的尺寸,而且當我在JtextArea中鍵入文本時,它們將邊框放大,並佔據框架中的任何其他組件。我試過使用JScrollPane或設置最大尺寸,但它不起作用。誰能幫我。這是我的代碼。JScrollPane和響應GUI與gridbaglayout
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.DefaultCaret;
public class ClientGUI extends JPanel {
public ClientGUI() {
Dimension size = getPreferredSize();
size.width = 500;
setPreferredSize(size);
setBorder(BorderFactory.createTitledBorder("Peron"));
GridBagConstraints gbc = new GridBagConstraints();
JTextArea chat, list;
JTextField wm;
JButton sm, sf, pm, lo;
JFrame fr = new JFrame("FRAME");
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setSize(200, 200);
fr.setMinimumSize(new Dimension(1400, 1000));
JPanel panel = new JPanel(new GridBagLayout());
fr.add(panel);
gbc.insets = new Insets(40, 40, 40, 40);
chat = new JTextArea("Welcome to the chat room");
// chat.setEditable(false);
JScrollPane scroll = new JScrollPane(chat); // place the JTextArea in a
// scroll pane
panel.add(scroll);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 5;
gbc.gridheight = 7;
// gbc.gridwidth = java.awt.GridBagConstraints.RELATIVE;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.ipady = 400;
gbc.ipadx = 200;
panel.add(chat, gbc);
wm = new JTextField("Insert message", 10);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.gridheight = 2;
gbc.ipady = 150;
gbc.ipadx = 300;
gbc.gridx = 0;
gbc.gridy = 10;
panel.add(wm, gbc);
list = new JTextArea("User online");
gbc.gridx = 5;
gbc.gridy = 2;
gbc.ipady = 400;
gbc.ipadx = 300;
panel.add(list, gbc);
sm = new JButton("Send");
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 10;
gbc.ipady = 20;
gbc.ipadx = 200;
panel.add(sm, gbc);
pm = new JButton("Private message");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 4;
gbc.gridy = 10;
gbc.ipady = 20;
gbc.ipadx = 20;
panel.add(pm, gbc);
lo = new JButton("LOGOUT");
gbc.gridx = 5;
gbc.gridy = 1;
gbc.ipady = 20;
panel.add(lo, gbc);
sf = new JButton("Send File");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 5;
gbc.gridy = 10;
gbc.ipady = 20;
gbc.ipadx = 20;
panel.add(sf, gbc);
}
}
非常感謝,它的工作! – Werokk
你知道如何讓用戶調整窗口大小來響應組件嗎? – Werokk
@Werokk你能澄清你的意思嗎?我似乎注意到這個框架也很奇怪。我刪除了兩行'fr.setMinimumSize()'和'fr.setSize()',並在代碼的末尾添加了'fr.pack()'。 我強烈建議重新構建代碼以分隔面板和框架配置,以便於進行故障排除。 – KyleKW