2017-05-04 87 views
0

我通常不會在這裏提問,但我很難過。我有一個Java應用程序中的JLabel,它的長度很長。無論我嘗試什麼,Java都不會將這些文本包裝到下一行。我已經完成了研究,每個人都會告訴我在它周圍放置HTML標籤,但是當我嘗試使用我的整個GUI時停止工作。這是一個學校項目!所有的幫助非常感謝!如何在多行中跨越JLabel?

下面是一些代碼:(這是由主法暗示的類文件)

import javax.swing.*; 
import java.awt.event.*;//needed for button listeners 
import java.awt.*;//Layout class 

public class gui extends JFrame implements SwingConstants 
{ 

    //Arrays 
    public JPanel[] panels = new JPanel[6]; 
    public JPanel[] nested_panels = new JPanel[6]; 
    public JLabel[] productDescriptions = new JLabel[6]; 
    public product[] home_product_array = new product[6]; 
    public JLabel[] productTitles = new JLabel[6]; 
    public JLabel[] productPrices = new JLabel[6]; 
    public JButton[] buttons = new JButton[6]; 

    //Constants 
    final int WINDOW_WIDTH = 1000; 
    final int WINDOW_HEIGHT = 800; 

    //Main Window 
    public JFrame mainWindow; 

/*  
     Constructor 
*/ 
public gui(){ 
//main window 
JFrame mainWindow = new JFrame("Clothes 4 Sale"); 
//set layout 
mainWindow.setLayout(new GridLayout(2,3)); 
//title of window 
mainWindow.setTitle("Clothes 4 Sale"); 
//size of window 
mainWindow.setSize(WINDOW_WIDTH,WINDOW_HEIGHT); 
//Close Button 
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
//inititate window 
mainWindow.setVisible(true); 

//pull first title 
productList product_list = new productList(); 
home_product_array = product_list.get_product_array(); 



for(int i=0;i<6;i++){ 
//print whole array 
System.out.println(home_product_array[i].get_product_title()); 
System.out.println(home_product_array[i].get_product_description()); 
System.out.println(home_product_array[i].get_product_price_string()); 
// 

productTitles[i] = new JLabel(home_product_array[i].get_product_title()); 
productDescriptions[i] = new 
JLabel(home_product_array[i].get_product_description()); 
productPrices[i] = new 
JLabel(home_product_array[i].get_product_price_string()); 
productPrices[i].setForeground(Color.GREEN); 
panels[i] = new JPanel(); 
panels[i].setLayout(new BorderLayout(5,10)); 
panels[i].add(productTitles[i], BorderLayout.NORTH); 
panels[i].add(productDescriptions[i], BorderLayout.CENTER); 
nested_panels[i] = new JPanel(); 
nested_panels[i].add(productPrices[i]); 
buttons[i] = new JButton("Add To Cart"); 
nested_panels[i].add(buttons[i]); 
panels[i].add(nested_panels[i], BorderLayout.SOUTH); 
mainWindow.add(panels[i]); 
}//for loop 
/* 


*/ 

    }//End of constructor 



    }//end of class file 
+0

爲什麼不使用jtextarea? – yelliver

+0

@yelliver也可以適合賬單,但也有一些工作:使其不可編輯,設置透明背景,刪除邊框... –

+0

因此,根據需要,'JTextArea'可能更適合。無論如何,你的意思*完全由「整個GUI停止工作」? –

回答

0

有跡象表明,支持多標籤庫,但對於一個學校的項目,你或許應該確使用HTML。

您可以使用這樣的事情,這將包裹文字和尊重換行符(原始文本換行字符):

/*...*/ new JLabel(asHtml(someMultilineTextString)); 
/*...*/ 
private String asHtml(String text) { 
    return "<HTML>" + text.replace("\n", "<br>") + "</HTML>"; 
} 

編輯:再次,這是一所學校的項目。對於一個真實世界的程序,你會使用一個庫,或者至少逃過換行符(還有一個庫)。