How to persist inspection options when working with custom options panel?
Hi!
I am implementing a JavaScript inspection that would recognize some placeholder keywords in JS doc comments.
I have a pre-defined set of keywords but I also want to add an option to the inspection's Options panel, so that users can customize the keywords.
So far I have the following class (removed all non-UI related code):
public class MissingPropTypesDocCommentsInspection extends LocalInspectionTool {
private static final List<String> DEFAULT_KEYWORDS = List.of("asd", "asdasd", "todo", ".");
@SuppressWarnings("PublicField")
public OrderedSet<String> placeholderKeywords = new OrderedSet<>(DEFAULT_KEYWORDS);
@Nullable
@Override
public JComponent createOptionsPanel() {
PlaceholderKeywordsForm form = new PlaceholderKeywordsForm();
form.placeholderKeywordsField.setText(String.join(",", placeholderKeywords));
return form.panel;
}
/**
* A form built with Swing UI Designer.
*/
public static final class PlaceholderKeywordsForm {
private JTextField placeholderKeywordsField;
private JPanel panel;
}
}
So, I built a simple form with the UI Designer, with a label and a textfield in it, and this form is bound to the PlaceholderKeywordsForm class.
What I'm having trouble with finding out are
- when the text in the textfield on my panel changes, how can that change be recognized as a modification by the IJ Settings form? At the moment, if I change anything in it, the Apply button stays inactive.
- how can I persist the state of the fields in my inspection class (placeholderKeywords in this case), so that later when I open Settings, the saved values are loaded, not the default ones I set initially?
Of course with the built-in panel creation utility classes and methods there are no such problems, and I guess under the hood they somehow register the given fields for persistence. But how can this be achieved with such custom-built panels?
Thank you!
请先登录再写评论。
Meanwhile I think I figured it out.
Although I tried adding a listener (ActionListener) to the JTextField object, it seems it wasn't the correct one.
The new setup is that I add a KeyListener like this (meanwhile I also changed the field type from OrderedSet to String):
form.placeholderKeywordsField.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
placeholderKeywords = form.placeholderKeywordsField.getText();
}
});
You can use com.siyeh.ig.ui.ExternalizableStringSet to persist set of ordered Strings. Changed setting of inspection is detected via com.intellij.codeInspection.ex.ScopeToolState#areSettingsEqual
Thank you Yann. That's awesome.