java按钮选择文件名字,使JFileChooser选择文件名的文本,而不选择扩展名

I'd like the text in the file name field of the JFileChooser save dialog to select just the file name and not the extension.

I currently have this:

kjiZz.jpg

And want it to look like this:

BVHMa.jpg

This is a simple change, but one that makes saving a file much easier, in my opinion, since the user can start typing the file name right away without erasing the extension accidentally.

I know I can forcefully add the extension if it's missing, but I'd rather not do this because the extension isn't mandatory and I don't feel it should be enforced.

So, is there any way I could achieve this?

解决方案

The API does not offer that directly but one simple way to do it is to scan the component hierarchy, looking for a JTextField and then change the selection of that textfield.

Here is an example of that solution:

import java.awt.Component;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.File;

import javax.swing.JButton;

import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JTextField;

import javax.swing.SwingUtilities;

public class TestJFileChooser {

public TestJFileChooser() {

}

protected void initUI() {

JFrame frame = new JFrame(TestJFileChooser.class.getSimpleName());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JButton button = new JButton("Click me");

button.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

JFileChooser chooser = new JFileChooser();

chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "save.dat"));

final JTextField textField = getTexField(chooser);

if (textField != null) {

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

String text = textField.getText();

if (text != null) {

int index = text.lastIndexOf('.');

if (index > -1) {

textField.setSelectionStart(0);

textField.setSelectionEnd(index);

}

}

}

});

}

chooser.showSaveDialog(button);

}

private JTextField getTexField(Container container) {

for (int i = 0; i < container.getComponentCount(); i++) {

Component child = container.getComponent(i);

if (child instanceof JTextField) {

return (JTextField) child;

} else if (child instanceof Container) {

JTextField field = getTexField((Container) child);

if (field != null) {

return field;

}

}

}

return null;

}

});

frame.add(button);

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

TestJFileChooser fc = new TestJFileChooser();

fc.initUI();

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值