2011-04-27 34 views
1

我正在构建一个JFrame,它最终将显示一个程序的输出,该程序具有可变数量的部分。我已经解析了输出,但在框架中显示它是一个问题。未在Java中的新框架中出现的项目

当框架出现时,除滚动窗格外,它完全是空的。我如何让这些标签出现?

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

    } 
} 
+0

你真的想为每行parsedOutput创建一个JLabel吗?这听起来很奇怪。为什么不简单地使用JList? – jfpoilpret 2011-04-28 13:29:40

回答

2

你不应该组件添加到滚动

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

2

你应该用一个容器代替的add()JScrollPane的中,使用setViewportView()。

试试这个。

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

    } 
} 
相关问题