How to add JButton on JScrollPane?

≡放荡痞女 提交于 2019-12-10 17:42:29

问题


Hi i am trying to make a desktop application in swing here i am using jscrollpane. i want to add multipul button in jscrollpane. i am able to add only single button there how can i do this

My code is given below

 public class AddingToJScrollPane {

  public static void main(String args[]) {
    JFrame frame = new JFrame("Tabbed Pane Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label = new JLabel("Label");
    label.setPreferredSize(new Dimension(1000, 1000));
    JScrollPane jScrollPane = new JScrollPane(label);

    JButton jButton1 = new JButton("Hello");
     JButton jButton2 = new JButton("Hello");

    jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane.setViewportBorder(new LineBorder(Color.RED));
    jScrollPane.getViewport().add(jButton1,jButton2);

    frame.add(jScrollPane, BorderLayout.NORTH);
    frame.setSize(400, 150);
    frame.setVisible(true);
  }
}

Updated code

public class AddingToJScrollPane {

  public static void main(String args[]) {
    JFrame frame = new JFrame("Tabbed Pane Sample");
    JPanel panel = new JPanel();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout( new GridLayout() );
    JLabel label = new JLabel("Label");
    label.setPreferredSize(new Dimension(1000, 1000));
    JScrollPane jScrollPane = new JScrollPane(panel);

    JButton jButton1 = new JButton("Hello");
     JButton jButton2 = new JButton("He");

   // jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane.setViewportBorder(new LineBorder(Color.RED));
   // jScrollPane.getViewport().add(panel);

    frame.add(jScrollPane, BorderLayout.NORTH);
    panel.add(jButton1);
     panel.add(jButton2);
    frame.setSize(400, 150);
    frame.setVisible(true);
  }
}

How can i achieve my desired output Thanks in advance


回答1:


Add the buttons to a panel with suitable layout (e.g. GridLayout or FlowLayout). Add the panel to the scroll pane.



来源:https://stackoverflow.com/questions/22268958/how-to-add-jbutton-on-jscrollpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!