我添加了滚动条但它不会在框架上下滚动

时间:2015-04-09 09:48:07

标签: java jframe awt jscrollbar

我添加了滚动条,但它不会在框架上下滚动,我也看不到我创建的上标签。 请给我任何建议,这样我就可以在我的框架中上下滚动。 我还有一个问题,当我的框架大小是固定的,我想创建 我必须向下滚动的许多标签和文本字段,所以在这种情况下我必须增加其框架大小

 public static void main(String[] args) 
  {
    JFrame frame = new JFrame("jframe");
    JLabel[] labels=new JLabel[50];

  for (int i=0;i<labels.length;i++)
  {
        labels[i]=new JLabel("Column" + i);
  }


    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints cst = new GridBagConstraints();
    JScrollBar vbar=new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 500);

    for(int i =0 ; i<50 ;i++)
    {    

         cst.fill = GridBagConstraints.HORIZONTAL;
         cst.gridx = 0;
         cst.gridy = i;//
         cst.gridwidth = 2;
         panel.add(labels[i],cst);

    }       




    frame.getContentPane().add(vbar, BorderLayout.EAST);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1300,700);
    frame.getContentPane().add(panel);
    frame.setVisible(true);
}

1 个答案:

答案 0 :(得分:1)

为什么不使用JScrollPane并将面板放在上面? 看看:https://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html

public static void main(String[] args)
{
    JFrame frame = new JFrame("jframe");
    JLabel[] labels = new JLabel[50];

    for(int i = 0; i < labels.length; i++)
    {
        labels[i] = new JLabel("Column" + i);
    }

    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints cst = new GridBagConstraints();
    //      JScrollBar vbar = new JScrollBar(JScrollBar.VERTICAL,30,40,0,500);

    for(int i = 0; i < 50; i++)
    {

        cst.fill = GridBagConstraints.HORIZONTAL;
        cst.gridx = 0;
        cst.gridy = i;//
        cst.gridwidth = 2;
        panel.add(labels[i],cst);

    }

    JScrollPane scrollPane = new JScrollPane(panel);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    frame.getContentPane().add(scrollPane,BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1300,700);
    frame.setVisible(true);
}
相关问题