How to Put an HTML code in a Button in Java

May 28, 2020
Tutorials
button html code in java

This instructional exercise is about how to put an HTML code in a button in Java. The HTML tags will be put inside the JButton to display text.

So, now let’s start this tutorial!

1. Open JCreator or NetBeans and make a java program with a file name of htmlInButton.java.

2. Import the javax.swing.* package library that is used to access the JButton, and JFrame class.

import javax.swing.*; //used to access the JButton, and JFrame class.

3. Initialize your variable in your Main, variable frame for JFrame, and variable button as JButton.

JFrame frame = new JFrame("HTML Code in a Button");
JButton button = new JButton();

 

4. Now, to make an HTML code inside the button, we’ll going to use the setText method of our button. The setText method can recognize HTML code. It has an advantage of calling a text with a font, color, alignment, font style without using the classes of awt library like font class, color class, alignment, and the styles of the font. Have this code below:

button.setText ("<html><font face='Tahoma'" + " color=blue><b>This text has an HTML Code<b></font><br><font face='courier new'" + " color=red><center>Sourcecodester<center></font></html>");

 

html – an html tag
font face=’Tahoma'” + ” color=blue – a font tag with a font style of tahoma and font color of blue
b– start of the bold tag
This text has an HTML Code – the text inside the html with a specific font of tahoma and blue color of font
font face=’courier new'” + ” color=red – a font tag with a font style of courier new and font color of red
center – a center alignment tag
Sourcecodester – the text inside the html with a specific font of courier new and red color of font

Add the button to the frame using the add method.

frame.getContentPane().add(button);

5. Lastly, set the size, set visibility to true, and the close operation of the frame. Have this code below:

frame.setSize(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 


Output:

button html code in java

Here’s the full code of this tutorial:

import javax.swing.*; //used to access the JButton, and JFrame class.
 
public class htmlInButton{
 
  public static void main(String[] a) {
    JFrame frame = new JFrame("HTML Code in a Button");
    JButton button = new JButton();
    button.setText ("<html><font face='Tahoma'" + " color=blue><b>This text has an HTML Code<b></font><br><font face='courier new'" + " color=red><center>Sourcecodester<center></font></html>");
 
    frame.getContentPane().add(button);
    frame.setSize(300, 200);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
 
}

 

 

Facebook Comments

Leave a Reply

Your email address will not be published.