小编典典

JScrollPane无法在空布局中工作

java

  import javax.swing.JCheckBox;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.JPanel;
  import javax.swing.JScrollPane;

public class ScrollJPanelDemo extends JFrame {
   public ScrollJPanelDemo(){
    setSize(480, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label = new JLabel("Select one or more options : ");
    JCheckBox jcb1 = new JCheckBox("Chandigarh");
    JCheckBox jcb2 = new JCheckBox("Mohali");
    JCheckBox jcb3 = new JCheckBox("Delhi");
    JCheckBox jcb4 = new JCheckBox("Noida");
    JCheckBox jcb5 = new JCheckBox("Mumbai");
    JCheckBox jcb6 = new JCheckBox("Kolkata");

    //creating JPanel to hold the checkboxes
    JPanel jpnl = new JPanel();
    jpnl.setLayout(null);
    jpnl.setOpaque(true);
    jcb1.setBounds(0,0,100,40);
            jcb2.setBounds(0,60,100,40);
            jcb3.setBounds(0,120,100,40);
            jcb4.setBounds(0,180,100,40);
            jcb5.setBounds(0,240,100,40);
            jcb6.setBounds(0,300,100,40);
    //adding check boxes and label to the JPanel
    jpnl.add(label);
    jpnl.add(jcb1);
    jpnl.add(jcb2);
    jpnl.add(jcb3);
    jpnl.add(jcb4);
    jpnl.add(jcb5);
    jpnl.add(jcb6);

    //creating the scroll pane that will scroll the panel.
    JScrollPane jscrlPane = new JScrollPane(jpnl);
    jscrlPane.setBounds(0,0,300,300);



        jscrlPane.setHorizontalScrollBarPolicy
       (JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS) ;
   jscrlPane.setVerticalScrollBarPolicy
   (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    //adding that scroll pane to the frame.
    getContentPane().add(jscrlPane);
    setVisible(true);
  }

    public static void main(String args[]){
            new ScrollJPanelDemo();             
        }

 }

我是Java Swing的新手,并尝试在Java代码上使用“滚动”窗格,但是它不起作用。滚动窗格是在垂直方向上添加到框架上的,但无法使用。


阅读 215

收藏
2020-11-30

共1个答案

小编典典

您应该创建自己的面板,JPanel该面板扩展为包含所有复选框,并且在此面板中,重写getPreferredSize()方法如下:

@Override
public Dimension getPreferredSize()
{
    return new Dimension( 300,300 );
}

并在您的代码中使用它:

...

// creating the scroll pane that will scroll the panel.
JScrollPane jscrlPane = new JScrollPane( new MyPanelWithCheckboxes() );
jscrlPane.setBounds( 0, 0, 300, 300 );
...
2020-11-30