转:HTML操作 Swing Components

One useful feature of Swing GUI’s many people overlook is the ability to use simple HTML tags within swing components. This tutorial assumes you know how to create a GUI in swing and add components. If you do not know how to do this, it is a good idea to read one of my previous tutorials.

Lets first create a basic GUI with a JButton and JLabel:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
 
public class HTMLJButton {
 
    public HTMLJButton(){
        JFrame mainFrame = new JFrame("HTML");
        mainFrame.setLayout(new java.awt.FlowLayout());
 
        JButton button1 = new JButton("JButton Text");
        JLabel label1 = new JLabel("JLabel Text");
 
        mainFrame.add(button1);
        mainFrame.add(label1);
 
        mainFrame.setDefaultCloseOperation(mainFrame.EXIT_ON_CLOSE);
        mainFrame.setVisible(true);
        mainFrame.pack();
    }
 
    public static void main(String[] args){
        new HTMLJButton();
    }
}

But what if you want the text on the button to be a different color? You can use the HTML font tags inside the JButton string parameter.

Such as:

 JLabel label1 = new JLabel("<html><font color='#FF0000'>Red Text</font>" +  "<br /><font color='#00FF00'>Blue Text</font></html>");

Not only can you modify fonts, you can also insert images:

 JLabel label1=new JLabel("<html><img src='file:/C://1.jpg' /> </html>");

JLabel label1 = newJLabel("<html><img src='http://www.google.com/intl/en_ALL/images/logo.gif'></img></html>");

There is much more you can do with HTML, just note, when you do insert HTML into a componnents string paramater, you need to surround the HTML with the opening and closing HTML tags and you need to use single quotes since the entire string is bound by double quotes.

via http://www.johnciacia.com/2009/08/01/html-with-swing-components/

 

原文地址:https://www.cnblogs.com/youxin/p/2465485.html