2017-05-04 108 views
0

当我运行该程序时,JPanel不可见。尽管它没有JScrollPane。这真让我抓狂!之前,我使用了Canvas和ScrollPane。请注意,FlowchartPanel扩展了JPanel。Java swing JPanel和JScrollPane不显示

public class Window extends JFrame{ 

private FlowchartPanel panel;      // contains all the main graphics 
private JScrollPane scrollpane;      // contains panel 
private int canvasWidth, canvasHeight;    // the width and height of the canvas object in pixels 
private Flowchart flowchart;      // the flowchart object 

public Window(Flowchart flowchart) { 
    super(); 
    canvasWidth = 900; 
    canvasHeight = 700; 
    this.flowchart = flowchart; 
    flowchart.setWidth(canvasWidth); 
    flowchart.setHeight(canvasHeight); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    panel = new FlowchartPanel(flowchart); 
    panel.setPreferredSize(new Dimension(canvasWidth, canvasHeight)); 
    scrollpane = new JScrollPane(); 
    scrollpane.setPreferredSize(new Dimension(canvasWidth, canvasHeight)); 
    scrollpane.add(panel); 
    add(scrollpane); 
    //add(panel); 
    pack(); 
    } 
} 

回答

2

不要将组件直接添加到JScrollPane

组件需要被添加到的JScrollPane

要做到这一点,最简单的方式JViewPort是使用:

JScrollPane scrollPane = new JScrollPane(panel); 

另一种方法是在视口中更换(添加)组件是使用:

scrollPane.setViewportView(panel); 

panel.setPreferredSize(新尺寸(canvasWidt h,canvasHeight));

不要设置组件的首选大小。每个Swing组件都负责确定自己的首选大小。而是覆盖自定义面板的getPreferredSize()方法以返回大小。随着自定义绘画更改,可以根据需要动态更改首选大小。

+0

谢谢!这解决了它! –