Adding a custom Java Swing component in the GUI Designer
Answered
I've searched a lot, and apparently there are no tutorials for doing this in IntelliJ, but how do I create a custom component and use it in the GUI Designer form?
I want to create a custom JPanel with a gradient background and use it like I would use a regular JPanel, but I can't, I'm running on some problem
public class PanelMenu extends JPanel {
public PanelMenu() {
super();
setOpaque(false);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
GradientPaint gradientPaint = new GradientPaint(0, 0, Color.decode("1CB5E0"), 0, getHeight(), Color.decode("#000046"));
g2.setPaint(gradientPaint);
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 15, 15);
g2.fillRect(getWidth() - 20, 0, getWidth(), getHeight());
super.paintComponent(g);
}
}
I create my custom class, and then add it to a custom group in the palette.
It does get added to the component tree, but it doesn't work like a JPanel and I can't do anything with it, and instead, it ends up breaking IntelliJ.
Please sign in to leave a comment.
I have the same problem
Make sure this class is built with the JDK version not higher than the JetBrains Runtime used to run IntelliJ IDEA (target version).
If your project targets JDK 18 or 19, IDE running on JDK 17 will not be able to load such class.
Change the project JDK target levels, see https://stackoverflow.com/a/12900859/104891 for the relevant screenshots.
I'm using JDK15, I even tried lowering the target levels for the project to JDK 11 and it didn't work.
Your class code throws exception which is causing the problem, check the logs: https://intellij-support.jetbrains.com/hc/en-us/articles/207241085.
Fix this issue and it should work fine.
Thank you. I fixed the issue, and tried using the custom JPanel manually in a JFrame, and it works, but now when I drag and drop the custom JPanel in the GUI Builder, nothing happens.
Check logs for any potential exceptions.
Hmmm, all I'm getting is
Feel free to report a bug at https://youtrack.jetbrains.com/newIssue?project=IDEA and attach a sample project to reproduce this issue.
Thank you!