【问题标题】:How do I add a scrollbar to a JFrame with setLayout(null)?如何使用 setLayout(null) 向 JFrame 添加滚动条?
【发布时间】:2022-01-21 21:29:53
【问题描述】:

我有一些组件需要在上面使用setBounds(),这就是我使用setLayout(null) 的原因。

但我的一些组件在窗口外(在 Y 轴下方)。我想知道是否有办法添加滚动条来向下导航窗口以便查看所有剩余的组件。我的窗口截图如下。

我的窗口图像的输出:

【问题讨论】:

  • 你不需要使用空布局,也不应该使用空布局。如果您有一个垂直的信息列表,请将其放在 JList 或 JTable 中,并将 JList 或 JTable 放在 JScrollPane 中。
  • @AndrewThompson 能否请您发布此代码的副本。谢谢

标签: java swing awt layout-manager jscrollpane


【解决方案1】:

使用布局生成 GUI 会很简单。将显示列表的组件(看起来很适合成为JTable,给定每行/行的两条数据)放入JScrollPane。将滚动窗格放入BorderLayoutCENTER。将红色标签放入边框布局的PAGE_START。然后..哦等等,工作完成了!

这可能是它的样子(使用JTextArea 而不是表格)。

你能把这段代码发一份吗。

尝试根据上面的说明实现它。如果有问题,请发布您的尝试minimal reproducible example

【讨论】:

    【解决方案2】:

    由于您将滚动区域中的项目称为组件,而不是 JTextArea 中的文本,因此请查看以下内容。

    import java.awt.*;
    import javax.swing.*;
    import java.util.Random;
    
    public class Mainframe {
        private JFrame f;
        Box box;
        JScrollPane scrollPane;
        Random rand = new Random();
    
        public static void main(String[] args) {
            new Mainframe().go();
        }
    
        private void go() {
            box = new Box(BoxLayout.Y_AXIS);
    
            JLabel label = new JLabel("Possible Paths and Total Distances");
            label.setForeground(Color.RED);
    
            for (int i = 0; i < 200; i++) {
                box.add(Box.createRigidArea(new Dimension(0, 2)));// creates space between the components
                box.add(new JLabel(i + " : " + rand.nextInt(10000)));
            }
    
            scrollPane = new JScrollPane(box);
            Dimension dim = new Dimension(box.getComponent(0).getPreferredSize());
            scrollPane.getVerticalScrollBar().setUnitIncrement(dim.height * 2); // adjusts scrolling speed
            //scrollPane.getViewport().setBackground(Color.WHITE);
    
            f = new JFrame();
            f.getContentPane().add(label, BorderLayout.NORTH);
            f.getContentPane().add(scrollPane, BorderLayout.CENTER);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(640, 480);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-07
      • 1970-01-01
      • 1970-01-01
      • 2018-04-30
      • 1970-01-01
      • 2013-10-23
      • 1970-01-01
      相关资源
      最近更新 更多