I have this sample code below where it inherits from JFrame and thus my add()
method is inherited from the container(JPanel
). I would like to know the following:
Why do we call an instance for the following methods:
fc.setSize(280,125); // width and height
fc.setResizable(false);
fc.setLocationRelativeTo(null);
fc.setVisible(true);
We inherit all of these methods so i naively tried to call them without creating objects and using them as instances but i obtained some errors complaining about non-static methods being referenced as a static context. I added them at the end of the constructor and i did not receive any problems. I would also really like to know in this case what is the benefit if any of calling an instance instead of calling the method directly. Its not like we have multiple frames so i don't see the use of creating objects.
code:
import java.awt.FlowLayout;
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.JTextField;
public class FC2 extends JFrame {
JTextField ftext, ctext;
JButton f2c, c2f;
public FC2(String title) {
super(title);
JLabel f = new JLabel("Fahrenheit");
JLabel c = new JLabel("Celsius");
ftext = new JTextField(5);
ctext = new JTextField(5);
f2c = new JButton(">>>");
c2f = new JButton("<<<");
setLayout(new FlowLayout(FlowLayout.LEFT,10,10));
add(f);
add(f2c);
add(c);
add(ftext);
add(c2f);
add(ctext);
ActionListener bl = new ButtonListener(this);
// anonymous class for ActionListener parameter
f2c.addActionListener(bl);
c2f.addActionListener(bl);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame fc = new FC2("F2C Converter");
fc.setSize(280,125); // width and height
fc.setResizable(false);
fc.setLocationRelativeTo(null);
fc.setVisible(true);
}
}
class ButtonListener implements ActionListener {
FC2 frame;
public ButtonListener(FC2 frame) {
this.frame = frame;
}
public void actionPerformed(ActionEvent e) {
// get at button label
String label = e.getActionCommand();
if (label.equals("<<<")) { // c2f
String cstr = frame.ctext.getText();
float c = Float.parseFloat(cstr);
float f = c*9/5+32;
String fstr = String.format("%4.1f", f);
frame.ftext.setText(fstr);
} else {
String fstr = frame.ftext.getText();
float f = Float.parseFloat(fstr);
float c = (float)((f-32)*5/9.0);
String cstr = String.format("%4.1f", c);
frame.ctext.setText(cstr);
}
}
}
You should read about the differences of static
and non-static
methods - the methods you are inheriting are only valid in non-static
context whilst your main
-method is in static
context. Don't mix these two things up!