2017-05-04 44 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>"; 
} 

编辑:再次,这是一所学校的项目。对于一个真实世界的程序,你会使用一个库,或者至少逃过换行符(还有一个库)。