java - 如何将 ActionListener 添加到扩展 JButton 的类的实例?

标签 java swing events uri jbutton

我实例化了我的类的一个按钮,如下所示:

linkBtn = new LinkButton(
                        new URI("http://www.example.com"),
                        "Click me");

当我点击它时什么也没有发生,所以我想添加一个像这样的 Action 监听器:

linkBtn.addActionListener(SOMETHING);

我尝试过这样的事情:

linkBtn.addActionListener(new LinkButton.OpenUrlAction());

这会产生以下错误:

an enclosing instance that contains LinkButton.OpenUrlAction is required

我还没有找到正确的语法。

这是我扩展 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 */ }
  }
}

最佳答案

I'm open to suggestions. I don't like my program structure either...

到目前为止提供的答案都非常好。

Hovercraft 建议使用 Action,这将简化代码的结构。

例如...

import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class LinkButtonExample {

    public static void main(String[] args) {
        new LinkButtonExample();
    }

    public LinkButtonExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new GridBagLayout());
                    frame.add(new JButton(new OpenURLAction(new URL("http://stackoverflow.com/"))));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (MalformedURLException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public class OpenURLAction extends AbstractAction {

        private URL url;

        public OpenURLAction(URL url) {

            this("<HTML>Click the <FONT color=\\\"#000099\\\"><U>link</U></FONT> to go to the website.</HTML>", url);

        }

        public OpenURLAction(String text, URL url) {

            putValue(NAME, text);
            setURL(url);

        }

        public void setURL(URL url) {
            this.url = url;
            setEnabled(
                            url != null
                            && Desktop.isDesktopSupported()
                            && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE));
            putValue(SHORT_DESCRIPTION, url == null ? null : url.toString());
        }

        public URL getURL() {
            return url;
        }

        @Override
        public void actionPerformed(ActionEvent e) {

            if (isEnabled()) {

                URL url = getURL();
                if (url != null && Desktop.isDesktopSupported()
                                && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                    try {
                        Desktop.getDesktop().browse(url.toURI());
                    } catch (    IOException | URISyntaxException ex) {
                        ex.printStackTrace();
                    }
                }

            }

        }
    }
}

查看How to use Actions了解更多详情

关于java - 如何将 ActionListener 添加到扩展 JButton 的类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17246764/

相关文章:

java - Bukkit PlayerInteractEvent 被注册了两次

java - Solr中多值字段的搜索结果按升序排序

java - zeromq 与 Python 与 Java 的 node.js 性能

java - 如何访问构造函数内创建的对象?

java - 如何在 JTable java 中搜索元素?

java - 如何在 Java 中渲染二维图像

ruby-on-rails - ruby rails : Observe model changes from controller action

c# - 派生类应该处理基类的事件吗? (C#/WPF)

java - 系统架构

java - JFrame 在 Thread.sleep(int) 期间处于非 Activity 状态