Java Swing JList在BorderLayout中动态调整大小

时间:2015-07-24 08:27:51

标签: java swing chat jlist

目前我正在进行聊天。在基地设置的那一刻,我试图让它更好。所以现在我想做一个在线用户列表,但我不知道如何做到以下几点: 我的聊天目前(忽略德语): enter image description here

我已通过以下方式设置在线列表的大小:

JScrollPane userListSP = new JScrollPane();
userListSP.setPreferredSize(new Dimension(200,0));

但是,scrollPane始终保持在x = 200 enter image description here 我尝试通过添加minimumSIze来修复它:

userListSP.setMinimumSize(new Dimension(50,0));

我的问题:有人有一个想法如何实现它调整大小但同时仍然足够大?

1 个答案:

答案 0 :(得分:0)

以此为例:

package com.test.package;

import java.awt.Color;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

/**
 *
 * @author rmu
 */
public class ChatDemo extends JFrame {

    private final JScrollPane scrollPaneMessages;
    private final JList<String> listMessages = new JList<String>();
    private final JPanel pnlUsers = new JPanel();
    private final JTextField txtUserMsgInput = new JTextField();

    public ChatDemo() {
        scrollPaneMessages = new JScrollPane(listMessages);
        pnlUsers.setBackground(Color.WHITE);
        setVisible(true);
        setTitle("Chat layout demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        putSampleData();
        organizeLayout();
    }

    private void organizeLayout() {
        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addComponent(scrollPaneMessages, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE)
                        .addComponent(pnlUsers, 50, 50, 50))
                .addComponent(txtUserMsgInput)
        );
        layout.setVerticalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(scrollPaneMessages)
                        .addComponent(pnlUsers))
                .addComponent(txtUserMsgInput, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
        );
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);
        pack();

    }

    private void putSampleData() {
        DefaultListModel<String> listModel = new DefaultListModel<>();
        listModel.addElement("Very long string with many characters... Oh, so long!!");
        listModel.addElement("This string is shorter");
        listMessages.setModel(listModel);
    }

    public static void main(String[] args) {
        new ChatDemo();
    }
}