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:
[code lang="java"]package tutorials;
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();
}
}[/code]
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:
[code lang="java"]JLabel label1 = new JLabel("Red Text" +
"
Blue Text");[/code]
Not only can you modify fonts, you can also insert images:
[code lang="java"]JLabel label1 = new JLabel("
");[/code]
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.
[code lang="java"]package tutorials;
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("Red Text" +
"
Blue Text" +
"
Green Text" +
"
Black Text" +
"
Blue 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();
}
}[/code]
Thank you so much for submitting your tutorial to Pixel2life, your submission has been accepted
I look forward to more tutorials from your site in the future!
|