Including a panel from external java file? - java

Is it possible to include a jpanel into an container from another java file? Let suppose I have 2 java files fileA.java and fileB.java. And I want to add the entire display content of fileB.java inside a container in fileA.java. Is this possible? Just a confusion running in for a very long time. Thanks in advance.

You could make the other file/cass extends JPanel and then since it is a JPanel, you can add it to any other file. For example:
FileA.java
public class FileA {
public FileA() {
JFrame jf = new JFrame();
jf.setLayout(new BorderLayout());
FileB b = new FileB();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setBounds(100,100,800,600);
jf.setVisible(true);
add(b, BorderLayout.CENTER);
}
public static void main(String[] args) {
new FileA();
}
}
FileB.java
public class FileB extends JPanel {
public FileB() {
setLayout(new BorderLayout());
add(new JLabel("Example"), BorderLayout.CENTER);
}
}
Or you can simply have a JPanel be a field in another file and access it with a getter method.
Example:
FileC.java
public class FileC {
private JPanel panel;
public FileC() {
panel = new JPanel();
panel.add(new JLabel("Example 2"));
}
public JPanel getPanel() {
return panel;
}
}

Yes, you can.
1- If fileB class extends JPanel, then create an instance of fileB and add it to whatever container you have:
fileB panel = new fileB();
container.add(panel);
2- If fileB has a JPanel as a field, then you need to access it either by itself if it's public field, or by a getter method otherwise:
fileB f = new fileB();
JPanel panel = f.getPanel(); // or f.panel if the panel is a public field
container.add(panel);

Related

Setting an internal private panel opaque

Is there anyway i can set an internal private JPanel opaque? An example:
//Assuming I have no access rights to modify OuterPanel.java
class OuterPanel extends JPanel{
private JPanel internalPanel = new JPanel();
public OuterPanel(){
setLayout(new BorderLayout());
internalPanel.setOpaque(true);
add(internalPanel, BorderLayout.CENTER);
}
}
class MyClass{
private OuterPanel myPanel;
public MyClass(){
panel = new OuterPanel();
// is there anyway i can set myPanel's internalPanel to opaque(false)?
// assuming OuterPanel is a library and i have no way to modify it.
}
}
With the sample code above, assuming OuterPanel is a library class which I am unable to modify it's code, is there any way I could actually set it's internalPanel's opaque settings?
As mentioned by maloomeister. I used the following code to resolve this.
class OuterPanel extends JPanel{
private JPanel internalPanel = new JPanel();
public OuterPanel(){
setLayout(new BorderLayout());
internalPanel.setOpaque(true);
add(internalPanel, BorderLayout.CENTER);
}
}
class MyClass{
private OuterPanel myPanel;
public MyClass(){
panel = new OuterPanel();
setAllOpaque(panel.getComponents());
}
// This method is called recursively to set ALL JPanels
private void setAllOpaque(Component[] comp){
for (Component com : comp){
if (com instanceof JPanel){
JPanel p = (JPanel)com;
p.setOpaque(false);
setAllOpaque(p.getComponents());
}
}
}
}
I used recursion as this current example of OuterPanel is simple but my actual actual JPanel is actually a form filled with many different JPanels within it. This resolved it.
It might not be the most refined method, so if anyone has a better solution please do share! :)

How to add a panel class to my frame in main class

