JFrame滚动条和画布

时间:2015-04-27 12:12:59

标签: java canvas jframe scrollbar

我在尝试将水平滚动条添加到具有画布的JFrame时遇到了麻烦。我在画布上绘制图像,有时这些图像会覆盖屏幕,所以我想要一个滚动条让用户看到它们。

以下是代码中的关键部分,如果需要任何其他代码,请告诉我,我将进行编辑。

有谁可以指出我做错了什么?

非常感谢J

public class TheFrame extends JFrame {

private static ThePanel canvas;
private String deckImagesToUse;

/**
 * The constructor creates a Frame ready to display the cards
 */
public TheFrame(String cardImgFile) {


    // Calls the constructor in the JFrame superclass passing up the name to 
    // display in the title
    super("Window title");

    //Using users choice of cards
    deckImagesToUse = cardImgFile;

    // When you click on the close window button the window will be closed
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // This has North, East, South, West and center positions for components
    setLayout(new BorderLayout());

    // This is what we will draw on (see the inner class below)
    canvas = new ThePanel();
    setSize(700, 300);
    this.add(canvas, BorderLayout.CENTER);

    //Scroll Bar
    JScrollPane scrollPane = new JScrollPane(canvas);
    //scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    this.getContentPane().add(scrollPane);
    int desiredWidth = (Pack.cardsInPlay.size() * 70);
    Dimension d = new Dimension(desiredWidth,300);
    canvas.setPreferredSize(d);

    setVisible(true); // Display the window


}

1 个答案:

答案 0 :(得分:1)

canvas = new ThePanel();
setSize(700, 300);
this.add(canvas, BorderLayout.CENTER);

设置大小并添加到this是徒劳的,因为后来的scrollpane会忽略它。

当您的图片大于JScrollPane时,只需致电canvas.setPreferredSize(imageWidth, imageHeight);