发现问题过程:
想添加一个指示功能开关的按钮,如图:
代码如下:
import javax.swing.*;
import java.awt.*;
public class M_Button extends JPanel {
private JButton button;
private JLabel label;
public M_Button(String title){
button = new JButton(title);
label = new JLabel(" ");
label.setOpaque(true);
label.setBackground(Color.red);
setLayout(new BorderLayout());
add(button, BorderLayout.CENTER);
add(label, BorderLayout.EAST);
button.addActionListener((e) ->{
Color color = label.getBackground();
if(color.equals(Color.red)){
label.setBackground(Color.green);
}else if(color.equals(Color.green)){
label.setBackground(Color.red);
}
});
}
}
写好之后编译一下这个类,步骤:[主菜单-构建-重新编译****.java]
将其添加到组件列表中,步骤如下:
将其添加到窗口中之后问题发生了:
解决方法
很多人以为这是一个问题,其实这是两个问题
- Class not found
- 窗体包含具有"自定义创建"选项但没有 createUIComponents() 方法的组件
Class not found 解决方法
官方说明文档地址:Placing Non-Palette Components or Forms | IntelliJ IDEA Documentation
根据说明可知我们的组件类需要有默认构造函数,巧了,我的组件里面刚好没有。
只需要添加默认构造函数或修改现有的构造函数即可,修改后如下:
import javax.swing.*;
import java.awt.*;
public class M_Button extends JPanel {
private JButton button;
private JLabel label;
public M_Button(){
button = new JButton("title");
label = new JLabel(" ");
label.setOpaque(true);
label.setBackground(Color.red);
setLayout(new BorderLayout());
add(button, BorderLayout.CENTER);
add(label, BorderLayout.EAST);
button.addActionListener((e) ->{
Color color = label.getBackground();
if(color.equals(Color.red)){
label.setBackground(Color.green);
}else if(color.equals(Color.green)){
label.setBackground(Color.red);
}
});
}
}
重新编译此类,步骤:[主菜单-构建-重新编译****.java]
重新加载自定义组件,步骤如图:
可能有的宝贝儿们找不到,找不到没关系,我也没找到,万能大法如下:
一般情况下这问题就解决了
可有些宝贝儿们就会问,这样就不能通过构造方法设置按钮标题了,怎么办?
不要急,往下看就好。
窗体包含具有"自定义创建"选项但没有 createUIComponents() 方法的组件解决方法
取消勾选自定义创建(Custom Create)即可
一般情况这样都能解决,有没有宝贝儿遇到了不一般的情况,比如无法取消勾选
这样的情况一般伴随着第一个问题,先把Class not found解决掉就好了。
回到之前的疑问,这样不能通过构造方法设置按钮标题,怎么办?
简单,勾选自定义创建选项,然后在自定义创建方法里手动初始化即可
自定义创建的官方文档:Creating Form Initialization Code | IntelliJ IDEA Documentation
- 将自定义创建(Custom Create)勾选上
- 修改自定义组件代码,添加一个空的默认构造函数,一个传入标题的构造函数
-
import javax.swing.*; import java.awt.*; public class M_Button extends JPanel { private JButton button; private JLabel label; private M_Button(){} public M_Button(String title){ button = new JButton(title); label = new JLabel(" "); label.setOpaque(true); label.setBackground(Color.red); setLayout(new BorderLayout()); add(button, BorderLayout.CENTER); add(label, BorderLayout.EAST); button.addActionListener((e) ->{ Color color = label.getBackground(); if(color.equals(Color.red)){ label.setBackground(Color.green); }else if(color.equals(Color.green)){ label.setBackground(Color.red); } }); }
- 到窗体设计界面关联的界面类中创建方法 createUIComponents()
- 在方法体里手动调用自定义组件的非默认构造函数即可
-
import javax.swing.*; public class Demo { private JPanel panel1; private M_Button m_Button1; private void createUIComponents(){ m_Button1 = new M_Button("title"); } }
宝贝儿们再见,有什么问题评论区留言或者私信哦。