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. You can view my Tutorial Index here: http://forum.codecall.net/java-tutor...ial-index.html
Lets first create a basic GUI with a JButton and JLabel:
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.Code: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(); } }
Such as:
Not only can you modify fonts, you can also insert images:Code:JLabel label1 = new JLabel("<html><font color='#FF0000'>Red Text</font>" + "<br /><font color='#00FF00'>Blue Text</font></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 <html></html> and you need to use single quotes since the entire string is bound by double quotes.Code:JLabel label1 = new JLabel("<html><img src='http://www.google.com/intl/en_ALL/images/logo.gif'></img></html>");
Originally posted as HTML with Swing ComponentsCode: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("<html><font color='#FF0000'>JButton Text</font></html>"); JLabel label1 = new JLabel("<html><font color='#FF0000'>Red Text</font>" + "<br /><font color='#00FF00'>Blue Text</font>" + "<br /><font color='#0000FF'>Green Text</font>" + "<br /><font color='#000000'>Black Text</font>" + "<br /><font color='#FFFFFF'>Blue Text</font></html>"); 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(); } }
Last edited by John; 08-01-2010 at 09:26 AM.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks