将JButton添加到滚动窗格

时间:2018-07-05 10:02:22

标签: java layout jbutton jscrollpane

JAVA:

我想将一些JButton添加到滚动窗格。 JButton是聊天室(就像在Skype中一样)。我希望它们仅包含1列。 组/行的数量应灵活。 按钮的大小应始终保持相同(300x50或类似大小),并且按钮内的文本应左对齐。 我该如何实现?

代码:

//You will see some Math.Max and Math.Min - these are required because in your comments 
//you state the pairs can be out of order (the second value is less than the first)

int upper = int.MinValue;
values = values
    //Group all pairs by their minimum value, so (18,30) and (18,27) for example 
    //would be processed together
    .GroupBy(x => Math.Min(x.Item1, x.Item2))
    //Sort the groups based on their minimum value, so they can be processed in order. 
    //Although your example does not require this, the comments say this is required.
    .OrderBy(x => x.Key)
    //From the group [which may contain (18,30) and (18,27) for example],
    //only choose the one with the highest max value. This will choose (18,30)
    .Select(x => x.OrderBy(y => Math.Max(y.Item1, y.Item2)).Last())
    //Now iterate through the items and throw away the items which are inside
    //a pair previously processed pair. We use the upper variable to
    //keep track of the greatest processed upper bound to make throwing away 
    //previously processed pairs easy
    .Where(x =>
    {
        var max = Math.Max(x.Item1, x.Item2);
        if (upper < max)
        {
            upper = max;
            return true;
        }
        else
        {
            return false;
        }

    }).ToList();

2 个答案:

答案 0 :(得分:1)

首先隔离所需的功能。从JPanelGridBagLayout和一些按钮开始...

    setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.fill = GridBagConstraints.HORIZONTAL;

    for (int index = 0; index < 100; index++) {
        add(new JButton("Chat " + (index + 1)), gbc);
    }

然后将其添加到JScrollPane并将其添加到主容器中,也许使用BorderLayout

frame.add(new JScrollPane(new ChatListPane()), BorderLayout.LINE_START);

您可能会发现,您可能还需要实现Scrollable interface来更好地控制JScrollPane的大小以更好地满足您的整体需求。当我在这里使用它时,您并不总是需要它...

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Scrollable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new ChatPane());
                frame.add(new JScrollPane(new ChatListPane()), BorderLayout.LINE_START);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ChatPane extends JPanel {

        public ChatPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    public class ChatListPane extends JPanel implements Scrollable {

        public ChatListPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            for (int index = 0; index < 100; index++) {
                add(new JButton("Chat " + (index + 1)), gbc);
            }
        }

        @Override
        public Dimension getPreferredScrollableViewportSize() {
            return new Dimension(100, 100);
        }

        @Override
        public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
            return 64;
        }

        @Override
        public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
            return 64;
        }

        @Override
        public boolean getScrollableTracksViewportWidth() {
            return true;
        }

        @Override
        public boolean getScrollableTracksViewportHeight() {
            return false;
        }

    }

}

另一个更好的解决方案是使用JList和自定义ListCellRenderer

有关更多详细信息,请参见How to Use Lists

答案 1 :(得分:0)

创建一个新的JPanel,设置GridBadLayout或GridLayout并添加聊天按钮。 然后用新面板创建一个JScrollPane。 您可以在JPanel上实现Scrollable来改善滚动(鼠标滚动)。

相关问题