滚动条不会出现在具有巨大图像大小的JLabel中。

时间:2014-05-10 18:56:09

标签: java swing jscrollpane jlabel

我使用Jlabel来显示图像,但我现在有滚动条的问题。滚动条不会出现。我来看看我的代码:

   public AVFrame(String title, ArrayList<String> imageList) throws HeadlessException {
    super(title);
    this.imageList = imageList;

    AddRootPanel(imageList);

    //Config frame
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setSize(FRAME_WIDTH, FRAME_HEIGHT);
    addWindowListener(new WindowAdapter() {
        /**
         * Invoked when a window is in the process of being closed.
         * The close operation can be overridden at this point.
         */
        @Override
        public void windowClosing(WindowEvent e) {
            rp.stopListening();
            System.exit(0);
        }
    });

    //pack();
    //setResizable(false);
    setLocationRelativeTo(null); // center the window
    setVisible(true);
}

/**
 * Method add root panel into frame
 */
private void AddRootPanel(ArrayList<String> imageList) {
    rp = new RootPanel(imageList);
    Container container = getContentPane();
    container.add(rp);
}
    **
 * Creates a new <code>JPanel</code> with a double buffer
 * and a flow layout.
 */
public RootPanel(ArrayList imageList) {

    this.imageList = imageList;
    listener = new AVListener(this);
    controller = new Controller();
    controller.addListener(listener);

    addImageLabel();
    showImage((File) this.imageList.get(0));
}

private void addImageLabel() {
    imgLabel = new JLabel();
    JScrollPane scrollPane = new JScrollPane(imgLabel);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    add(scrollPane);
}

public  void showImage(File imagePath) {
    try {
        bufferedImage = ImageIO.read(imagePath);
    } catch (IOException e) {
        e.printStackTrace();
    }
    ImageIcon icon = new ImageIcon(bufferedImage);
    imgLabel.setIcon(icon);

如果有人需要我的代码,请参阅:https://github.com/VitaliyPetrov/AIR_WORK/tree/master/Air%20Viewer

P.S。我的全球想法是创建应用程序,可以调整大小,旋转图像。如果有人,请提出建议或提示如何改进我的代码。我会感恩的。

1 个答案:

答案 0 :(得分:1)

JScrollPane直接添加到JFrame's Content Pane,而不是先将JScrollPane添加到JPanel

以这种方式行事

private void AddRootPanel(ArrayList<String> imageList) {
   rp = new RootPanel(imageList);
   Container container = getContentPane();
   container.add(rp.getScrollpane());
}

// Not require to extend JPanel for RootPanel class if it contains only single component
class RootPanel{
    private JScrollPane scrollpane;
    ...
    private void addImageLabel() {
        imgLabel = new JLabel();
        scrollPane= new JScrollPane(imgLabel);
        ...
    }
    public JScrollPane  getScrollpane(){
        return scrollPane;
    }
}