【问题标题】:How would I reference a double value without making a new object? [closed]如何在不创建新对象的情况下引用双精度值? [关闭]
【发布时间】:2013-11-08 19:18:52
【问题描述】:

我的问题是我想制作一个通用的代码块。 getHalfDotTime 方法和 getHalfTime 方法是许多类似方法中的两种。

我不想为每个方法都创建一个新的 ActionListener,而是想在 commonFormatting 方法中创建 ActionListener。

当我这样做时遇到的问题是,Declarations.halfDotTime 双变量不能包含为例如本地双变量。

我想要 double currentTitle = Declarations.halfDotTime 然后在 ActionListener setText 到 currentTitle。产生的这个问题是,当程序运行时,它将当前标题设置为 INIT 值 0,然后在按下按钮时保持为 0。

private static void gethalfDotTime(JButton tapButton, JPanel contentPane) {
        final JLabel currentLabel = new JLabel("0ms");
        currentLabel.setBounds(119, 185, 120, 16);

    tapButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            currentLabel.setText(Declarations.threeDecimals.format(Declarations.halfDotTime) + "ms");
        }
    }); 
        commonFormatting(tapButton, contentPane, currentLabel);
    }

private static void gethalfTime(JButton tapButton, JPanel contentPane) {
        final JLabel currentLabel = new JLabel("0ms");
        currentLabel.setBounds(119, 185, 120, 16);

    tapButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            currentLabel.setText(Declarations.threeDecimals.format(Declarations.halfTime) + "ms");
        }
    }); 
        commonFormatting(contentPane, currentLabel);
    }

//MANY MORE SIMILAR METHODS ALL CALLING COMMON FORMATTING.



private static void commonFormatting(JPanel contentPane, final JLabel currentLabel) {

    currentLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    currentLabel.setForeground(new Color(255, 255, 255));
    currentLabel.setFont(new Font("Letter Gothic Std", Font.BOLD, 14));
    contentPane.add(currentLabel);

【问题讨论】:

  • 这个问题似乎是题外话,因为它是关于审查代码,因此应该在Code Review
  • 这不是评论,而是问题。我现在已经解决了它,如果它被解锁,我会发布解决方案。我也改写了这个问题,因为它一团糟!我向所有人道歉!
  • 当然,经过您的编辑,它看​​起来会更好。在你看起来真的想改进你的代码风格之前。

标签: java oop polymorphism double encapsulation


【解决方案1】:

您需要将commonTitle 作为新的额外方法参数传递给commonFormatting。您的 commonTitle 变量是局部变量,这意味着它们仅在声明它们的方法中可见。

多态和封装与为什么代码不能编译无关。实际上,您没有使用多态性,这可能是解决此问题的好方法。

【讨论】:

  • 我这样做了。这段代码不是我在stackoverflow中重建的直接副本。那没有用,问题是如果我不为每种方法都创建一个新的动作侦听器。单击时该值不会更新,因为在 commonFormatting 之前调用了该值。并且保持静态值 0
  • 好的,你让我生气了,我将投票结束这个问题。这里有很多问题:你的评论没有提供足够的细节,你没有提供真实的代码,而是用假代码浪费了我的时间,你似乎不知道你在说什么。
  • 好的罗宾,我很抱歉让你生气。这段代码让我一团糟。你实际上帮助了我,所以我要标记你是对的。对不起,我的问题到处都是。我需要实现多态性。我现在在一个名为 currentTitle 的单独类中有一个公共字段,而不是从 ActionListener Declarations.halfDotTime 我实际上从设置值的类调用这个 HalfDotTime.currentTitle = ((60000/timeValue)*3); (命名课程有助于我在拥有大约 30 个 currentTitles 的同时保持其井井有条)如果消息被解锁,我将发布我的解决方案!
猜你喜欢
  • 1970-01-01
  • 2012-04-14
  • 2021-12-20
  • 1970-01-01
  • 2014-06-09
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
相关资源
最近更新 更多