Java Swing Create LinkButton


 

Java Swing Create LinkButton

In this section, you will learn how to create a link button in java swing.

In this section, you will learn how to create a link button in java swing.

Java Swing Create LinkButton

You all are aware of JButtons, JRadioButtons, JToggleButtons and you have used these components in your applications. Here we are going to create a Link Button that will allow you to move to another page very easily. For this, we have used html code to display the text in a standard way.

Here is the code:

import java.awt.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;

public class LinkButton {
	public static void main(String[] args) throws Exception {
		final URI uri = new URI("http://www.roseindia.net");
		JFrame frame = new JFrame("Link");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(300, 100);
		Container container = frame.getContentPane();
		container.setLayout(new GridBagLayout());

		JButton button = new JButton();
		button.setText("www.roseindia.net");
		button.setHorizontalAlignment(SwingConstants.LEFT);
		button.setBorderPainted(false);
		button.setOpaque(false);
		button.setBackground(Color.lightGray);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (Desktop.isDesktopSupported()) {
					Desktop desktop = Desktop.getDesktop();
					try {
						desktop.browse(uri);
					} catch (Exception ex) {
					}
				} else {
				}
			}
		});
		container.add(button);
		frame.setVisible(true);
	}
}

Output:

Ads