import java.awt.*; import java.awt.event.*; import javax.swing.*; class TrippButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("Tripp!"); } } // class TrippButtonListener public class BoringWindow { private int bwx = 1; private class TrappButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("Trapp!"); System.out.println("bwx = " + bwx); } } // class TrappButtonListener public BoringWindow() { int kx = 2; final int fkx = 3; class TrullButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("Trull!"); System.out.println("bwx = " + bwx); // Ger kompileringsfel // local variable kx is accessed from within inner class; needs to be declared final // System.out.println("kx = " + kx); System.out.println("fkx = " + fkx); } } // class TrullButtonListener JFrame frame = new JFrame("Ett tråkigt fönster"); frame.setSize(350, 50); Container cp = frame.getContentPane(); cp.setLayout(new GridLayout(1, 4)); JButton trippknapp = new JButton("Tripp!"); JButton trappknapp = new JButton("Trapp!"); JButton trullknapp = new JButton("Trull!"); JButton hejsanknapp = new JButton("Hejsan!"); cp.add(trippknapp); cp.add(trappknapp); cp.add(trullknapp); cp.add(hejsanknapp); trippknapp.addActionListener(new TrippButtonListener()); trappknapp.addActionListener(new TrappButtonListener()); trullknapp.addActionListener(new TrullButtonListener()); hejsanknapp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.out.println("Hejsan!"); System.out.println("bwx = " + bwx); // Ger kompileringsfel // local variable kx is accessed from within inner class; needs to be declared final // System.out.println("kx = " + kx); System.out.println("fkx = " + fkx); } }); frame.setVisible(true); } // BoringWindow public static void main(String[] args) { final BoringWindow b = new BoringWindow(); int mx = 4; final int fmx = 5; class UnusedButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("Impossible!"); // Ger kompileringsfel // non-static variable bwx cannot be referenced from a static context // System.out.println("bwx = " + bwx); System.out.println("b.bwx = " + b.bwx); // Ger kompileringsfel // local variable mx is accessed from within inner class; needs to be declared final // System.out.println("mx = " + mx); System.out.println("fmx = " + fmx); } } // class TrullButtonListener // Ger kompileringsfel // non-static variable this cannot be referenced from a static context // new TrappButtonListener(); new TrippButtonListener(); // Ger kompileringsfel // cannot resolve symbol // new TrullButtonListener(); new UnusedButtonListener(); } // main } // class BoringWindow