Java swing scroll jpanel

Java Swing How to — Create JPanel implements Scrollable

We would like to know how to create JPanel implements Scrollable.

Answer

import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Rectangle; //from w w w . jav a 2s .c o m import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.Scrollable; public class Main < public static void main(String args[]) < JPanel container = new ScrollablePanel(); container.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0)); for (int i = 0; i < 20; ++i) < JPanel p = new JPanel(); p.setPreferredSize(new Dimension(50, 50)); p.add(new JLabel("" + i)); container.add(p); > JScrollPane scroll = new JScrollPane(container); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(scroll); f.pack(); f.setSize(250, 300); f.setVisible(true); > > class ScrollablePanel extends JPanel implements Scrollable < public Dimension getPreferredSize() < return getPreferredScrollableViewportSize(); > public Dimension getPreferredScrollableViewportSize() < if (getParent() == null) return getSize(); Dimension d = getParent().getSize(); int c = (int) Math .floor((d.width - getInsets().left - getInsets().right) / 50.0); if (c == 0) return d; int r = 20 / c; if (r * c < 20) ++r; return new Dimension(c * 50, r * 50); > public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) < return 50; > public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) < return 10; > public boolean getScrollableTracksViewportHeight() < return false; > public boolean getScrollableTracksViewportWidth() < return getParent() != null ? getParent().getSize().width > getPreferredSize().width : true; > >

java2s.com | © Demo Source and Support. All rights reserved.

Источник

Добавить прокрутку для JPanel

Можно ли добавить JPanel на JTabbedPanel?
В данный момент у меня получается так что она смешает таблицу в сторону, а я хочу сделать так чтоб.

Не могу добавить обьект в JPanel
JPanel(Container).addImpl(Component, Object, int) line: not available — выбивает такое.

Добавить кусок собственного сайта на JPanel
Кусок сайта, который нужно добавить на панель, описан нужным классом в html. Нужно взять этот класс.

Как добавить JPanel к JFrame и рисовать на нем
ПРивет всем, я нашел в интернете кучу вариантов того как можно это сделать. Но дело в том что.

windows.getContentPane().add(spane);

