简体   繁体   中英

JAVA JScrollPane not showing up

I have a JPanel with scrollbar and i want to add a lot of JLabels to it. But the scrollbar doesnt work . I can not use the scrollbar and even after the panel is full it doesn't scroll . Here is my code :

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;


public class Scroll {
public static void main(String[] args) {
    JPanel panel = new JPanel(new GridLayout(0,1));
    JPanel p = new JPanel(new BorderLayout());
    JScrollPane scroll = new JScrollPane(panel);
    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    p.add(scroll, BorderLayout.NORTH);
    JButton but = new JButton("OK");
    p.add(but, BorderLayout.SOUTH);
    but.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            panel.add(new JLabel("Some random text"));
            scroll.revalidate();
            p.repaint();p.revalidate();
        }
    });
    JFrame frame = new JFrame();
    frame.setSize(800,200);
    frame.setVisible(true);
    frame.add(p);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
}
}

Your problem seems to lie with your layout managers. I think BorderLayout behaves strangely when you don't use the BorderLayout.CENTER position. I changed the line

p.add(scroll, BorderLayout.NORTH);

to

p.add(scroll, BorderLayout.CENTER);

Then, to make the text appear from the top instead of centering, I changed the layout manager for the panel component to a BoxLayout. From:

JPanel panel = new JPanel(new GridLayout(0, 1));

to

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

This seems to have given me the functionality you want. Let me know if this fixes your issues or not!

As already suggested, you should probably use JList or JTable to implement your use case.

Regarding the issue, this is because all BorderLayout constraints except of CENTER will expand to as much space as their components occupy, even if that means that they will expand out of the screen bounds (in your case the NORTH section expands to the south after each button click).

To solve this, explicitly specify the preferred size for the components which can grow indefinitely if you add them to a non-central panel section with BorderLayout :

scroll.setPreferredSize(new Dimension(-1, 100));

I use -1 for the width here to indicate that it is not important (I could use any other value), since it will be ignored by the layout manager anyway (with BorderLayout.NORTH the component is stretched horizontally to take all the available horizontal space).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM