I have been working on how to use JPanels within a Jframe. It is quite confusing for me in the beginning as I had no idea how to start and what to import or initialize. After a while I decided to create a simple class to test Jframes and JPanels
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javarefresher;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author Samuel Tambunan
*/
public class UsingFrames {
public static void main(String []args) {
System.out.println("Hoi");
MyFrame mf = new MyFrame();
MyPanel mp = new MyPanel();
mf.add(mp);
mf.pack();
mf.setLocationRelativeTo(null);
mf.setVisible(true);
}
}
class MyFrame extends JFrame {
public MyFrame() {
/*MyPanel mp = new MyPanel();
add(mp);
pack();
setLocationRelativeTo(null);
setSize(300,200);
setVisible(true);
*/
}
}
class MyPanel extends JPanel {
public MyPanel(){
JButton ok = new JButton("OK");
add(ok);
}
}
the simple java class above demonstrates how to use a Jpanel and a JFrame if it is being called from a third separate class. One thing I noticed when doing this is that the mf.pack() must be called or otherwise the buttons will not show up properly. The method, is inherited from the Windows Java API and essentially "causes the frame window and its object to fit the preferred size and layout". It is also important to show the frame by giving the command "mf.setVisible(true)" or otherwise it will be empty.
My next step will be to try to create a Jpanel and Jframe using Netbeans and then packing them together. This will be considerably harder as the positioning of the panels is what is causing me to get headaches at the moment.
No comments:
Post a Comment