【问题标题】:Is it possible that JButton and actionPerformed method are in different files?JButton 和 actionPerformed 方法是否可能在不同的文件中?
【发布时间】:2013-03-31 14:11:02
【问题描述】:

是否可以在一个文件上有一个按钮,而在另一个文件中有它的 actionPerformed(ActionEvent e) 方法?我正在尝试向按钮添加一个 actionListener,choose1 在文件 trialdump.java 中,但 actionPerformed(ActionEvent e) 方法在文件 listen.java 中。我尝试扩展公共类 Trialdump 扩展侦听,但它显示错误。知道如何将方法添加到按钮吗?谢谢。

这是我在文件 trialdump.java 中的代码:

package Core;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.*;
import java.awt.*;

// Create a simple GUI window
public class trialdump {

private static void createWindow() {

    // Create and set up the window.
    JFrame frame = new JFrame("PDF Denoiser");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // My edit
    JPanel panel = new JPanel();
    GroupLayout layout = new GroupLayout(panel);
    panel.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true);

    JLabel label1 = new JLabel("Image File");
    JLabel label2 = new JLabel("Destination");
    JLabel label3 = new JLabel("Preview");

    JTextField current = new JTextField();
    JTextField dest = new JTextField();
    JTextArea preview = new JTextArea();

    preview.setEditable(false);
    JScrollPane previewScrollPane = new JScrollPane(preview);

    JButton choose1 = new JButton("Search1");
    JButton choose2 = new JButton("Search2");
    JButton algo1 = new JButton("MDWM");
    JButton algo2 = new JButton("BFMR");
    JButton algo3 = new JButton("Mine");



    // Horizontal arrangement
    layout.setHorizontalGroup(layout
            .createSequentialGroup()
            .addGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(label1)
                            .addComponent(label2).addComponent(label3))
            .addGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(current)
                            .addComponent(dest).addComponent(preview))
            .addGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(choose1)
                            .addComponent(choose2).addComponent(algo1).addComponent(algo2).addComponent(algo3)));

    layout.linkSize(SwingConstants.HORIZONTAL, choose1, choose2, algo1, algo2, algo3);

    // Vertical arrangement
    layout.setVerticalGroup(layout
            .createSequentialGroup()
            .addGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(label1)
                            .addComponent(current).addComponent(choose1))
            .addGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(label2)
                            .addComponent(dest).addComponent(choose2))
            .addGroup(
                    layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                            .addComponent(label3)
                            .addComponent(preview)
                            .addGroup(
                                    layout.createSequentialGroup().addComponent(algo1).addComponent(algo2)
                                            .addComponent(algo3))));

    // Display the window.
    frame.setLocationRelativeTo(null);
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {

    createWindow();

}
}

这是我在 listen.java 中的代码:

package components;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;

public class listen extends JPanel implements ActionListener{

static private String newline = "\n";
private JTextArea log;
private JFileChooser fc;

public listen() {



}

public void actionPerformed(ActionEvent e) {
    //Set up the file chooser.
    if (fc == null) {
        fc = new JFileChooser();

    //Add a custom file filter and disable the default
    //(Accept All) file filter.
        fc.addChoosableFileFilter(new imagefilter());
        fc.setAcceptAllFileFilterUsed(false);

    //Add custom icons for file types.
        fc.setFileView(new imagefileview());

    //Add the preview pane.
        fc.setAccessory(new imagepreview(fc));
    }

    //Show it.
    int returnVal = fc.showDialog(listen.this,
                                  "Attach");

    //Process the results.
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();

    } else {
        log.append("Attachment cancelled by user." + newline);
    }
    log.setCaretPosition(log.getDocument().getLength());

    //Reset the file chooser for the next time it's shown.
    fc.setSelectedFile(null);
}

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event dispatch thread.
 */


public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            //Turn off metal's use of bold fonts
            UIManager.put("swing.boldMetal", Boolean.FALSE);

        }
    });
}
}

【问题讨论】:

  • 有可能。监听器可以在一个单独的文件中。
  • 嗨,Sudhanshu,你能给我举个例子吗?非常感谢。
  • 答案是“是”。事实上,在内部课程之前的日子里,这是唯一的方法......啊,那些日子。只要您尝试注册到按钮的类实现ActionListener,您就不应该有问题。
  • 您可能会发现阅读How to use Action Listeners 会有所帮助

标签: java swing button actionlistener


【解决方案1】:

您可以添加在另一个类中定义的侦听器,执行类似的操作

JButton choose1 = new JButton("Search1");
choose1.addActionListener(new listen());

顺便说一句,您应该注意代码的更多部分:

  • 类名的首字母大写应采用驼峰法输入
  • 为您的包使用正确的名称
  • 我不认为侦听器类中的主要方法有什么用处
  • 根本不需要在侦听器类中从 JPanel 扩展
  • 尽量避免创建空构造函数,就像您在listen() 中所做的那样。至少调用 super(),或者干脆不包含它。

【讨论】:

  • 这个我试过了,但是有错误:找不到符号choose1.addActionListener(new listen());箭头指向listen()。
  • 您是使用 Eclipse 之类的 IDE 进行开发还是尝试使用 javac 进行编译?在第二种情况下,您要编译两个类:javac *.java。您还必须为这两个类创建一个正确的包名称和相同的包。
  • 我正在使用 JCreator Pro。所以问题出在包裹上?我将尝试再次修改我的代码。谢谢。
  • 你是对的。包名解决了它。非常感谢。 :)
  • 我同意你的所有其他建议,除了最后一个:如果你不调用另一个构造函数,任何构造函数都会调用super()
【解决方案2】:

只是示例代码,您可以在类似的行中进行更改-

class Some extends JFrame {

    private JButton button = new JButton("Something");

    Some() {
        button.addActionListener(new MyListener());
    }
}

class MyListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // do something
    }    
}

【讨论】:

  • 我试过这个但是有一个错误:找不到符号choose1.addActionListener(new listen());箭头指向listen()。
【解决方案3】:

这样做的正确方法是扩展AbstractAction 类,将所有操作代码添加到它的actionPerformed 方法,然后将它的新实例传递给JButton's 构造函数或调用@987654325 @上JButton

这里有一个link,可以帮助您解决所有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 2017-05-05
    相关资源
    最近更新 更多