I'm having trouble getting JScrollPanes to actually display scroll bars

前端 未结 3 1552
小鲜肉
小鲜肉 2021-01-20 17:20

I\'ve found some examples scattered around the internet involving getting an image or a textbox to display scroll bars, but they all involve a program that basically display

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-20 18:03

    Better that you should use layout managers to your advantage and to let these managers do the heavy lifting of calculating component sizes and placements for you. For example:

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    
    import javax.swing.*;
    
    public class ScrollDemo2 extends JPanel {
       public static final Color[] COLORS = {Color.green, Color.red, Color.blue};
       private static final Dimension PANEL_SIZE = new Dimension(300, 300);
       public ScrollDemo2() {
          JPanel innerPanel = new JPanel(new GridLayout(0, 1));
          for (int i = 0; i < COLORS.length; i++) {
             JPanel colorPanel = new JPanel();
             colorPanel.setPreferredSize(PANEL_SIZE);
             colorPanel.setBackground(COLORS[i]);
             innerPanel.add(colorPanel);
          }
          JScrollPane scrollPane = new JScrollPane(innerPanel);
          scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
          scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          scrollPane.getViewport().setPreferredSize(PANEL_SIZE);
    
          int eb = 10;
          setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
          setLayout(new BorderLayout());
          add(scrollPane, BorderLayout.CENTER);
       }
    
       private static void createAndShowGui() {
          ScrollDemo2 mainPanel = new ScrollDemo2();
    
          JFrame frame = new JFrame("ScrollDemo2");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(mainPanel);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    

提交回复
热议问题