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

时间:2013-06-22 02:29:43

标签: java swing events uri jbutton

我实例化了我班级的按钮:

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

单击它时没有任何反应,所以我想添加一个像这样的动作监听器:

linkBtn.addActionListener(SOMETHING);

我尝试过这样的事情:

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

这会产生以下错误:

  

包含LinkBut​​ton.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 */ }
  }
}

4 个答案:

答案 0 :(得分:2)

我不明白为什么你扩展JButton但你可以在构造函数中默认添加这个监听器。

 public LinkButton(URI target, String text) {
        super(text);
        this.target = target;
        //this.setText(text);
        this.setToolTipText(target.toString());
        this.addActionListener(this);
        //this.addActionListener(new OpenUrlAction());
    }

或者你可以这样做。

linkBtn.addActionListener(linkBtn.new OpenUrlAction());    outerObject.new InnerClass()

或者您可以使用constructor injection

修改内部课程
class OpenUrlAction implements ActionListener{
  private URI target;

  OpenUrlAction(URI target){
   this.target=target;
  }

  @Override
  public void actionPerformed(ActionEvent evt){
     open(this.target);
  }
}

在客户代码中:

`linkBtn.addActionListener(linkBtn.new OpenUrlAction(lninkBtn.getTarget)); // or the target that you want`

答案 1 :(得分:2)

你可以这样做:

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

但是你的程序结构让我很畏缩。我自己试图让Actions与视图分开。我也更喜欢通过组合而不是继承来扩展。

答案 2 :(得分:2)

  

我愿意接受建议。我不喜欢我的程序结构...

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

Hovercraft建议使用Action s,这只是代码的结构。

例如......

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了解详情

答案 3 :(得分:0)

到目前为止,我提出了这个问题。我将此方法添加到我的LinkBut​​ton类:

public void init() {
    this.addActionListener(this);
}

然后我添加了这段代码来添加动作监听器:

linkBtnDonate.init();

它正在运作。我愿意接受其他建议。