Cod*_*Guy 2 java swing jtextfield
我有一个JTextField textField,我有一个任意的String string
我希望文本字段显示字符串的结尾,但切断它不适合的内容并使用"..."代替它.例如,如果字符串是,"Hello How Are You Doing"那么文本字段可能看起来像
...re You Doing
Run Code Online (Sandbox Code Playgroud)
鉴于textfield和string,我该怎么做?
更新:我想这样做的原因是因为它是一个文件选择器,所以我想优先显示文件的结尾.例如,如果用户选择保存在/Users/Name/Documents/Folder1/Folder2/Folder3/file.txt,那么我想显示结束,其余不适合的应该替换为"..."
这是它的地方:
JFileChooser chooser = new JFileChooser();
int response = chooser.showSaveDialog(this);
if(response == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String string = file.getAbsolutePath();
fileTextField.setText(/* here's where the code would go */);
}
Run Code Online (Sandbox Code Playgroud)
..it是一个文件选择器,所以我想优先显示文件的结尾.
我建议将此作为替代方案,或者在文件名后删除工具提示(路径).

import java.awt.*;
import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
class FileListName {
final class FileListCellRenderer extends DefaultListCellRenderer {
private FileSystemView fsv = FileSystemView.getFileSystemView();
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
JLabel l = (JLabel) c;
File f = (File) value;
l.setText(f.getName());
l.setIcon(fsv.getSystemIcon(f));
l.setToolTipText(f.getAbsolutePath());
return l;
}
}
public FileListName() {
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
if (jfc.getSelectedFile() != null) {
File[] f = {jfc.getSelectedFile()};
JList list = new JList(f);
list.setVisibleRowCount(1);
list.setCellRenderer(new FileListCellRenderer());
JOptionPane.showMessageDialog(null, list);
}
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
// Provides better icons from the FSV.
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
new FileListName();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Run Code Online (Sandbox Code Playgroud)