2017-05-04 302 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

謝謝!這解決了它! –