I'm learning game development in Java. Here are 2 ways I've learned to initialize a JPanel attached to a JFrame. What are the differences between the two, and which one would be more correct?
Note that in Method 1, Skeleton does not extend JFrame. In Method 2 it does.
Method 1:
Board.java
public class Board extends JPanel {
public Board() {
setPreferredSize(new Dimension(300, 280));
}
}
Skeleton.java
public class Skeleton {
public static void main(String[] args) {
JFrame window = new JFrame("Skeleton");
window.setContentPane(new Board());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);
}
}
Method 2:
Board.java
public class Board extends JPanel {
public Board() {}
}
Skeleton.java
public class Skeleton extends JFrame {
public Skeleton() {
add(new Board());
setTitle("Skeleton");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 280);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
}
public static void main(String[] args) {
new Skeleton();
}
}
Basically, if you want your skeleton class to only be a JFrame, you'll be fine extending it. If you want it to have other functions, you'll want to have the class contain the JFrame object, as in your 'method 1'. Both methods will work the same (in terms of operating as a JFrame object), but it is a matter of what you want to do in the application. Extending JFrame will limit what you can do (i.e. calling certain methods), but if it is solely functioning as a JFrame, that won't matter anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With