gpt4 book ai didi

java - Java Swing 中的面板向左浮动并带有垂直条

转载 作者:行者123 更新时间:2023-12-02 02:02:08 25 4
gpt4 key购买 nike

如何创建一个 JPanel ,其中有很多左对齐 float 按钮并且仅具有垂直滚动条?

按钮应按如下方式排序。

1  2  3  45  6  7  89 10 11 12

最佳答案

如果您使用GridLayout,那么您将无法添加滚动 Pane ,因为它会自动调整大小以适应其中的所有组件。一种更简单的方法是使用 FlowLayoutsetPreferredSize(...) 来设置面板的大小。虽然不建议设置面板的大小,但您仍然需要以某种方式使用滚动条。这是一个 MCVE:

enter image description here

import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Example extends JFrame {

private final int BUTTON_WIDTH = 100;
private final int BUTTON_HEIGHT = 50;
private final int BUTTON_ROWS = 3;
private final int BUTTON_COLUMNS = 4;
private final int OFFSET = 20;// the width of the actual scroll bar in pixels (approximately).
private final int PANEL_WIDTH = BUTTON_WIDTH * BUTTON_COLUMNS + OFFSET;
private final int PANEL_HEIGHT = BUTTON_HEIGHT * BUTTON_ROWS + OFFSET;
private final int SCROLL_HEIGHT = 100;//or whatever you would like...
private final JButton[] buttons = new JButton[BUTTON_ROWS * BUTTON_COLUMNS];

public Example() {
JPanel panel = new JPanel(new FlowLayout());
JScrollPane scroll = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panel.setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
scroll.setPreferredSize(new Dimension(PANEL_WIDTH + OFFSET, SCROLL_HEIGHT));
for (int i = 0; i < buttons.length; i++) {
JButton button = new JButton((i + 1) + "");
buttons[i] = button;
button.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
panel.add(button);
}

//if you want the panel to resize when window is stretched.
//setLayout(new FlowLayout(FlowLayout.CENTER));
add(scroll);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}

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

关于java - Java Swing 中的面板向左浮动并带有垂直条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51412770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com