Zerox029 Zerox029 - 22 days ago 6
Java Question

Subclass not inheriting parent class fields

I have a subclass but the problem is that for some reason, it doesn't inherit the main class' fields. I've tried making the public instead of private (even though you're supposed to be able to access private fields from subclasses anyway) but even that didn't work.

package com.testfoler;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Fenetre extends JFrame{

private Panneau pan = new Panneau();
public JButton bouton = new JButton("Go");
public JButton bouton2 = new JButton("Stop");
private JPanel container = new JPanel();
private JLabel label = new JLabel("Le JLabel");

public Fenetre(){
this.setTitle("Animation");
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);

container.setBackground(Color.white);
container.setLayout(new BorderLayout());
container.add(pan, BorderLayout.CENTER);
bouton.addActionListener(new BoutonListener());
bouton.setEnabled(false);
bouton2.addActionListener(new Bouton2Listener());

JPanel south = new JPanel();
south.add(bouton);
south.add(bouton2);
container.add(south, BorderLayout.SOUTH);
Font police = new Font("Tahoma", Font.BOLD, 16);
label.setFont(police);
label.setForeground(Color.blue);
label.setHorizontalAlignment(JLabel.CENTER);
container.add(label, BorderLayout.NORTH);
this.setContentPane(container);
this.setVisible(true);
}
}
//Those are the subclasses
class BoutonListener implements ActionListener{
public void actionPerformed(ActionEvent arg0) {
bouton.setEnabled(false);
bouton2.setEnabled(true);
}
}

class Bouton2Listener implements ActionListener{
public void actionPerformed(ActionEvent e) {
bouton.setEnabled(true);
bouton2.setEnabled(false);
}
}

Answer

You marked the fields as private, thus they cannot be inherited.

Futhermore, these "subclasses" don't extend your Fenetre class. Pay attention.

Should be:

class BoutonListener extends Fenetre implements ActionListener 

instead of:

class BoutonListener implements ActionListener 

in both cases.