我像这样实例化了我的班级的一个按钮:
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 */ }
}
}