test.java

来自「swing 教程,与大家分享一下,哈哈,希望大家多多指教」· Java 代码 · 共 73 行

JAVA
73
字号
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;

public class Test extends JFrame {
	JFileChooser chooser = new JFileChooser();
	JComboBox comboBox = new JComboBox();
	JButton button = new JButton("show file chooser ...");

	public Test() {
		super("Standard File Chooser Types");
		Container contentPane = getContentPane();

		contentPane.setLayout(new FlowLayout());
		contentPane.add(comboBox);
		contentPane.add(button);		

		comboBox.addItem("OPEN_DIALOG");
		comboBox.addItem("SAVE_DIALOG");
		comboBox.addItem("custom dialog");

		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String message = "CANCELED";
				int state = showChooser(
							(String)comboBox.getSelectedItem());
				File file = chooser.getSelectedFile();

				if(file != null && 
				   state == JFileChooser.APPROVE_OPTION) {
					message = chooser.getApproveButtonText() + 
							  " " + file.getPath();
				}
				JOptionPane.showMessageDialog(null, message);
			}
		});
	}
	private int showChooser(String s) {
		int state; 

		if(s.equals("OPEN_DIALOG")) {
			state = chooser.showOpenDialog(null);
		}
		else if(s.equals("SAVE_DIALOG")) {
			state = chooser.showSaveDialog(null);
		}
		else { // custom dialog
			String string = JOptionPane.showInputDialog(
										null, 
										"Button/Title String:");

			chooser.setApproveButtonMnemonic(string.charAt(1));
			state = chooser.showDialog(Test.this, string);
		}
		return state;
	}
	public static void main(String args[]) {
		JFrame f = new Test();
		f.setBounds(300,300,350,100);
		f.setVisible(true);

		f.setDefaultCloseOperation(
			WindowConstants.DISPOSE_ON_CLOSE);
	
		f.addWindowListener(new WindowAdapter() {
			public void windowClosed(WindowEvent e) {
				System.exit(0);	
			}
		});
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?