有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JScrollPane现在显示其视口

我正在用JavaSwing制作一个应用程序,我遇到了一个问题。我制作了一个选项卡式面板,它需要容纳一个简单的面板和一个滚动面板。简单面板工作正常,但在我的滚动面板中,我只能看到滚动条,而不能看到视口,我的代码如下:

内容窗格

public class ContentPane extends JTabbedPane {
    private InfoPanel ip;
    ScrollPanel sp;

    public InfoPanel getIp() {
        return ip;
    }

    public ContentPane(GraphPanel gp) {
        this.sp = new ScrollPanel(gp);
        this.sp.setViewportView(gp);

        this.addTab("Graph", this.sp);
        this.ip = new InfoPanel(gp);
        this.addTab("Info", ip);
    }
}

滚动面板

public class ScrollPanel extends JScrollPane {
    public ScrollPanel(GraphPanel gp){
        this.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        this.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        this.repaint();
    }
}

石墨板

public GraphPanel(StatusBar sb) {
    this.sb = sb;
    zoomLevel = 5;
    sm = new Simulation();
    mh = new MouseHandler(this, sm);
    this.addMouseListener(mh);
    this.setBackground(new Color(240, 165, 98));        
    this.repaint();
}

由于我没有得到任何错误或异常,我现在完全不知道该采取哪种方法


共 (1) 个答案

  1. # 1 楼答案

    您不应该将JScrollPane子类化,这不是必需的

    但是如果这样做了,不要忘记将组件添加到滚动窗格中

    在您的子类中,您正在而不是将图形面板添加到滚动窗格中:

    public class ScrollPanel extends JScrollPane {
        public ScrollPanel(GraphPanel gp){
    
             // ::::  HERE ::: you are not doing anything with gp 
             // like this.setViewPort( gp ) or something like that
    
            this.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            this.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            this.repaint();
        }
    }
    

    试试看:

    public class ScrollPanel extends JScrollPane {
        public ScrollPanel(GraphPanel gp){
            super( gp );
            .... etc ...            
    

    并让GraphPanel扩展JComponent或JPanel