【发布时间】:2021-03-22 12:45:36
【问题描述】:
package me.an.ugm;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
public class Application
{
private JFrame frame;
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Application window = new Application();
window.frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
public Application()
{
initialize();
}
private void initialize()
{
frame = new JFrame();
frame.setTitle("Application");
frame.setBounds(100, 100, 401, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//frame.setResizable(false);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 296, 710);
panel.setLayout(null);
JScrollPane scrollPane = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBounds(0, 0, 296, 399);
frame.getContentPane().add(scrollPane);
for (int i = 0, j = 10; i < 20; i++, j += 35)
{
JButton button1 = new JButton();
button1.setBounds(10, j, 25, 25);
panel.add(button1);
JComboBox<String> selectorBox = new JComboBox<>();
selectorBox.setBounds(40, j, 200, 25);
panel.add(selectorBox);
JButton button2 = new JButton();
button2.setBounds(245, j, 25, 25);
panel.add(button2);
}
}
}
我不知道为什么滚动条不显示。 JPanel 比 JScrollPane 大,所以我认为它应该出现。此外,当我尝试将 setPreferredSize 用于滚动窗格而不是 setBounds 或 setSize 时,根本什么都没有显示。我对该程序的最终目标是在右侧关闭一个按钮以添加另一组按钮(循环中的按钮),用于选择另一个项目。我希望程序以 10 行按钮开始,但我将其设置为 20 以测试滚动条。是没有布局的问题还是我把滚动窗格弄乱了?
【问题讨论】:
-
不要使用空布局!!! Swing 旨在与布局管理器一起使用。当您使用空布局时,滚动窗格将不起作用。
-
请记住,LayoutManagers 旨在帮助开发人员。他们在幕后做了很多事情,使需要付出很多努力才能完成的事情。为什么不想使用它们?
标签: java swing jscrollpane null-layout-manager