Hello! I have such a task: you need to write a program in the Eclipse environment so that all event handling (keystroke, button on form) is in one class, and all work with the interface is in another. To explain the problem, wrote a simple program Tes: here it is.

import java.awt.event.*; public class Ecouter extends Fenetre implements ActionListener { public void actionPerformed(ActionEvent e) { Fenetre.monButton1.setName("name"); } } import javax.swing.*; import java.awt.*; public class Fenetre { public JButton monButton1; public static void main(String [] args) { Fenetre InterfaceGraphique = new Fenetre(); InterfaceGraphique.dessine(); } public void dessine() { JFrame fenetre = new JFrame ("Exemple d'interface"); JButton monButton1 = new JButton("Bouton1"); monButton1.addActionListener(new Ecouter()); fenetre.getContentPane().add(monButton1); fenetre.pack(); fenetre.setVisible(true); } } 

The meaning of the program is that when you click a button on a form, the name of the button should change, but the program hangs instead. A possible problem is that I do not correctly use the inheritance mechanisms: extends Fenetre, but without it I do not know how to get access from one class to the fields of another class so that they can be changed. Thanks in advance for the answers.

  • monsieur You are a mean liar:> I wrote a simple program called Test. I doubt very much that when studying programming, I gave a French name to variables and classes - jmu
  • 2
    I’m going through practice in France>; -> - stream2006
  • Good advice: if you know that your code will be \ people who do not know French can look - let's give the names in English. Sometimes it does not deliver the code in an unknown language, especially with comments on it>. < - Viacheslav
  • one
    my cant, first posted, then looked - stream2006

1 answer 1

The error is that you pass a new instance of the class to the handler, in whose parent monButton1 is not initialized, you should do something like this (without dancing with the parent):

 import java.awt.event.*; public class Ecouter implements ActionListener { private JButton monButton; public Ecouter(JButton monButton) { this.monButton=monButton; } public void actionPerformed(ActionEvent e) { monButton.setName("name"); } } import javax.swing.*; import java.awt.*; public class Fenetre { public JButton monButton1; public static void main(String [] args) { Fenetre InterfaceGraphique = new Fenetre(); InterfaceGraphique.dessine(); } public void dessine() { JFrame fenetre = new JFrame ("Exemple d'interface"); JButton monButton1 = new JButton("Bouton1"); monButton1.addActionListener(new Ecouter(monButton1)); fenetre.getContentPane().add(monButton1); fenetre.pack(); fenetre.setVisible(true); } } 
  • 1 post = 1 question - follow the rules. Post a question - Barmaley