您的位置:首页 > 编程语言 > Java开发

基于Java Swing的超链接标签

2010-11-06 10:05 399 查看
1.要解决的问题

基于Java Swing的超链接实现

2.自定义一个超链接标签控件[LinkLabel]

2.1.完整代码如下:
public class LinkLabel extends JLabel {

private String text, url;

private boolean isSupported;

public LinkLabel(String text, String url) {

this.text = text;

this.url = url;

try {

this.isSupported = Desktop.isDesktopSupported()

&& Desktop.getDesktop().isSupported(Desktop.Action.BROWSE);

} catch (Exception e) {

this.isSupported = false;

}

setText(false);

addMouseListener(new MouseAdapter() {

public void mouseEntered(MouseEvent e) {

setText(isSupported);

if (isSupported)

setCursor(new Cursor(Cursor.HAND_CURSOR));

}

public void mouseExited(MouseEvent e) {

setText(false);

}

public void mouseClicked(MouseEvent e) {

try {

Desktop.getDesktop().browse(

new java.net.URI(LinkLabel.this.url));

} catch (Exception ex) {

}

}

});

}

private void setText(boolean b) {

if (!b)

setText("<html><font color=blue><u>" + text);

else

setText("<html><font color=red><u>" + text);

}

public static void main(String[] args) {

JFrame jf = new JFrame("一个超链接实现的例子");

JPanel jp = new JPanel();

jp.add(new LinkLabel("访问eRedLab", "http://hi.baidu.com/eRedLab"));

jf.setContentPane(jp);

jf.pack();

jf.setVisible(true);

}

}

Swing 给JLabel加超链接 ---另一种方式

实现这样一个功能很简单,我们可以把它封装到一个类中,如果我们想把一个带图标的JLabel做成一个超链接效果,就可以给JLabel组件增加鼠标事件,来调用我们下边的代码,打开系统的默认浏览器。

自己先封装一个打开浏览器的类:

package com.feng.logon;

import java.awt.Cursor;

import java.awt.Desktop;

import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URI;

import java.net.URISyntaxException;

import javax.swing.JLabel;

/** *//**

*

* @author Anthrax

*此类负责检测系统的默认浏览器等程序,并负责启动它们

* @netSite 指定要显示的网址

*/

public class RunBrowser{

private Desktop desktop;

private URI uri;

private String netSite;

private Cursor hander;

/** *//** Creates a new instance of DesktopRuner */

public RunBrowser(){

this.desktop = Desktop.getDesktop();

}

/**//*

*检测系统是否支持浏览器

*/

public boolean checkBroswer(){

if(desktop.isDesktopSupported() && desktop.isSupported(Desktop.Action.BROWSE)){

return true;

}

else{

return false;

}

}

/**//*

*运行默认浏览器,并在其中显示指定网址

*/

public void runBroswer(){

netSite = "http://www.baidu.com";

try {

uri = new URI(netSite);

} catch (URISyntaxException ex){

ex.printStackTrace();

}

try{

desktop.browse(uri);

} catch (IOException ex){

ex.printStackTrace();

}

}

/**//*

*改变鼠标形状

*/

public void changeMouse(JLabel label){

hander = new Cursor(Cursor.HAND_CURSOR);

label.setCursor(hander);

}

}

假如有这样一个JLabel,就可以给这个JLabel加超链接了

JLabel jl=new JLabel("申请帐号");

LLogon.setCursor(new Cursor(Cursor.HAND_CURSOR));//这样也可以改变鼠标形状

LLogon.addMouseListener(new MouseAdapter(){

public void mouseClicked(MouseEvent e){

try{

new RunBrowser().runBroswer();

}catch(Exception ex){

ex.printStackTrace();

}

}

});

注意上面的红色代码是调用的部分...一般放在构造函数里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: