MaC*_*aCo 2 java swing jfilechooser jframe disambiguation
我在使用JFileChooser时遇到了一些麻烦.每当我运行程序时,如果我立即单击"取消"按钮而不选择文件,它将显示"你好",如果我点击打开,它将不会做任何事情.另一方面,如果我选择一个文件并单击打开它将开始显示"Hello"(调用createFile方法),如果单击"取消",将显示"hello".
我的问题是如何找出单击了哪个按钮并为每个按钮执行特定操作,如单击取消时调用die函数并在单击打开时调用createFile函数.
我在想类似的东西
if(e.getSource() == "Something_I_Dont_know") { do this}
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
} // MFRAME CLASS结束
Rei*_*eus 10
使用适当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");
}
Run Code Online (Sandbox Code Playgroud)
注意:单击对话框X上的JFileChooser按钮也会触发CANCEL_OPTION.