简体   繁体   English

如何在Java中使用SpringLayout的Jpanel中添加垂直滚动条?

[英]How to add vertical scrollbar to Jpanel which is having SpringLayout in Java?

I have below snippet of code in which TestClass is extending jPanel which is using SpringLayout, in which I'm not able to add vertical scrollbar. 我在下面的代码段中,TestClass扩展了使用SpringLayout的jPanel,在其中我无法添加垂直滚动条。

Could you please help me guys? 你能帮我吗?



        public class TestClass extends JPanel {

            private SpringLayout layout;
            private Spring s, sprWest;
            private JComboBox comboDevice = new JComboBox();
            private JComboBox comboCommand = new JComboBox();
            private JLabel lblDevice = new JLabel("Select the Device:");
            private JLabel lblCommand = new JLabel("Select Command:");
            private JButton btnCommand = new JButton("Save");

            public TestClass () {
                layout = new SpringLayout();
                s = Spring.constant(0, 60, 60);
                setLayout(layout);
            }

            public void populateFields(){
                add(lblCommand);
                add(comboCommand);


                sprLblEast = Spring.sum(s, Spring.max(layout.getConstraints(lblCommand).getWidth(), layout.getConstraints(lblDevice).getWidth()));
                Spring strut = Spring.constant(10);

                layout.putConstraint(SpringLayout.NORTH, lblCommand, strut, SpringLayout.SOUTH, comboDevice);
                layout.putConstraint(SpringLayout.NORTH, comboCommand, strut, SpringLayout.SOUTH, comboDevice);
                layout.putConstraint(SpringLayout.EAST, lblCommand, sprLblEast, SpringLayout.WEST, this);
                layout.putConstraint(SpringLayout.WEST, comboCommand, Spring.sum(s, layout.getConstraints(lblCommand).getWidth()), SpringLayout.WEST, lblCommand);
                layout.putConstraint(SpringLayout.EAST, this, sprLblEast, SpringLayout.WEST, comboCommand);

                List cmdList = getCommandList();
                for (int index = 0; index < cmdList.size(); index++) {
                    comboCommand.addItem(cmdName);
                }
                validate();
                repaint();
            }
    }

I would sugest use of ScrollPane 我建议使用ScrollPane

ScrollPane mainWindow = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED); mainWindow.add(this);

but You would have to use another object than Your TestClass as view, here it would be mainWindow . 但是您必须使用TestClass以外的其他对象作为视图,这里是mainWindow

You could use also JScrollPane from Swing: tutorial for JScrollPane 您也可以使用Swing 中的JScrollPaneJScrollPane教程

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

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