Search code examples
javaswingactionlistenerfinal

Changing JButton Text or color without final?


Hey all I can change the text of 1 single button easily with "final" but I need to create lots of buttons for a flight booking system, and when the buttons are more, final doesnt work ...

JButton btnBookFlight;

eco = new EconomyClass();
eco.setSeats(5);
for(int i=0;i<20;i++){
    btnBookFlight = new JButton("Book" +i);
    btnBookFlight.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            btnBookFlight.setBackground(Color.RED);
            btnBookFlight.setOpaque(true);
            btnBookFlight.setText("Clicked");
        }
    });
    btnBookFlight.setBounds(77, 351, 100, 23);
    contentPane.add(btnBookFlight);
} 

I would be glad if you can suggest me any trick to get over this.I want to change a buttons color or text when it is clicked or maybe some other cool effects when mouse over but for now only text or color will be enough =).Thanks for your time!


Solution

  • Use the source of the ActionEvent in the ActionListener

    btnBookFlight.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
    
          JButton button = (JButton)event.getSource();
          button.setBackground(Color.RED);
          ...
        }
    });
    

    btnBookFlight has to be final for the inner class (ActionListener) to access it.

    From JLS 8.1.3

    Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

    If this is not permitted, then the JButton may be accessed using the source component of the ActionEvent itself using getSource.

    However, that said, the simplest solution would be to move the JButton declaration within the scope of the for loop and make it final:

    for (int i = 0; i < 20; i++) {
        final JButton btnBookFlight = new JButton("Book" + i);
        btnBookFlight.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                btnBookFlight.setBackground(Color.RED);
                ...
            }
        });
    }