【发布时间】:2017-11-03 20:29:35
【问题描述】:
我想创建26个类似的JLabel,唯一的区别是位置和文本,所以我想用一个方法来做。 如何使用字符串中的名称创建 JLabel? 我想使用字符串中的名称创建一个 JLabel,因为如果我对所有 JLabel 使用相同的名称,它将覆盖我之前创建的 JLabel。 这是我所拥有的:
public void CreateButton(int x, int y, String text) {
JLabel btnA = new JLabel("A");
btnA.setIcon(new ImageIcon(getClass().getResource("/Btn.png")));
btnA.setSize(40, 40);
btnA.setLocation(x, y);
btnA.setHorizontalTextPosition(JLabel.CENTER);
btnA.setVerticalTextPosition(JLabel.CENTER);
try {
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("MorePerfectDOSVGA.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f);
} catch (IOException |FontFormatException e) {
e.printStackTrace();
}
btnA.setFont(new Font("More Perfect DOS VGA", Font.PLAIN, 40));
btnA.setForeground(Color.WHITE);
btnA.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent e) {
btnA.setIcon(new ImageIcon(getClass().getResource("/BtnHover.png")));
btnA.setForeground(Color.YELLOW);
}
public void mouseExited(java.awt.event.MouseEvent e) {
btnA.setIcon(new ImageIcon(getClass().getResource("/Btn.png")));
btnA.setForeground(Color.WHITE);
}
public void mouseClicked(java.awt.event.MouseEvent e) {
//Button Action
}
});
我想使用 CreateButton 方法中的字符串“text”来替换 btnA 和
JLabel 内容
【问题讨论】:
-
你的尝试在哪里?
-
欢迎来到 SO。请向我们展示您已经写的内容,并详细说明您的意图是什么,因为从您提供的少量上下文中很难知道您真正想要什么
-
@LonelyNeuron 编辑了我的帖子
-
似乎您应该使用数组而不是尝试动态创建变量名(顺便说一句,这不起作用)。
-
感谢您的更新。我仍然不知道“如何使用字符串中的名称创建 JLabel”是什么意思。 “名字”是什么意思?我希望你不是在谈论变量名,是吗?