在JScrollPane中将JButtons堆叠在一起

时间:2017-01-19 15:18:14

标签: java layout

我希望将多个JPanel堆叠在一起,以便在JScrollPane中滚动

enter image description here

我试过了:

的JFrame:

setLayout(new BorderLayout());

JPanel boxListPanel = new JPanel();
        boxListPanel.setLayout(new BoxLayout(boxListPanel,BoxLayout.Y_AXIS));

boxListPanel.add(boxp1);
boxListPanel.add(boxp2);
boxListPanel.add(boxp3);

JScrollPane jscollPane = new JScrollPane(boxListPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

add(jscollPane, BorderLayout.CENTER);

但是JButton像这样拉伸:

enter image description here

当我使用FlowLayout时,JButtons没有拉伸,但它们是按顺序排列的。

解决方案1:

DefaultListModel model = new DefaultListModel();

box = new Box();
model.addElement(boxp);
box = new Box();
model.addElement(boxp);
box = new Box();
model.addElement(boxp);

JList<Box> boxes = new JList<>(model);
        boxes.setCellRenderer(new PanelRenderer());

JScrollPane jscollPane = new JScrollPane(boxes, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

jscollPane.setBounds(0, 0, 395, 600);
add(jscollPane);


class PanelRenderer implements ListCellRenderer {

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        JButton renderer = (JButton) value;
//            renderer.setBackground(isSelected ? Color.red : list.getBackground());
        renderer.setBackground(list.getBackground());
        return renderer;
    }
}

解决方案2:

setLayout(null);

int y_achis = 5;
        int x_achis = 5;
        int c_with = 380;
        int c_height = 65;
        int c_padding = 5;

...
box = new Box();
box.setBounds(x_achis, y_achis, c_with, c_height);
add(box)
y_achis += c_height + c_padding;

box = new Box();
box.setBounds(x_achis, y_achis, c_with, c_height);
add(box)
y_achis += c_height + c_padding;

1 个答案:

答案 0 :(得分:0)

尝试将框架的布局设置为absolutLayout!