简体   繁体   中英

Java swing JPanel and JScrollPane not displaying

When I run the program, the JPanel is not visible. It works without the JScrollPane though. This is driving me crazy! Before, I had it using a Canvas and a ScrollPane. Note that FlowchartPanel extends JPanel.

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();
    }
}

Don't add components directly to a JScrollPane .

The component needs to be added to the JViewPort of the JScrollPane

The easiest way to do this is to use:

JScrollPane scrollPane = new JScrollPane( panel );

Another way is to replace (add) the component in the viewport is to use:

scrollPane.setViewportView( panel );

panel.setPreferredSize(new Dimension(canvasWidth, canvasHeight));

Don't set the preferred size of a component. Every Swing component is responsible for determining its own preferred size. Instead override the getPreferredSize() method of your custom panel to return the size. This way as the custom painting changes, you can dynamically change the preferred size as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM