我尝试编写一个像这样的 GUI。每次创建新按钮并将其放置在特定位置时单击按钮,但在 jscrollpane 中添加一些按钮后,滚动条未激活,因此我无法看到所有创建的按钮。
我的代码在这里:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test{
private JFrame frame;
private JPanel panel1,panel2;
private JScrollPane pane;
private JButton button;
int i = 1, y = 10;
public Test()
{
panel2 = new JPanel(null);
panel2.setBounds(0,0,280,300);
button = new JButton("Add Button");
button.setBounds(90,10,120,30);
pane = new JScrollPane();
pane.setBounds(10,50,280,300);
panel1 = new JPanel(null);
panel1.setPreferredSize(new Dimension(300,400));
panel1.setBackground(Color.WHITE);
frame = new JFrame("Test");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1);
frame.pack();
panel1.add(pane);
panel1.add(button);
pane.add(panel2);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panel2.add(new JButton("Button "+i)).setBounds(80,y,120,30);
i += 1;
y += 35;
}
});
}
public static void main(String[] args) {
new Test();
}
}
最佳答案
不要使用空布局。不要使用 setBounds()。
只有当面板的首选尺寸大于滚动 Pane 的尺寸时,滚动条才会自动显示。
布局管理器的工作是:
- 设置组件的位置
- 设置组件的大小
- 计算面板的首选尺寸。
因此,解决方案是在面板上使用适当的布局管理器。
例如,您可以使用 BoxLayout:
//panel2 = new JPanel(null);
panel2 = new JPanel();
panel2.setLayout( new BoxLayout(panel2, BoxLayout.Y_AXIS) );
然后,当您将组件添加到可见框架时,您需要 revalidate() 面板以调用布局管理器:
//panel2.add(new JButton("Button "+i)).setBounds(80,y,120,30);
panel2.add(new JButton("Button "+i));
panel2.revalidate();
不需要 panel1。只需将组件添加到框架即可:
//panel1.add(pane);
//panel1.add(button);
frame.add(button, BorderLayout.PAGE_START);
frame.add(pane, BorderLayout.CENTER);
但还有其他问题:
pane = new JScrollPane();
您实际上需要将面板添加到滚动 Pane 。所以代码应该是:
pane = new JScrollPane(panel2);
由于组件只能有一个父组件,因此您需要删除:
pane.add(panel2);
由于 panel2 已添加到滚动 Pane 中。
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1);
frame.pack();
以上逻辑是错误的。
您应该仅在所有组件都添加到框架后调用 pack() 和 setVisible( true ) 。
所以发布的大部分代码都是错误的。
首先阅读 Swing 教程中关于 Layout Managers 的部分。下载工作演示代码并了解如何更好地构建代码。修改您的具体示例的代码。
关于java - 如何在jscrollpane中添加自动滚动条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62481109/