How to make scrollable to jPanel

笑着哭i 提交于 2019-12-10 11:27:33

问题


I am making swing application. And there is too much height of my jPanel. So I want to make this panel as scrollable.: Following is my description of my requirement.

I have four jpanel in one jpanel I mean:

JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JPanel p4=new JPanel();

I am adding p2, p3, p4 inside p1 like following output:

like above showing panel has more height than computer screen height. So I want to display all content of my panel on computer screen by scrolling.

I searched here and found the following questions:

  • How to make a JPanel scrollable?
  • How do i get vertical scrolling to JPanel?

However, the answers did not solve myproblem.


回答1:


Without seeing your code, my guess is that you don't have a JScrollpane to provide the scrollable behaviour you want.

JPanel mainPanel = new JPanel(); //This would be the base panel of your UI
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JPanel p4=new JPanel();
JPanel newPanel = new JPanel();
newPanel.add(p1);
newPanel.add(p2);
newPanel.add(p3);
newPanel.add(p4);
JScrollPane pane = new JScrollPane(newPanel);
mainPanel.add(pane);

Since you use NetBeans, add a JScrollpane from the palette in which you'll add a panel to contain the 4 others. I think you could also just add the 4 panel into the JScrollpane.




回答2:


Add your panel to a JScrollPane. Assumed that you want vertical scrolling only:

JScrollPane scrollPane=new JScrollPane(panel, 
   ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,  
   ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

For fine-tuning the scroll amounts, you can optionally implement the Scrollable interface.
See also How to Use Scroll Panes (The Java Tutorial)




回答3:


It is easy to design scroll pane using Netbeans IDE. Below given are the steps I followed to add a scroll pane:

    1. In Netbeans GUI editor, select all panels which requires scroll pane using CTRL+left click
    2. Right click on the hilighted panels, select the option 'Enclose in' -> Scroll Pane. This will add a scroll pane for the selected panels.
    3. If there are other elements than Panel(say JTree), select all the elements ->Enclose in ->Panel. Then enlose the new parent panel to scroll pane
    4. Make sure that 'Auto Resizing' is turned on for the selected parent panel(Right click on panel -> Auto resizing -> Tick both Horizontal and vertical)


来源:https://stackoverflow.com/questions/18408668/how-to-make-scrollable-to-jpanel

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