JFileChooser-关于;开放式;及;取消“;按钮。JAVA
我在使用JFileChooser时遇到一些问题。每当我运行程序时,如果我没有选择文件而立即单击“取消”按钮,它将显示“你好”,如果我单击“打开”,它将不会执行任何操作。另一方面,如果我选择一个文件并单击“打开”,它将开始显示“Hello”(调用createFile方法),如果我单击“取消”,它将显示“Hello” 我的问题是如何找出单击了哪个按钮,以及如何为每个按钮执行特定的操作,如单击cancel时调用die函数,单击open时调用createFile函数 我在想类似的事情JFileChooser-关于;开放式;及;取消“;按钮。JAVA,java,swing,jframe,jfilechooser,disambiguation,Java,Swing,Jframe,Jfilechooser,Disambiguation,我在使用JFileChooser时遇到一些问题。每当我运行程序时,如果我没有选择文件而立即单击“取消”按钮,它将显示“你好”,如果我单击“打开”,它将不会执行任何操作。另一方面,如果我选择一个文件并单击“打开”,它将开始显示“Hello”(调用createFile方法),如果我单击“取消”,它将显示“Hello” 我的问题是如何找出单击了哪个按钮,以及如何为每个按钮执行特定的操作,如单击cancel时调用die函数,单击open时调用createFile函数 我在想类似的事情 if(e.getS
if(e.getSource() == "Something_I_Dont_know") { do this}
这是我的密码:
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Grading{
public static void main(String[] arg){
new MFrame();
}
}// end of class Grading
class MFrame extends JFrame{
private JCheckBox cum,uc,ucs;
private JButton calc, clear, exit;
private ButtonGroup bg;
private JTextArea display;
private JFileChooser input;
public MFrame(){
setVisible( true );
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(550,550);
input = new JFileChooser();
add( input );
input.addActionListener(
new ActionListener(){
public void actionPerformed( ActionEvent e ){
//die();
createFile();
}
}
);
setLayout( new FlowLayout() );
pack();
}// end of constructor
public double gpa(){
return 1.0;
}// end of gpa method
public void createFile(){
System.out.println("Hello");
}
public void die(){
System.exit(0);
}
}//MFRAME类的末尾使用相应的
showDialog
方法的结果来确定单击了哪个按钮
JFileChooser input = new JFileChooser();
int result = input.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
createFile();
} else if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("Cancel was selected");
}
注意:单击JFileChooser
对话框上的X
按钮也会触发CANCEL\u选项
初始化组件时请阅读:
fileChooser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
fileChooserActionPerformed(evt);
}
});
上面的操作侦听器调用以下方法:
private void fileChooserActionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(javax.swing.JFileChooser.APPROVE_SELECTION)) {
System.out.println("approve selection");
} else if (e.getActionCommand().equals(javax.swing.JFileChooser.CANCEL_SELECTION)) {
System.out.println("cancel selection");
}
}
注意:必须选择一个文件/文件夹,才能使“批准”选择生效谢谢!成功了!但出于好奇,我能走ActionListener路线吗?或者我是不是被迫走了“批准”的路?避免走那条路。当取消在文件选择器的
ActionListener
中注册时,“打开”按钮没有注册,因此根本不会响应。使用如上所示的返回结果,意图更加清晰。