Veröffentlicht 19. September 200817 j Hallo. Ich versuch gerade die Syntax und Hintergründe des ActionListeners zu verstehen, damit ich ihn einsetzen kann. Dazu habe ich mir folgendes Programm geschrieben, ganz simpel und doch versteh ich die Fehlermeldung nicht! import java.awt.*; import javax.swing.*; import java.awt.event.*; public class MyAL { public static void main(String[] args) { JFrame frame = new JFrame("FFS"); frame.setSize(200,100); frame.setVisible(true); frame.setLayout(new FlowLayout()); JButton b1 = new JButton("Hallo"); JButton b2 = new JButton("Test"); frame.add(b1); frame.add(b2); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println(e.getSource()); if (e.getSource() == b2) { System.out.println("Hallo-Button pressed!"); } else if (e.getSource() == b1) { System.out.println("Test-Button pressed!"); } } }; b1.addActionListener(al); b2.addActionListener(al); } } Er sagt mir dann, dass: Exception in thread "main" java.lang.Error: Unresolved compilation problems: Cannot refer to a non-final variable b2 inside an inner class defined in a different method Cannot refer to a non-final variable b1 inside an inner class defined in a different method at MyAL.main(MyAL.java:22) Kann mir da evtl jmd etwas auf die Sprünge helfen?? Danke && Gruß starbuck1 Bearbeitet 19. September 200817 j von starbuck86
19. September 200817 j Ok, ich habs: Die Objekte sind nicht final, wusste nicht dass "final JButton blubb = new..." funktioniert.
Archiv
Dieses Thema wurde archiviert und kann nicht mehr beantwortet werden.