JScrollPane没有显示滚动条

时间:2012-02-23 21:33:07

标签: java swing jpanel jscrollpane layout-manager

我有一个带有自定义LayoutManager的JPanel并尝试将其放入JScrollPane中,但是,滚动窗格似乎不知道它应该启用滚动。无论我如何设置组件的首选大小(这就是JScrollPane所说的javadoc所说的),它绝对没有区别。这是代码:

    canvas = new JPanel();
    JScrollPane scroll = new JScrollPane();
    scroll.setViewportView(canvas);
    scroll.setPreferredSize(new Dimension(924,700));
    canvas.setPreferredSize(new Dimension(2000,2000));

滚动条不会出现。 JScrollPane的容器设置为遵循其首选大小。我已经通过调试器检查了画布的首选大小确实是2000 x 2000(LayoutManager确保这一点),那么可能会发生什么呢?

1 个答案:

答案 0 :(得分:5)

这不是一个真正的答案,但它是一个演示sscce,再次表明您的代码对我来说很好:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;

import javax.swing.*;

public class ScrollBarEg {
   protected static final Paint GRADIENT_PAINT = new GradientPaint(0, 0,
         Color.blue, 50, 50, Color.red, true);

   private static void createAndShowGui() {
      JPanel mainPanel = new JPanel();

      JPanel canvas = new JPanel() {
         @Override
         protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                  RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(GRADIENT_PAINT);
            g2.fillOval(0, 0, getWidth(), getHeight());
            g2.dispose();
         }
      };
      JScrollPane scroll = new JScrollPane();
      scroll.setViewportView(canvas);
      scroll.setPreferredSize(new Dimension(924, 700));
      canvas.setPreferredSize(new Dimension(2000, 2000));

      mainPanel.add(scroll);

      JFrame frame = new JFrame("ScrollBar Eg");
      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();
         }
      });
   }
}

这告诉我,您的错误位于您尚未发布的代码中的其他位置。