@Axeles
Нечего тут пока писать

В чём ошибка ActionListener?

Заранее извиняюсь, вернулся к изучению Java, и сразу застрял на простом примере и не как не могу разобраться в чём данная ошибка заключается. Понимаю что не красиво написать код и просить в нём разобраться но в данной ситуации как мне кажется нет другого выхода. Подскажите что почитать по этому поводу и как избежать подобной ошибки.
public class OOP {
	public static void main(String[] args) {
		
		
		JFrame frame = new JFrame();
		frame.setSize(400, 500);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLocationRelativeTo(null);
		frame.setLayout(new GridBagLayout());

		JTextField textf = new JTextField();
		JTextField textf2 = new JTextField();
		JButton Mybutton = new JButton("Start");
		
		
		
		frame.add(textf, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.9,
				GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
				new Insets(2, 2, 2, 2), 0, 0));

		frame.add(textf2, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.9,
				GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
				new Insets(2, 2, 2, 2), 0, 0));

		frame.add(Mybutton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.9,
				GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
				new Insets(1, 2, 2, 2), 0, 0));
		
		Mybutton.addActionListener(new ButtonActionListener()); // Ошибка

		frame.setVisible(true);
		frame.pack();
		
		
	}
	
	
	public class ButtonActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
          JOptionPane.showMessageDialog(null, "Messege box");
			
		}
		
	}
}

Как следствие слушатель не работает.
fec2a82e8ae64d13a3ba07d094395b74.JPG
Видимо я делаю ошибки в концепции ООП но понять какую именно не могу. Пример беру из видео уроков, и как раз там то всё прекрасно
  • Вопрос задан
  • 3038 просмотров
Решения вопроса 1
@EdmunD
Java Программист
Проблема в том что static код который выполняется в методе public static void main не может получит доступ к не статичному внутреннему классу. Либо сделайте класс public static class ButtonActionListener implements ActionListener, либо перенесите основной код в нестатичный метод
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@asd111
Как вариант можно сделать ButtonActionListener package-private классом

public class OOP {
  public static void main(String[] args) {
    
    JFrame frame = new JFrame();
    frame.setSize(400, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setLayout(new GridBagLayout());

    JTextField textf = new JTextField();
    JTextField textf2 = new JTextField();
    JButton Mybutton = new JButton("Start");
    
    frame.add(textf, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.9,
        GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
        new Insets(2, 2, 2, 2), 0, 0));

    frame.add(textf2, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.9,
        GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
        new Insets(2, 2, 2, 2), 0, 0));

    frame.add(Mybutton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.9,
        GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
        new Insets(1, 2, 2, 2), 0, 0));
    
    Mybutton.addActionListener(new ButtonActionListener()); // Ошибка

    frame.setVisible(true);
    frame.pack();   
  } 
}

class ButtonActionListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
          JOptionPane.showMessageDialog(null, "Messege box");      
    }
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы