TextFieldWithBrowseButton with completion relative to project dir
I want a text field that will have a file relative to project root.
I've managed to get to work browse button using following TextComponentAccessor:
new TextComponentAccessor<JTextField>() {
@Override
public String getText(JTextField component) {
return project.getBasePath() + "/" + component.getText();
}
@Override
public void setText(JTextField component, @NotNull String text) {
String baseDir = project.getBaseDir().getPath();
if (baseDir.endsWith("/"))
baseDir = baseDir.substring(0, baseDir.length() - 1);
if (!text.startsWith(baseDir)) {
throw new IllegalArgumentException("Only paths inside a project allowed");
}
component.setText(text.substring(baseDir.length() + 1));
}
}
How do I install completion so that it works with relative paths?
Please sign in to leave a comment.
You have to call com.intellij.openapi.ui.TextFieldWithBrowseButton#addBrowseFolderListener() with properly configured FileChooserDescriptor, e.g. passing in project base dir into com.intellij.openapi.fileChooser.FileChooserDescriptor#setRoots(). You can find many examples of usage in Community Edition sources.
I've tried to call setRoots(baseDir); for descriptor and call addBrowseFolderListener and/or installCompletion with them, It completes only things that are inside this root(cool) but still shows a full path(not cool). Thanks for the idea for checking out CE sources, I'll try tolookinto them
Could you, please, give me an idea where in idea I can see similar fields?
I've tried to find it in sources randomly. I found more convenient way to work with browse button(overiding extendPath and chosenFileToResultingText) but not a way to make work completion with relative URLs.
Just curious: why do you need this specific behavior? The users can configure their project in such a way that the project base directory will not contain anything except for the project files, with all the actual contents of the project stored elsewhere. Your text field would not be very useful in such a configuration.
Well, I needto save paths and don't want to store absolute paths to allow moving a project. It was just the easiest idea I had for that
IntelliJ IDEA takes care of it by itself. If you use JDOMExternalizable or PersistentStateComponent to store your settings, it will automatically replace the project base directory with $PROJECT_DIR$ when saving the settings, and back when restoring.
Thanks for info, I use PersistentStateComponent, so I'll consider moving to absolute paths.