Tuesday 14 November 2017

java - Design JFrame with mounting multiples JPanels?

itemprop="text">

I'm new java GUI developer and I have
a question.



Is possible to create a Jframe with
multiples Jpanels? My idea is create a class with the components added in the JPanel and
from another class create the JFrame adding multiples objects of the JPanel
Class.




At the moment I'm doing
test:



public class Principal
{

private JFrame window;

public
Principal(){

window = new JFrame("Principal");

}


/**
* @return the finestra

*/
public JFrame getFinestra() {
return window;

}
}`



Child
Class



public class
Childs {

private JPanel panel;
private JLabel
text1;

public Childs(){
panel = new
JPanel();
text1 = new JLabel();



text1.setText("TEXT");
panel.add(text1);
}


/**
* @return the panel
*/
public JPanel getPanel()
{
return panel;


}
}


TestFrame
Class



public class
TestFrame {

/**
* @param args the command line
arguments

*/
public static void main(String[] args)
{

Principal p = new Principal();
Childs c = new
Childs();
Childs c2 = new Childs();


p.getFinestra().add(c.getPanel());

p.getFinestra().add(c2.getPanel());

p.getFinestra().setVisible(true);


}
}
`


Answer




It is certainly possible to have multiple
JPanels in a JFrame. You can get the component Container from
the JFrame with getContentPane(), which in your example would
work as



p.getFinestra().getContentPane();



To
understand how to place your JPanels to the
JFrame, you should study some Layouts.
Here is a good resource and this site has many more: href="https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html"
rel="nofollow">https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html



For
example to use a FlowLayout (the default
one)



p.getFinestra().getContentPane().setLayout(new
FlowLayout());
p.getFinestra().getContentPane().add(c);
p.getFinestra().getContentPane().add(c2);

//It
is also a good habit to call pack() before setting to
visible
p.getFinestra().pack()

p.getFinestra().setVisible(true);


And
as a short lesson in English, the plural of child is
children.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...