-1

我遇到的问题是我想制作一个通用的代码块。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);
4

1 回答 1

1

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

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

于 2013-11-08T19:35:34.787 回答