Java Swing,可滚动的HBox

时间:2018-01-19 13:18:54

标签: java swing

我正在编写一个程序,我正在尝试实现可滚动的HBox。可悲的是,JSCrollPane似乎根本不起作用,当窗口太小时,图像才开始相互夹闭。

enter image description here

包含图片的窗格包含以下代码:

    public class Caller extends JPanel {

    public Caller() {
        initPanel();
    }

    private void initPanel() {
        this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    }

    public void addBall(Ball ball) {
        this.add(ball);
    }
}

主框架:

public class GUI extends JFrame {

    public GUI() throws HeadlessException {
        super();
        initMainFrame();
        initCaller();
    }

    private void initCaller() {
        Caller caller = new Caller();
        JScrollPane scrollPane = new JScrollPane(caller, JScrollPane.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

        caller.addBall(new Ball(5));
        caller.addBall(new Ball(16));
        caller.addBall(new Ball(34));
        caller.addBall(new Ball(34));
        caller.addBall(new Ball(34));

        this.add(scrollPane);
    }

    private void initMainFrame() {
        this.setTitle("Main");
        this.setSize(new Dimension(500,200));
    }
}

Ball Draw Code:

@Override
public void paint(Graphics g) {
    super.paint(g);
    g.drawImage(ballImage, 0,0, this);
    g.setFont(new Font("Arial Black", Font.BOLD, 20));
    g.setColor(Color.WHITE);
    g.drawString(designation, 20,ballImage.getHeight()/2);
}

我是否以错误的方式实现了滚动条?

1 个答案:

答案 0 :(得分:1)

您的Ball JComponent似乎缺少有关其首选/最小/最大尺寸的信息,因此Caller面板BoxLayout并不知道它们是什么,当你减小宽度时,你的组件将减小其尺寸而不是滚动窗格,反映了滚动的需要。

您必须覆盖Ball类的相关方法,例如:

@Override
public Dimension getPreferredSize() {

    return new Dimension(ballImage.width, ballImage.height);

}

@Override
public Dimension getMaximumSize() {

    return new Dimension(ballImage.width, ballImage.height);

}

@Override
public Dimension getMinimumSize() {

    return new Dimension(ballImage.width, ballImage.height);

}