нет это не поможет, разобрался, стоило заменить в панели setBounds на setPreferredSize(new Dimension()) и все заработало как нужно )

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
package base; import java.awt.Color; import java.awt.Dimension; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.ScrollPaneConstants; import javax.swing.JScrollPane; public class CSVmake { public JFrame window = new JFrame(); public CSVmake() { makeWindow(); makeJPanel(); makeFonWindow(); } private void makeWindow() { window.setSize(800, 600); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.getContentPane().setBackground(Color.black); window.setTitle("CSV"); window.setLayout(null); window.setResizable(false); window.setLocationRelativeTo(null); window.setVisible(true); } private void makeFonWindow() { JLabel fon0 = new JLabel(); fon0.setBounds(0, 0, 800, 600); fon0.setIcon(new ImageIcon(getClass().getResource("/res/fon0.jpg"))); fon0.setLayout(null); window.add(fon0); window.repaint(); } private void makeJPanel() { int b = 15; JPanel jp = new JPanel(); jp.setPreferredSize(new Dimension(500,5+47*b)); jp.setOpaque(false); jp.setLayout(null); //JScrollPane spane = new JScrollPane(scrol); JScrollPane spane = new JScrollPane(); spane.setBounds(15,15,650,500); spane.setOpaque(false); spane.getViewport().setOpaque(false); spane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); spane.setViewportView(jp); for (int i = 0; i  b; i++) { JButton menyBt = new JButton(); menyBt.setBounds(5, 5+i*47, 520, 42); menyBt.setName(i+""); menyBt.setText("Helloy"); menyBt.setForeground(Color.WHITE); menyBt.setOpaque(false); menyBt.setContentAreaFilled(false); menyBt.setBorderPainted(true); menyBt.setFocusPainted(false); menyBt.setLayout(null); jp.add(menyBt); } window.add(spane); window.repaint(); } public static void main(String[] args) { new CSVmake(); } }

Источник

Java Swing How to — Create JPanel implements Scrollable

We would like to know how to create JPanel implements Scrollable.

Answer

import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Rectangle; //from w w w.j av a2 s.c o m import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.Scrollable; public class Main < public static void main(String args[]) < JPanel container = new ScrollablePanel(); container.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0)); for (int i = 0; i < 20; ++i) < JPanel p = new JPanel(); p.setPreferredSize(new Dimension(50, 50)); p.add(new JLabel("" + i)); container.add(p); > JScrollPane scroll = new JScrollPane(container); scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(scroll); f.pack(); f.setSize(250, 300); f.setVisible(true); > > class ScrollablePanel extends JPanel implements Scrollable < public Dimension getPreferredSize() < return getPreferredScrollableViewportSize(); > public Dimension getPreferredScrollableViewportSize() < if (getParent() == null) return getSize(); Dimension d = getParent().getSize(); int c = (int) Math .floor((d.width - getInsets().left - getInsets().right) / 50.0); if (c == 0) return d; int r = 20 / c; if (r * c < 20) ++r; return new Dimension(c * 50, r * 50); > public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) < return 50; > public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) < return 10; > public boolean getScrollableTracksViewportHeight() < return false; > public boolean getScrollableTracksViewportWidth() < return getParent() != null ? getParent().getSize().width > getPreferredSize().width : true; > >

java2s.com | © Demo Source and Support. All rights reserved.

Источник

JScrollPane in Java

jscrollpane in java

JScrollPane is used to give a scrollable view to your component. When the screen size is small or limited, we can use a scroll pane to showcase a large component or a component whose size changes dynamically. The components like image, table, text, textarea, etc., should be lightweight. JScrollPane component should be inside the container like JFrame or JPanel. It is an important component in Graphic programming, especially your need to handle and display large data. In this topic, we are going to learn about JScrollPane in Java. When we have a limited screen size, then we need to use a scroll pane for the following two conditions:

JScrollPane class is a combination of viewports and scrollbars. It will connect our viewport with the scrollbar. We can control our scrollbar’s appearances using scrollbar display policy properties: verticalScrollbarPolicy and horizontalScrollbarPolicy.

Both these properties can have values AS_NEEDED, ALWAYS, or NEVER. It also has two additional viewports:

  1. rowHeading – Used to scroll horizontally
  2. columnHeading – Used to scroll vertically

JScrollPane in Java

Constructors

The Sole purpose of the constructor of this class is to create a scroll pane. The input values undermine the dimensions of it these constructors, i.e., parameters. Constructors of JscrollPane class are of two types Parameterized and Non-Parameterized; they are further classified as below:

1. JScrollPane( )

Creates an empty scroll pane (no viewPort). It can have both vertical and horizontal scrollbars when needed.

import java.awt.*; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Jscrollpane < public static void main(String[] args) < JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JScrollPane scrollPane = new JScrollPane(); panel.add(scrollPane); frame.setContentPane(panel); frame.setSize(500, 500); frame.setLocationByPlatform(true); frame.setVisible(true); >>

JScrollPane in Java OUTPUT 1

2. JscrollPane (Component c)

Creates a scroll pane with the specified component. When the component content exceeds the view, horizontal and vertical scrollbars appear.

import java.awt.*; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Jscrollpane < public static void main(String[] args) < JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JTextArea tArea = new JTextArea(10,10); JScrollPane scrollPane = new JScrollPane(tArea); panel.add(scrollPane); frame.setContentPane(panel); frame.setSize(500, 500); frame.setLocationByPlatform(true); frame.setVisible(true); >>

JScrollPane in Java OUTPUT 2

3. JScrollPane(int vsPolicy, int hsPolicy)

Creates a scroll pane with the specified scroll policies.

import java.awt.*; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Jscrollpane < public static void main(String[] args) < JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JScrollPane scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); panel.add(scrollPane); frame.setContentPane(panel); frame.setSize(500, 500); frame.setLocationByPlatform(true); frame.setVisible(true); >>

JScrollPane in Java OUTPUT 3

4. JScrollPane(Component c, int vsPolicy, int hsPolicy)

Creates a scroll pane with the specified component. The component position is controlled with a pair of scrollbars.

import java.awt.*; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Jscrollpane < public static void main(String[] args) < JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JTextArea tArea = new JTextArea(10,10); JScrollPane scrollPane = new JScrollPane(tArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); panel.add(scrollPane); frame.setContentPane(panel); frame.setSize(500, 500); frame.setLocationByPlatform(true); frame.setVisible(true); >>

specified component

Methods in JscrollPane Class

Below are the methods in JscrollPane Class.

  1. setColumnHeaderView(Component) – It sets the column header for the scroll pane of the specified component in the parameters.
  2. setRowHeaderView(Component) – It sets the row header for the scroll pane of the specified component in the parameters.
  3. setCorner(String key, Component) – It sets the corner for the scroll pane for the specified component in the parameter. The string key parameter is along with the following:
    JScrollPane.UPPER_LEFT_CORNER, JScrollPane.UPPER_RIGHT_CORNER, JScrollPane.LOWER_LEFT_CORNER, JScrollPane.LOWER_RIGHT_CORNER, JScrollPane.LOWER_LEADING_CORNER, JScrollPane.LOWER_TRAILING_CORNER, JScrollPane.UPPER_LEADING_CORNER, JScrollPane.UPPER_TRAILING_CORNER
  4. getCorner(Component) – It gets the corner for the scroll pane for the specified component in the parameter.

Examples of JScrollPane in Java

Here are some of the Examples given below.

1. Example Program for JscrollPane

import java.awt.*; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Jscrollpane < public static void main(String[] args) < JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JTextArea tArea = new JTextArea(20,20); JLabel labelColumn = new JLabel("Column Header"); JLabel labelRow = new JLabel("Row Header"); JLabel label1 = new JLabel("UL"); JLabel label2 = new JLabel("UR"); JLabel label3 = new JLabel("LL"); JLabel label4 = new JLabel("LR"); JScrollPane scrollPane = new JScrollPane(tArea); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setColumnHeaderView(labelColumn); scrollPane.setRowHeaderView(labelRow); scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER ,label1); scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER ,label2); scrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER ,label3); scrollPane.setCorner(JScrollPane.LOWER_RIGHT_CORNER ,label4); panel.add(scrollPane); frame.setContentPane(panel); frame.setSize(500, 500); frame.setLocationByPlatform(true); frame.setVisible(true); >>

