Question

The problem I have is that I want to make a generic code block of code. The getHalfDotTime method and getHalfTime method are two of many many similar methods.

I do not want to create a new ActionListener for every single method and instead I want to create the ActionListener within the commonFormatting method.

The problem I am running into when I do this is that the Declarations.halfDotTime double variable can not be contained as a local double for example.

I wanted double currentTitle = Declarations.halfDotTime and then in the ActionListener setText to currentTitle. This problem created was that as the program runs through it sets current title to the INIT value of 0 and then stays as 0 when the button is pressed.

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);
Was it helpful?

Solution

You need to pass commonTitle as a new extra method parameter to commonFormatting. Your commonTitle variables are local variables, which means they are only visible inside the method they are declared in.

Polymorphism and encapsulation have nothing to do with why the code does not compile. Indeed, you are not using polymorphism, which might be a good way to solve this problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top