项目未出现在Java的新框架中

时间:2011-04-27 19:41:04

标签: java swing

我正在构建一个JFrame,它最终会显示一个程序的输出,该程序中包含可变数量的部分。我已解析输出但在框架中显示它是一个问题。

当框架出现时,除滚动窗格外,它完全为空。如何显示这些标签?

public class OutputPanel extends JFrame {

    public OutputPanel(Vector parsedOutput) {

    this.setTitle("Output");
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    JScrollPane scrollPane = new JScrollPane();

    Iterator<Vector> outputIter = parsedOutput.iterator();

    while(outputIter.hasNext()) {
        Vector section = outputIter.next();

        JLabel sectionLabel = new JLabel((String)section.get(0));
        System.out.println((String)section.get(0));
        scrollPane.add(sectionLabel);

    }
    this.add(scrollPane);
    this.pack();
    this.setVisible(true);

    }
}

2 个答案:

答案 0 :(得分:2)

您不应将组件添加到scrollPane

scrollPane.add(sectionLabel);

而是将它们添加到单独的面板中,并使用

scrollPane = new JScrollPane(thePanel);

scrollPane.setViewportView(thePanel);

示例:

import java.awt.GridLayout;
import java.util.Vector;

import javax.swing.*;

class Test {
    public static void main(String[] args) {
        new OutputPanel(null);
    }
}

class OutputPanel extends JFrame {

    public OutputPanel(Vector parsedOutput) {

        this.setTitle("Output");
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel content = new JPanel(new GridLayout(0, 1));

        for (int i = 0; i < 100; i++) {    
            JLabel sectionLabel = new JLabel("hello " + i);
            content.add(sectionLabel);
        }
        JScrollPane scrollPane = new JScrollPane(content);

        this.add(scrollPane);
        this.pack();
        this.setVisible(true);

    }
}

<强>产地:

enter image description here

答案 1 :(得分:2)

您应该将setViewPortView()与容器一起使用,而不是对JScrollPane使用add()。

试试这个。

public class OutputPanel extends JFrame {

    public OutputPanel(Vector parsedOutput) {

    this.setTitle("Output");
    this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    JScrollPane scrollPane = new JScrollPane();

    Iterator<Vector> outputIter = parsedOutput.iterator();
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    scrollPane.setViewportView(panel);
    while(outputIter.hasNext()) {

        Vector section = outputIter.next();

        JLabel sectionLabel = new JLabel((String)section.get(0));
        System.out.println((String)section.get(0));
        panel.add(sectionLabel);

    }
    this.add(scrollPane);
    this.pack();
    this.setVisible(true);

    }
}