1. 程式人生 > >Swing 實現超連結 開啟網頁

Swing 實現超連結 開啟網頁

1、建立一個超連結的JLabel,// 主要是使用下面方法,僅適用於JdK1.6及以上版本
  Desktop.getDesktop().browse(
   new URL("http://www.baidu.com").toURI());

import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

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

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);
    }
}

2、 使用Runtime.getRuntime().exec
 import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
class JButtonDemo
{
 JFrame mainFrame;
 JButton simpleButton;
 public JButtonDemo()
 {
  mainFrame = new JFrame("JButtonDemo");
  simpleButton = new JButton("百度搜索");
  mainFrame.getContentPane().add(simpleButton);
  simpleButton.addActionListener(new ActionListener()
  {// 新增動作偵聽器,當按鈕被按下時執行這裡的程式碼以開啟網頁
     public void actionPerformed(ActionEvent e)
     {
      try
      {
       Runtime.getRuntime()
         .exec("cmd /c start http://www.baidu.com");
      } catch (IOException ee)
      {
       ee.printStackTrace();
      }
     }
    });
  simpleButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
  mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  mainFrame.pack();
  mainFrame.setLocationRelativeTo(null);
  mainFrame.setVisible(true);
 }
 public static void main(String[] args)
 {
  new JButtonDemo();
 }
}