クラスのボタンを次のようにインスタンス化しました。
linkBtn = new LinkButton(
new URI("http://www.example.com"),
"Click me");
クリックしても何も起こらないので、次のようなアクション リスナーを追加します。
linkBtn.addActionListener(SOMETHING);
私はこのようなことを試しました:
linkBtn.addActionListener(new LinkButton.OpenUrlAction());
次のエラーが発生します。
LinkButton.OpenUrlAction を含む外側のインスタンスが必要です
私はまだ正しい構文を見つけていません。
JButton を拡張するクラスは次のとおりです。
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URI;
import javax.swing.JButton;
public class LinkButton extends JButton
implements ActionListener {
/** The target or href of this link. */
private URI target;
final static private String defaultText = "<HTML>Click the <FONT color=\"#000099\"><U>link</U></FONT>"
+ " to go to the website.</HTML>";
public LinkButton(URI target, String text) {
super(text);
this.target = target;
//this.setText(text);
this.setToolTipText(target.toString());
}
public LinkButton(URI target) {
this( target, target.toString() );
}
public void actionPerformed(ActionEvent e) {
open(target);
}
class OpenUrlAction implements ActionListener {
@Override public void actionPerformed(ActionEvent e) {
open(target);
}
}
private static void open(URI uri) {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(uri);
} catch (IOException e) { /* TODO: error handling */ }
} else { /* TODO: error handling */ }
}
}