I've been a lurker on stackoverflow for some time. I'm teaching myself Java, so bear with me if this is a rather elementary question (I couldn't find the answer on here though).
If I have a java class (like the one below), which I wish to use in future classes in a slightly different way (e.g. changing the button text/or output), is there a way to do this by extending the original class?
In the case below I have a JFrame with two buttons which print different text to the console. I simply want to extend this class whilst changing one of the button names.
ORIGINAL CLASS:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FrameIt extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
new FrameIt().setVisible(true);
}
public FrameIt() {
super("Make a choice");
setSize(600, 600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout());
JButton button = new JButton("Click Me.");
JButton button2 = new JButton("No, you should Click Me!");
button.addActionListener(this);
button2.addActionListener(this);
add(button);
add(button2);
}
@Override
public void actionPerformed(ActionEvent e) {
String name = e.getActionCommand();
if(name.equals("Click Me")){
System.out.println("That was actually the right choice.");
}else{
System.out.println("Poor choice.");
}
}
}
CLASS THAT EXTENDS:
import javax.swing.JButton;
public class Alterations extends FrameIt{
private static final long serialVersionUID = 1L;
public static void main(String args[]){
new Alterations().setVisible(true);
System.out.println("Doing it");
}
public Alterations(){
JButton button2 = new JButton("Slightly different button");
}
}
Thanks.