I am fairly new to oo, I have created a class which is most of the interface of my program, I have put it all together in a class. I then want to add my Panel class to my main class so my panels are attached to my Frame:
This is what I have tried, I am not receiving any errors, when I run my program but the panels are not displaying:
Panel Class:
public class PanelDriver extends JPanel {
public JPanel p1, myg;
public PanelDriver() {
JPanel p1 = new JPanel();
p1.setBackground(Color.CYAN);
// Graphicsa myg = new Graphicsa();
JTextArea txt = new JTextArea(5,20);
txt.setText("test");
p1.add(txt);
}
}
Main class:
public class GraphicMain {
public static void main(String[] args) {
JFrame frame = new JFrame("My Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
PanelDriver panels = new PanelDriver();
frame.getContentPane().add(panels);
GridLayout layout = new GridLayout(1,2);
}
you need a super call (because you extend JPanel you don't need to create a new one) and a layout in you Panel class like this:
public class CustomerTest extends JPanel {
public CustomerTest() {
super();
this.setBackground(Color.CYAN);
this.setLayout(new BorderLayout());
JTextArea txt = new JTextArea();
txt.setText("test");
this.add(txt);
this.setVisible(true);
}
}
and then in your main class use this, to set the frame visible and display the content. you have to set the layout for the frame after you created it:
JFrame frame = new JFrame("My Program");
GridLayout layout = new GridLayout(1, 2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
CustomerTest panels = new CustomerTest();
frame.getContentPane().setLayout(layout);;
frame.add(panels);
frame.setVisible(true);
Your PanelDriver class creates a p1 JPanel, but doesn't add it to anything.
At least add it to the PanelDriver itself :
this.add(p1);
Note that as your code is, the frame isn't even displaying, look at the answer by #XtremeBaumer to fix that part.

how to change a panel of CardLayout through another panel

In my program I have a wizard based layout. Implemented by CardLayout. So there is a set of classes that extend JPanels. I want to have buttons in each panel to navigate to other panels. fro example, when the program is showing panel one, I want to have a button to show panel 2.
I tired to create a method in main cardlayout panel holder so any other class can change the showing panel by this method, but it does not works and a stackoverflow error come up.
Here are my classes
Base Frame:
public class Base {
JFrame frame = new JFrame("Panel");
BorderLayout bl = new BorderLayout();
public Base(){
frame.setLayout(bl);
frame.setSize(800, 600);
frame.add(new LeftBar(), BorderLayout.WEST);
frame.add(new MainPanel(), BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new Base();
}
}
Main class that holds sub panels:
public class MainPanel extends JPanel {
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel() {
NewSession session = new NewSession();
ChooseSource chooseSource = new ChooseSource();
panelHolder.add(session, "Session");
panelHolder.add(chooseSource, "ChooseSource");
cl.show(panelHolder, "Session");
add(panelHolder);
}
public void showPanel(String panelIdentifier){
cl.show(panelHolder, panelIdentifier);
}
}
Sub panel 1
public class NewSession extends JPanel {
MainPanel ob2 = new MainPanel();
public NewSession(){
JButton newSessionBTN = new JButton("Create A New Session");
newSessionBTN.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
System.out.println("HI");
ob2.showPanel("ChooseSource");
}
});
add(newSessionBTN);
}
}
Sub panel 2
public class ChooseSource extends JPanel {
public ChooseSource(){
JLabel showMe = new JLabel("Show Me");
JButton back = new JButton("Back");
//MainPanel ob = new MainPanel();
back.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//ob.showPanel("start");
}
});
add(back);
add(showMe);
}
}
As you can see I have button in each sub panel and those buttons must show the other panel after clicking. In later they will also transfer the data from one to another.
ERROR:
Exception in thread "main" java.lang.StackOverflowError
at java.awt.Component.setFont(Component.java:1899)
at java.awt.Container.setFont(Container.java:1748)
at javax.swing.JComponent.setFont(JComponent.java:2751)
at javax.swing.LookAndFeel.installColorsAndFont(LookAndFeel.java:208)
at javax.swing.plaf.basic.BasicPanelUI.installDefaults(BasicPanelUI.java:66)
at javax.swing.plaf.basic.BasicPanelUI.installUI(BasicPanelUI.java:56)
at javax.swing.JComponent.setUI(JComponent.java:663)
at javax.swing.JPanel.setUI(JPanel.java:153)
at javax.swing.JPanel.updateUI(JPanel.java:126)
at javax.swing.JPanel.<init>(JPanel.java:86)
at javax.swing.JPanel.<init>(JPanel.java:109)
at javax.swing.JPanel.<init>(JPanel.java:117)
at InnerPanels.NewSession.<init>(NewSession.java:21)
at StrongBaseLayout.MainPanel.<init>(MainPanel.java:22)
The error is longer than this, by repeating last two lines.
How can I make it working?
Also I had another idea to have a next and previous buttons at the bottom of the page to switch panels. But am not sure which one is optimal. Any idea?
Whenever you see an unexpected StackOverflowError always look for the presence of inadvertent recursion, and in fact, that's exactly what you have going on here since MainPanel creates a NewSession object which then creates a new MainPanel object which then creates a new NewSession object which then creates a new MainPanel object .... repeating ad infinitum or until stack memory (hence the stack overflow) runs out.
here:
public class NewSession extends JPanel {
MainPanel ob2 = new MainPanel(); // *****
and here:
public class MainPanel extends JPanel {
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel() {
NewSession session = new NewSession(); // *****
Don't do that. Instead take care to create one and only one of each object. Use setter methods or constructor parameters to help you do this.
For example, change to this:
public class NewSession extends JPanel {
MainPanel ob2;
NewSession(MainPanel mainPanel) {
this.ob2 = mainPanel;
and this:
public class MainPanel extends JPanel {
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel() {
NewSession session = new NewSession(this);
Regarding:
Also I had another idea to have a next and previous buttons at the bottom of the page to switch panels. But am not sure which one is optimal. Any idea?
I'm not sure what you mean here. Define "optimal".

How can i add the JPanel class into JFrame form class in netbeans?

I created two classes in netbeans;One of them is a JPanel form and another is a JFrame form;
How can i add the JPanel class into JFrame form class?
I wrote this code in constructor of JFrame form Class but ,it didnt work.
public JFrameClass() {
initComponents();
this.getContentPane().add(jpc = new JPanelClass());
jpc.setVisible(true);
this.pack();
this.setVisible(true);
}
You need to make sure the JPanelClass is visible from where your JFrameClass is.
Then do the following:
JPanelClass jpc = new JPanelClass()
this.getContentPane().add(jpc);
Also, there is no need to call jpc.setVisible(true);
The resulting code should be:
public JFrameClass() {
initComponents();
JPanelClass jpc = new JPanelClass()
getContentPane().add(jpc);
pack();
setVisible(true);
}
How can i add the JPanel class into JFrame form class in netbeans?
In your JFrame class just set your JPanel and add its to Container.
JPanel panel = new JPanelClass();
controls.add(panel);
Note: You should have some private void method named for example createAndAddCompontents() and call it in your constructor.
public JFrameClass() {
...
createAndAddCompontents();
}
Then when you want to execute your Application so in main() method you should call it similar like this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
YouJFrameClass initAndShowComponents = new YouJFrameClass();
initAndShowComponents.setVisible(true);
}
});
set the bounds of the JPanel so that the container knows where to draw it
public void run() {
NewJFrame frame = new NewJFrame();
NewJPanel panel = new NewJPanel();
panel.setBounds(0, 0, 200, 200);
frame.add(panel);
frame.setVisible(true);
}

How to implements Button ActionListener to run the cardLayout by other classes?

I don't what the problem is? I try to switch the two seperate classes extends JPanel with the cardLayout by using JButton and I don't know am I used the correct code...
Here is my coding.
CardLayoutMenu
public class CardLayoutMenu extends JFrame implements ActionListener{
CardLayout cardLayout = new CardLayout();
private JPanel p1 = new JPanel(cardLayout);
final String MAIN = "MAIN";
final String OPTION = "OPTION";
MainPanel mainPanel = new MainPanel();
OptionPanel optionPanel = new OptionPanel();
private Object object;
public CardLayoutMenu(Object object) {
this.object = object;
}
public CardLayoutMenu(){
setLayout(new BorderLayout());
setTitle("Card Layout Menu");
setSize(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
add(p1);
p1.add(mainPanel, MAIN);
p1.add(optionPanel, OPTION);
}
public void actionPerformed(ActionEvent e){
try{
cardLayout.show(p1, OPTION);
}catch(Exception ex){
System.out.println("" + ex);
}
}
}
Here is my MainPanel
public class MainPanel extends JPanel{
private JButton jbtOption = new JButton("Option");
public MainPanel() {
setLayout(new FlowLayout());
add(jbtOption);
jbtOption.addActionListener(new CardLayoutMenu(this));
}
}
Then my OptionPanel, use the JButton jbtBack to go back the MainPanel
public class OptionPanel extends JPanel{
private JButton jbtBack = new JButton("Back");
public OptionPanel() {
setLayout(new FlowLayout());
add(jbtBack);
}
}
This code here will cause an infinite recursion:
public MainPanel() {
setLayout(new FlowLayout());
add(jbtOption);
jbtOption.addActionListener(new CardLayoutMenu(this));
}
Since this constructor is ultimately called from the CardLayoutMenu class, you'll have a CardLayoutMenu object that creates a MainPanel object which creates a CardLayoutMenu object that creates a MainPanel object which creates a CardLayoutMenu object that creates a MainPanel object which creates a ... well, I think that you get the picture.
One basic rule I strongly urge on you is to not make your GUI classes implement Listener interfaces as it is asking the class to do too much and often leads to confusing code such as yours. This is sort of fine in small example programs, but I wish that it wasn't used as it encourages newbies to continue to do this sort of thing. Instead consider creating an ActionListener object and pass this listener to any class that needs a button that needs to tell the CardLayout to change views. You can pass this listener into these classes via a constructor or setter method parameter.

Categories

Resources