I have a little bit of a problem here with MouseListeners. I am trying to add multiple JLabels to a JFrame and that works perfectly fine. The problem is that I also want to add MouseListeners to each of the JLabels. But it doesn't want to work this way, because it is complaining about the variable not being final. Can anyone help me with this?
It is complaining at the part inside the mouseEntered and the mouseExited functions. In eclipse the variable button there gets highlighted and it says the variable needs to be a final variable.
The code:
public class OperatingScreen {
public String ride;
public static JFrame frame = new JFrame();
private static JPanel panel = new JPanel();
private static JPanel button_panel = new JPanel();
private static JLabel bg = new JLabel();
public OperatingScreen(String ride){
this.ride = ride;
frame.setTitle("Operating: " + ride);
panel.setLayout(null);
frame.add(panel);
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
frame.setVisible(true);
bg.setIcon(createImageIcon("/background_operating.png", "background"));
bg.setBounds(1280, 720, 0, 0);
frame.add(bg);
//buttons.setBounds(100, 500, 1080, 40);
frame.setSize(1280, 720);
SocketHandler.initializeride(ride);
}
public void Initialize(String init){
String buttons2 = init.split("\\*")[1];
String[] buttons = buttons2.split("\\|");
for(int i = 2; i < buttons.length; i++){
String text = buttons[i].split("\\>")[0];
String color = buttons[i].split("\\>")[1].substring(0, 1).toUpperCase() + buttons[i].split("\\>")[1].substring(1);;
JLabel button = new JLabel();
button.setIcon(createImageIcon("/Button" + color + ".png", "blue"));
button.setText(text);
button.setForeground(Color.BLACK);
button.setFont(button.getFont().deriveFont(17.0f));
button.setBorder(LineBorder.createBlackLineBorder());
button_panel.add(button);
button.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {
//button.setIcon(createImageIcon("/Button" + color + ".png", "choose"));
}
public void mouseExited(MouseEvent arg0) {
//button.setIcon(createImageIcon("/Button" + color + ".png", "choose"));
}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
});
JOptionPane.showMessageDialog(HomeScreen.frame, text + " " + color);
}
JScrollPane jop = new JScrollPane(button_panel, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jop.setBounds(100, 500, 1080, 60);
jop.setBorder(null);
panel.add(jop);
jop.setOpaque(false);
jop.getViewport().setOpaque(false);
panel.setSize(1280, 720);
panel.setOpaque(false);
button_panel.setOpaque(false);
}
protected ImageIcon createImageIcon(String path,
String description) {
URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}