import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* <p>Title: 在swing中使用html語言</p>
* <p>Description: 這裡演示使用html語言在swing面板上構造顯示信息</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: HtmlDemo.java</p>
* @version 1.0
*/
public class HtmlDemo extends JPanel
implements ActionListener {
JLabel theLabel;
JTextArea htmlTextArea;
/**
*<br>方法說明:構造器,描述窗體中的成員
*<br>輸入參數:
*<br>返回類型:
*/
public HtmlDemo() {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
String initialText = "<html>\n" +
"顏色和字體測試:\n" +
"<ul>\n" +
"<li><font color=red>red</font>\n" +
"<li><font color=blue>blue</font>\n" +
"<li><font color=green>green</font>\n" +
"<li><font size=-2>small</font>\n" +
"<li><font size=+2>large</font>\n" +
"<li><i>italic</i>\n" +
"<li><b>bold</b>\n" +
"</ul>\n";
//定義一個文本框
htmlTextArea = new JTextArea(10, 20);
htmlTextArea.setText(initialText);
JScrollPane scrollPane = new JScrollPane(htmlTextArea);
//定義按鈕
JButton changeTheLabel = new JButton("改變顯示");
changeTheLabel.setMnemonic(KeyEvent.VK_C);
changeTheLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
changeTheLabel.addActionListener(this);
//定義標簽
theLabel = new JLabel(initialText) {
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public Dimension getMinimumSize() {
return new Dimension(200, 200);
}
public Dimension getMaximumSize() {
return new Dimension(200, 200);
}
};
//設置標簽的對齊方式
theLabel.setVerticalAlignment(SwingConstants.CENTER);
theLabel.setHorizontalAlignment(SwingConstants.CENTER);
//構造一個帶邊框的左邊的編輯面板
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
leftPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder(
"編輯HTML,點擊按鈕顯示結果。"),
BorderFactory.createEmptyBorder(10,10,10,10)));
leftPanel.add(scrollPane);
leftPanel.add(Box.createRigidArea(new Dimension(0,10)));
leftPanel.add(changeTheLabel);
//構造一個帶邊框的右邊顯示的面板
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
rightPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("這裡使用標簽顯示HTML結果"),
BorderFactory.createEmptyBorder(10,10,10,10)));
rightPanel.add(theLabel);
setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
add(leftPanel);
add(Box.createRigidArea(new Dimension(10,0)));
add(rightPanel);
}
/**
*<br>方法說明:事件監聽,當用戶點擊按鈕觸發
*<br>輸入參數:
*<br>返回類型:
*/
public void actionPerformed(ActionEvent e) {
theLabel.setText(htmlTextArea.getText());
}
/**
*<br>方法說明:主方法
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
//創建窗體
JFrame frame = new JFrame("HtmlDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//創建面板
JComponent newContentPane = new HtmlDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
//顯示窗體
frame.pack();
frame.setVisible(true);
}
}