许多Swing组件在其GUI中显示文本字符串。默认情况下,组件的文本以一种字体和颜色显示,并且全部显示在一行上。 可以分别通过调用组件的setFont和setForeground方法来确定组件文本的字体和颜色。例如,以下代码创建一个标签,然后设置其字体和颜色:
label = new JLabel("A label");
label.setFont(new Font("Serif", Font.PLAIN, 14));
label.setForeground(new Color(0xffffdd));
如果要在文本中混合字体或颜色,或者要设置格式(例如多行),则可以使用HTML。 HTML格式可以在所有Swing按钮,菜单项,标签,工具提示和选项卡式窗格以及使用标签来呈现文本的树和表等组件中使用。
要指定组件的文本具有HTML格式,只需将html标记放在文本的开头,然后在其余部分使用任何有效的HTML。这是在按钮的文本中使用HTML的示例:
button = new JButton("Two
lines");
这是结果按钮。
名为HtmlDemo的应用程序允许您通过在标签上设置文本来使用HTML格式播放。您可以在HtmlDemo.java中找到此程序的完整代码。这是HtmlDemo示例的图片。
package components;
/* HtmlDemo.java needs no other files. */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HtmlDemo extends JPanel
implements ActionListener {
JLabel theLabel;
JTextArea htmlTextArea;
public HtmlDemo() {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
String initialText = "\n" +
"Color and font test:\n" +
"\n" +
"red\n" +
"blue\n" +
"green\n" +
"small\n" +
"large\n" +
"italic\n" +
"bold\n" +
"\n";
htmlTextArea = new JTextArea(10, 20);
htmlTextArea.setText(initialText);
JScrollPane scrollPane = new JScrollPane(htmlTextArea);
JButton changeTheLabel = new JButton("Change the label");
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(
"Edit the HTML, then click the button"),
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("A label with 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);
}
//React to the user pushing the Change button.
public void actionPerformed(ActionEvent e) {
theLabel.setText(htmlTextArea.getText());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("HtmlDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new HtmlDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
尝试这个: 单击启动按钮以使用Java™Web Start运行HtmlDemo(下载JDK 7或更高版本)。或者,要自己编译并运行示例,请查阅示例索引。 在左侧的文本区域中编辑HTML格式,然后单击“更改标签”按钮。右边的标签显示结果。 从左侧的文本区域中删除html标签。标签的文本不再解析为HTML。
让我们看看另一个使用HTML的示例。 ButtonHtmlDemo将字体,颜色和其他文本格式添加到三个按钮。您可以在ButtonHtmlDemo.java中找到此程序的完整代码。这是ButtonHtmlDemo示例的图片。
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
/*
* ButtonHtmlDemo.java uses the following files:
* images/right.gif
* images/middle.gif
* images/left.gif
*/
public class ButtonHtmlDemo extends JPanel
implements ActionListener {
protected JButton b1, b2, b3;
public ButtonHtmlDemo() {
ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");
ImageIcon rightButtonIcon = createImageIcon("images/left.gif");
b1 = new JButton("Disable
"
+ "middle button",
leftButtonIcon);
Font font = b1.getFont().deriveFont(Font.PLAIN);
b1.setFont(font);
b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand("disable");
b2 = new JButton("middle button", middleButtonIcon);
b2.setFont(font);
b2.setForeground(new Color(0xffffdd));
b2.setVerticalTextPosition(AbstractButton.BOTTOM);
b2.setHorizontalTextPosition(AbstractButton.CENTER);
b2.setMnemonic(KeyEvent.VK_M);
b3 = new JButton("Enable
"
+ "middle button",
rightButtonIcon);
b3.setFont(font);
//Use the default text position of CENTER, TRAILING (RIGHT).
b3.setMnemonic(KeyEvent.VK_E);
b3.setActionCommand("enable");
b3.setEnabled(false);
//Listen for actions on buttons 1 and 3.
b1.addActionListener(this);
b3.addActionListener(this);
b1.setToolTipText("Click this button to disable the middle button.");
b2.setToolTipText("This middle button does nothing when you click it.");
b3.setToolTipText("Click this button to enable the middle button.");
//Add Components to this container, using the default FlowLayout.
add(b1);
add(b2);
add(b3);
}
public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
} else {
b2.setEnabled(true);
b1.setEnabled(true);
b3.setEnabled(false);
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = ButtonHtmlDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ButtonHtmlDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new ButtonHtmlDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
单击启动按钮,以使用Java™Web Start(下载JDK 7或更高版本)运行ButtonHtmlDemo。或者,要自己编译并运行示例,请查阅示例索引。
左右按钮具有多行和文本样式,并使用HTML来实现。另一方面,中间按钮仅使用一行,字体和颜色,因此不需要HTML。这是指定这三个按钮的文本格式的代码:
b1 = new JButton("Disable
"
+ "middle button",
leftButtonIcon);
Font font = b1.getFont().deriveFont(Font.PLAIN);
b1.setFont(font);
...
b2 = new JButton("middle button", middleButtonIcon);
b2.setFont(font);
b2.setForeground(new Color(0xffffdd));
...
b3 = new JButton("Enable
"
+ "middle button",
rightButtonIcon);
b3.setFont(font);
请注意,我们必须使用u标记使使用HTML的按钮中的助记符“ D”和“ E”加下划线。还请注意,当禁用按钮时,不幸的是,其HTML文本将保持黑色,而不是变为灰色。 (请参阅错误#4783068,以查看这种情况是否发生了变化。)
本节讨论了如何在普通的非文本组件中使用HTML。有关主要目的是格式化文本的组件的信息,请参阅使用文本组件。
如果您使用JavaFX编程,请参见HTML编辑器。