Column & Row Header

2. Example of JTable with JScrollPane

import javax.swing.*; import java.awt.*; import javax.swing.table.TableModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.DefaultTableCellRenderer; public class JScrollDemo < public static void main(String[] args) < < String[] index = new String[] < "S.No", "Continent", "Area (square.km)", "Percentage Total Mass" >; JFrame frame = new JFrame("JScrollPane with JTable"); JLabel label = new JLabel("Continents Largest To Smallest", JLabel.CENTER); Object[][] data = new Object[][] < < "S.No", "Continent", "Area (square.km)", "Percentage Total Mass" >< "1", "Asia", "44,579,000", "29.5%" >, < "2", "Africa", "30,370,000", "20.4%" >, < "3", "North America", "24,709,000", "16.5%" >, < "4", "South America", "17,840,000", "12.0%" >, < "5", "Antartica", "14,000,000", "9.2%" >, < "6", "Europe", "10,180,000", "6.8%" >, < "7", "Australia", "8,600,000", "5.9%" >, >; // creating a DeFaultTableModel object, which is subclass of // TableModel DefaultTableModel TableModel = new DefaultTableModel(data, index); // Initializing a JTable from DefaultTableModel. JTable table = new JTable(TableModel); // Adjusting the contents of each cell of JTable in CENTER DefaultTableCellRenderer tableCellRenderer = new DefaultTableCellRenderer(); // Aligning the table data centrally. tableCellRenderer.setHorizontalAlignment(JLabel.CENTER); table.setDefaultRenderer(Object.class, tableCellRenderer); // Creating a JPanel, setting it layout to BorderLayout and adding // JTable to it. JPanel panel = new JPanel(new BorderLayout()); panel.add(table, BorderLayout.CENTER); // Creating a JScrollPane and adding its functionalities to JPanel JScrollPane scrollPane = new JScrollPane(panel); // Adding a JLabel and JScrollPane to JFrame. frame.add(label, BorderLayout.NORTH); frame.add(scrollPane, BorderLayout.CENTER); frame.setSize(320, 200); frame.setVisible(true); > > >

JTable

Conclusion

When screen size is limited, we need to use a scroll pane to display large components or components whose size can change dynamically.

We hope that this EDUCBA information on “JScrollPane in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8

Источник

Читайте также:  Как настроить интерпретатор питон
Оцените статью