Java swing JPanel 和 JScrollPane 不显示

标签 java swing

当我运行程序时,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

该组件需要添加到JScrollPaneJViewPort

最简单的方法是使用:

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/

相关文章:

java - 在两个平面表上编写 Hibernate 或 JPA native SQL

java - SWT 方法 - 从表查看器获取值/Swing 方法 - 使用该值

java - 禁用 JTable 上的弹出菜单

java - JMenu 项目将 jgraph 导出为图像

java - 除了RTFEditorKit之外,还有什么方法可以使用java读取rtf文件?

java - 从命令行更改 Swing 字体大小

JavaFx 8 - 一个具有无法着色的边框并且能够在中间包含文本的类

java - 模板方法模式 - 命名约定

java - GL15在lwjgl里坏了

java - 使用带有 xml.xsd 导入 : "Failed to read schema document ' xml. xsd 的 XJC 时出错”