当我运行程序时,JPanel 不可见。不过,它可以在没有 JScrollPane 的情况下工作。这真让我抓狂!之前,我使用 Canvas 和 ScrollPane。请注意,FlowchartPanel 扩展了 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();
}
}
最佳答案
不要将组件直接添加到 JScrollPane
。
该组件需要添加到JScrollPane
的JViewPort
最简单的方法是使用:
JScrollPane scrollPane = new JScrollPane( panel );
另一种方法是替换(添加)视口(viewport)中的组件,方法是使用:
scrollPane.setViewportView( panel );
panel.setPreferredSize(new Dimension(canvasWidth, canvasHeight));
不要设置组件的首选大小。每个 Swing 组件都有责任确定自己的首选大小。而是重写自定义面板的 getPreferredSize()
方法来返回尺寸。这样,当自定义绘画发生变化时,您可以根据需要动态更改首选尺寸。
关于Java swing JPanel 和 JScrollPane 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43794440/