[英]How do I create JLabels (or other elements) without repeating code?
I searched for a while and couldn't find anything about this. 我搜索了一会儿,找不到任何有关此的信息。 Say for instance I would be creating a lot of JLabels, but instead of retyping everything for every JLabel, I could have a method that would allow me to input what I wanted and have it create them for me. 举例来说,我将创建很多JLabel,但是不必为每个JLabel重新键入所有内容,而是可以使用一种方法,让我输入想要的内容并为我创建它们。 How would I go about doing that? 我将如何去做? I have a small example of what I mean below. 我下面有一个小例子。
private JLabel LabelBuilder(JLabel label, String text, int x, int y, int width, int height)
{
label = new JLabel(text);
label.setBounds(x, y, width, height);
label.setOpaque(true);
label.setBackground(Color.WHITE);
label.setHorizontalAlignment(SwingConstants.CENTER);
window.add(label);
}
public void SetupElements()
{
LabelBuilder(labelName, "Text", 10, 10, 200, 20);
}
How would I go about returning it? 我将如何退货? Is there a more efficient way than this? 有没有比这更有效的方法? Thanks in advance! 提前致谢!
To answer How would I go about returning it? 要回答我将如何退货?
private void setupElements()
{
JLabel aLabel = labelBuilder("Text", 10, 10, 200, 20);
}
//No need for a `JLabel label` argument.
//Method names start with lower case. see: https://www.geeksforgeeks.org/java-naming-conventions/
private JLabel labelBuilder(String text, int x, int y, int width, int height)
{
JLabel label = new JLabel(text);
//setting bounds is not recommended. Instead the parent container (window) needs
//to implemenent layout manager. See https://docs.oracle.com/javase/tutorial/uiswing/layout/layoutlist.html
label.setBounds(x, y, width, height);
window.add(label);
return label;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.