Java:无法将Gridlayout应用于Jscrollpane.获取java.lang.ClassCastException

Ali*_*a87 1 java swing jframe jscrollpane grid-layout

我使用Gridlayout将4个元素放在一行中.首先,我有一个JPanel,一切正常.对于行数变大而我必须能够向下滚动的情况,我改变了一下.现在我添加JPanel了一个JScrollPane.我使用相同的代码,现在我只是将元素添加到视口中Jscrollpane,但现在我得到了这个例外Get java.lang.ClassCastException: layout of JScrollPane must be a ScrollPaneLayout: at javax.swing.JScrollPane.setLayout(Unknown Source),我不知道究竟是为什么.为什么Gridlayout不为人所知Jscrollpane

这是代码:

    public objectDetails() {
    setTitle("LLI_MC_Solver");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    contentPane = new JPanel();
    contentPane.setLayout(new GridLayout());
    setBounds(100, 100, 510, 401);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setVisible(true);
    contentPane.setPreferredSize(new Dimension(500, 390));

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setViewportBorder(new LineBorder(new Color(0, 0, 0), 2));
    scrollPane.setBounds(10, 10, 474, 342);
    scrollPane.setLayout(new GridLayout(0,4)); //Line which causes the error
    scrollPane.setPreferredSize(new Dimension(465, 330));
    contentPane.add(scrollPane);

    JPanel view = (JPanel)scrollPane.getViewport().getView();

        for(Values v : colDetails)
        {
            JLabel lblC = new JLabel();
            lblC.setText(k);
            view.add(lblC);
            view.validate();

            JLabel lblN = new JLabel();
            lblN.setText(v.getName());
            view.add(lblN);
            view.validate();

            JLabel lblT = new JLabel();
            lblT.setText(v.getType());
            view.add(lblT);
            view.validate();

            JTextField valueBox = new JTextField();
            valueBox.setText(v.getValue());
            view.add(valueBox);
            view.validate();

        }
}
Run Code Online (Sandbox Code Playgroud)

我根据编译器标记了引起问题的行.我不明白为什么,使用JPanel相同的代码工作正常.添加了元素的for循环我发布了完成目的,问题必须在setLayout()-Method中的某个地方.

在此先感谢,感谢每一位帮助.

cam*_*ckr 9

scrollPane.setLayout(new GridLayout(0,4)); //导致错误的行

您无法更改滚动窗格的布局管理器.

JScrollPane有自己的自定义布局管理器,因为它需要管理水平/垂直滚动条以及行/列标题等.

而是添加一个使用GridLayout的面板:

JPanel panel = new JPanel( new GridLayout(0, 4) );
panel.add( component1 );
panel.add( component2 );
panel.add( component3 );
panel.add( component4 );
JScrollPane = new JScrollPane( panel );
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是`JScrollPane`中的一个错误...setLayout应该受到保护...`public void setLayout(LayoutManager布局)` (2认同)