Pages

Wednesday, November 4, 2015

how to create a jpanel in java

  Assalam-o-alaikum (warahmatullahi.wabarakatuhuu)               
  
                                  JPanel in Java

adding panel in the main function


package myPackage;

import javax.swing.JFrame;


/*JPanle import below
 make sure to import 
 */
import javax.swing.JPanel;


public class myClass{

 public static void main(String[]args){

 JFrame frame = new JFrame();


 /*create a JPanel object Here*/


JPanel panel = new JPanel();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setTitle("create Jpanel");

frame.setVisible(true);

frame.setSize(450, 500);


panel.add(frame);

}

}
and if you run so it would look like







adding panel in a separate classes in a method

this is the main class



package myPackage;

public class myMain {
 public void main(String[]args){
myClass clas = new myClass();
 }
}



now this is the class for methods to add JPanel into a frame



package myPackage;

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class myClass {

/*create a Jframe here*/

JFrame frame = new JFrame();

/*create a JPanel here*/

JPanel panel = new JPanel();

public myClass() {
frame();
}
public void frame(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setTitle("create Jpanel");

frame.setVisible(true);

frame.setSize(450, 500);
/*join both together
* cause we are call 
* this mehtod in
* the constructer
* so call the panel
*  method
*/
panel();
}
public void panel(){
 
panel.setBackground(Color.black);
frame.add(panel);

}

}



and the same result



No comments:

Post a Comment