2011-04-27 33 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); 

    } 
} 
相關問題