【问题标题】:Java create JLabel with a custom methodJava 使用自定义方法创建 JLabel
【发布时间】: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”是什么意思。 “名字”是什么意思?我希望你不是在谈论变量名,是吗?

标签: java swing methods jlabel


【解决方案1】:

基本上你的问题是无法完成的,或者至少是你似乎在想的方式。您可以使用数组来存储新创建的标签,或者将它们存储在 Map 中,但本质上,您需要一个可以将它们吐出的工厂方法

public JLabel createButton(int x, int y, String text) {
    JLabel btnA = new JLabel("A");
    //...
    return btnA;
}

然后你可以将它们存储在数组中......

public class ... {
    //...
    private JLabel[] labels = new JLabel[26];
    //...

    protected void someMethodThatYouCall() {
        // Probably some kind of loop
        labels[indexOfNextLabel] = createButton(x, y, text);
    }
}

或者你可以使用某种Map

public class ... {
    //...
    private Map<JLabel> labels = new HashMap<JLabel>();
    //...

    protected void someMethodThatYouCall() {
        // Probably some kind of loop
        labels.put(text, createButton(x, y, text));
    }
}

恕我直言,JLabel 对于您似乎正在尝试做的事情来说是一个糟糕的选择。某种JButton 会是更好的选择,因为它们已经内置了翻转支持以及所有用户交互功能

【讨论】:

    猜你喜欢
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多