How to display a large component within a smaller display area in Java?


To display a large component in a smaller display area, use JScrollPane, so that it’s easier for user to scroll through the component. The following is an example to display large component within a smaller display area in Java −

Example

package my;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JButton button1 = new JButton("One");
      JButton button2 = new JButton("Two");
      JButton button3 = new JButton("Three");
      JButton button4 = new JButton("Four");
      JButton button5 = new JButton("Five");
      JButton button6 = new JButton("Six");
      Box box = Box.createVerticalBox();
      box.add(button1);
      box.add(button2);
      box.add(button3);
      box.add(button4);
      box.add(button5);
      box.add(button6);
      box.setPreferredSize(new Dimension(900,900));
      JScrollPane jScrollPane = new JScrollPane();
      jScrollPane.setViewportView(box);
      frame.add(jScrollPane, BorderLayout.CENTER);
      frame.setSize(550, 250);
      frame.setVisible(true);
   }
}

This will produce the following output −

Updated on: 30-Jul-2019

61 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements