gpt4 book ai didi

java - 如何在java中创建没有额外方法的自定义组件?

转载 作者:行者123 更新时间:2023-11-30 07:41:04 25 4
gpt4 key购买 nike

我已经为 Labels 创建了自定义类,它工作正常,但我想要的是。每当我从该类创建实例时,必须创建标签而不需要额外的可返回方法。

请看我的代码

class  CustomLabel {

private JLabel customLabel;

public CustomLabel() {
createLabel();
}

private void createLabel() {
customLabel = new JLabel("Label test");
}

/*
i do not want to return this
*/
public JLabel getLabel() {
return customLabel;
}

}

class Booter {

/*
calling customLabel
*/
void createUI() {
CustomLabel customLabel = new CustomLabel();

JPanel jPanel = new JPanel();

// this is not working
jPanel.add(customLabel);
// but if i call extra method that inside customLabel
// it works fine but i do not want it
jPanel.add(customLabel.getLabel());
//i need to do same like java defined component like.
JLabel label = new JLabel("Test2");
jPanel.add(label); // its is not required getLabel or others
}
}

最佳答案

如果您想使用它的构造函数直接创建它,您可以扩展类 JLabel:

import javax.swing.JLabel;

public class CustomLabel extends JLabel {

public CustomLabel(String text) {
super(text);
}
}

然后在您的调用代码中,您可以这样做:

class Booter {

void createUI() {
CustomLabel customLabel = new CustomLabel("TEST TEXT");

JPanel jPanel = new JPanel();
JLabel label = new JLabel("Test2");
jPanel.add(customLabel);
jPanel.add(label);
}
}

关于java - 如何在java中创建没有额外方法的自定义组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56588041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com