Add scrollbar to JFrame

Source code below will show you, how to add scrollbar to a JFrame.

******************************************************************************
COMPLETE SOURCE CODE FOR : AddScrollBarToJFrame.java
******************************************************************************


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

public class AddScrollBarToJFrame
{
public static void main(String[]args)
{
//Create a JPanel
JPanel panel=new JPanel();

//Create a scrollbar using JScrollPane and add panel into it's viewport
//Set vertical and horizontal scrollbar always show
JScrollPane scrollBar=new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

//Create a JFrame with title ( AddScrollBarToJFrame )
JFrame frame=new JFrame("AddScrollBarToJFrame");

//Add JScrollPane into JFrame
frame.add(scrollBar);

//Set close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(400,400);

//Make JFrame visible. So we can see it.
frame.setVisible(true);

//So, if you want to add other component like JTextArea, just add them into JPanel.After that add
//the JPanel into JScrollPane before add the JScrollPane into JFrame.
}
}


******************************************************************************
JUST COMPILE AND EXECUTE IT
******************************************************************************

5 comments:

  1. Works like a charm. Thank you.

    ReplyDelete
  2. Very nice Example. Thanks. Can you also elaborate your example so that more than 1 panel could be placed within the "scrollBar" (i.e. the JScrollPane in your example).

    ReplyDelete
  3. THAAAAANKSSS YOU!!!
    YOU'RE THE BEST

    ReplyDelete
  4. But how do you add the scroll bar to the whole frame not just one panel?

    ReplyDelete
  5. can we use jscrollpane in null Layout() ? if answer is no then how can we set the position of buttons , textfield , backgroundimage etc in panel .PLZ give me answer.

    ReplyDelete

Leave a comment

Related Posts Plugin for WordPress, Blogger...

I Also Can Create T-Shirt Logo For You