【问题标题】:i have added the scroll bar but it does not scroll up and down the frame我添加了滚动条,但它不会在框架上上下滚动
【发布时间】:2015-04-09 09:48:06
【问题描述】:

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

 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);
}

【问题讨论】:

  • 源代码中的一个空白行是永远需要的。 { 之后或 } 之前的空行通常也是多余的。

标签: java jframe awt jscrollbar


【解决方案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);
}

【讨论】:

  • 我运行你给出的代码,但它给出了以下错误线程“main”java.lang.Error中的异常:未解决的编译问题:ScrollPaneConstants无法解析为CreateProject.Window.main的变量(Window.java:39)
  • 应该是 JScrollPane.VERTICAL_SCROLLBAR_​​ALWAYS
猜你喜欢
  • 1970-01-01
  • 2013-01-24
  • 1970-01-01
  • 2013-08-23
  • 1970-01-01
  • 2017-08-07
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多