简体   繁体   English

根据用户输入生成Java swing字段

[英]Generating java swing fields based on user input

Java beginner here. Java初学者在这里。

I am trying to generate Labels based on user input(take input for the number of labels to generate between 0 to 50) in a JPanel inside a JScrollPane. 我试图基于JScrollPane内的JPanel中的用户输入(接受输入以生成0到50之间的标签数量)来生成Labels。

The labels are generating correctly but the problem is the panel cant be scrolled down to view all the Labels. 标签生成正确,但问题是面板无法向下滚动以查看所有标签。

Is it because I am using absolute layout for the panel? 是因为我在面板上使用绝对布局吗? If yes then what might be the solution? 如果是,那么解决方案是什么? Please guide. 请指导。

Note: I made the labels using an array of 50 JLabels in a for loop. 注意:我在for循环中使用50个JLabel的数组制作标签。 Terrible programming practice maybe but works. 糟糕的编程实践也许奏效。

Here's the code snippet 这是代码片段

        frame = new JFrame();
        frame.setSize(800, 800);
        frame.getContentPane().setLayout(null);

        JScrollPane scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setBounds(103, 37, 439, 350);
        frame.getContentPane().add(scrollPane);

        JPanel panel = new JPanel();
        scrollPane.setViewportView(panel);
        panel.setLayout(null);

        JButton btnGenerateLabels = new JButton("Generate Labels");
        btnGenerateLabels.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JLabel[] lab =  new JLabel[50];
                int  y = 50;
                for(int i=0; i<50; i++)
                {
                    lab[i] = new JLabel();
                    lab[i].setText("Label "+(i+1));
                    panel.add(lab[i]);
                    lab[i].setBounds(180, y, 97, 25);
                    y += 30;
                }
            }
        });
        btnGenerateLabels.setBounds(129, 23, 152, 25);
        panel.add(btnGenerateLabels);

Is it because I am using absolute layout for the panel? 是因为我在面板上使用绝对布局吗?

Yes. 是。 Don't use a null layout. 不要使用空布局。 Swing was designed to be used with layout managers. Swing旨在与布局管理器一起使用。

The solution is to use a layout manager, probably the GridLayout as was suggested. 解决方案是使用布局管理器,可能是建议的GridLayout。

After all the components have been added to the panel you then need to invoke revalidate() and repaint() on the panel. 在将所有组件添加到面板之后,您需要在面板上调用revalidate()repaint() This will invoke the layout manager and each component will be given a size/location. 这将调用布局管理器,并且将为每个组件指定大小/位置。

Scrollbars will then appear as required. 滚动条将根据需要出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM