java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

awt swing编程java窗体加超级链接

上次编写的俄罗斯方块,为了给它加一个超级链接,发现java居然如此的笨笨。不过方法还是有的。基础思想为调用桌面。启动浏览器,之前看过这个启动的办法,当时看了觉得java这个方法没什么用处,现在发现,设计了这个办法,就有他的用处。

package com.javaer.examples.awt;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class FrameLink extends JLabel {
	private String _url;
	private String _text;
	private Cursor cur_bak;
	
	//加上超级链接底部的一条线
	protected void paintBorder(Graphics g) {
		int w = this.getSize().width;
		int h = this.getSize().height;

		g.drawLine(0, h - 1, w - 1, h - 1);// 底部加一条线条

	}

	public FrameLink(String text, String url) {
		this.setForeground(Color.BLUE);//设置颜色

		if (!url.startsWith("http://")) {
			url = "http://" + url;
		}
		this._url = url;
		this._text = text;
		setText(text);

		this.addMouseListener(new MouseAdapter() {
			public void mouseEntered(MouseEvent e) {
				cur_bak = getCursor();
				setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));// 显示小手

			}

			public void mouseExited(MouseEvent e) {
				setCursor(cur_bak);
			
			}
			
			//点击一瞬间
			public void mousePressed(MouseEvent e) {
				URI uri;
				try {
					uri = new URI(_url);
					Desktop dt = Desktop.getDesktop();
					if (Desktop.isDesktopSupported()
							&& dt.isSupported(Desktop.Action.OPEN)) {
						dt.browse(uri);
					}
				} catch (Exception x) {

				}
				// 仅仅对windows有效
				// try {
				// Runtime.getRuntime().exec("explorer " + _url);
				// } catch (IOException e1) {
				// e1.printStackTrace();
				// }
			}
		});
	}

	// 测试
	public static void main(String[] args) {
		JFrame f = new JFrame();
		f.setLayout(new FlowLayout());
		FrameLink fl = new FrameLink("月小升", "http://java-er.com/");

		f.add(fl);
		f.setSize(500, 400);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
	}
}

核心算法

uri = new URI(_url);
					Desktop dt = Desktop.getDesktop();
					if (Desktop.isDesktopSupported()
							&& dt.isSupported(Desktop.Action.OPEN)) {
						dt.browse(uri);
					}


This entry was posted in JAVA and tagged , , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/awt-swing-add-link/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply