我在使用 JFileChooser 时遇到了一些问题。每当我运行程序时,如果我在没有选择文件的情况下立即单击“取消”按钮,它将显示“你好”,如果我单击打开,它不会执行任何操作。另一方面,如果我选择一个文件并单击“打开”,它将开始显示“Hello”(调用 createFile 方法),如果我单击“取消”,它将显示“hello”。
我的问题是如何找出单击了哪个按钮并为每个按钮执行特定操作,例如单击取消时调用 die 函数并单击 open 时调用 createFile 函数。
我在想类似的事情
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");
}
注意:单击
X
JFileChooser
上的按钮对话框也会触发 CANCEL_OPTION
.阅读 How to Use File Choosers
关于java - JFileChooser - 关于 "open"和 "cancel"按钮。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17034282/