Let's say there is a button and if you will click that, a new frame will appear and so on...
The setVisible(true); function is used to display a frame. Create an object of the desired frame and call this function. Something like this
//The applications first or the main frame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainFrame extends JFrame {
private JButton myFirstButton;
private JButton mySecondButton;
// Constructor for a new frame
public MainFrame {
super("My First Button Program");
myFirstButton = new JButton("First Frame");
myFirstButton.setFont(new Font( "Arial", Font.BOLD, 18));
myFirstButton.setBackground(Color.red);
mySecondButton = new JButton("New Frame");
mySecondButton.setFont(new Font( "Arial", Font.BOLD, 18));
mySecondButton.setBackground(Color.green);
Container c = getContentPane();
FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
c.setLayout(fl);
c.add (myFirstButton);
c.add (mySecondButton);
ButtonHandler handler = new ButtonHandler(); //creation of a new Object
myFirstButton.addActionListener(handler); // Attach/register handler to myFirstButton
mySecondButton.addActionListener(handler); //Attach/register handler to mySecondButton
setSize(400, 300);
show();
}
public static void main(String [] args) {
// Make frame
MainFrame f = new MainFrame();
f.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// This closes the window and terminates the
// Java Virtual Machine in the event that the
// Frame is closed by clicking on X.
System.out.println("Exit via windowClosing.");
System.exit(0);
}
}
);
} // end of main
// inner class for button event handling
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myFirstButton) {
new NewFrame1();
}
if (e.getSource() == mySecondButton) {
new NewFrame2();
}
}
} // end of inner class
} // end of outer class
The frame to be opened for first button
//import statements here
public class NewFrame1 extends JFrame implements ActionListener
{
//initialises the frame and opens it
public NewFrame1()
{
JButton open = new JButton("New Window");
open.addActionListener(this);
add(open);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
//code for the new frame
}
}
The frame to be opened for second button
//import statements here
public class NewFrame2 extends JFrame implements ActionListener
{
//initialises the frame and opens it
public NewFrame2()
{
JButton open = new JButton("New Window");
open.addActionListener(this);
add(open);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
//code for the new frame
}
}
Make one JFrame class, call it MainFrame for example, and from here open JPanels, that way you have a centralized place to commuincate data between different frames,popups,options dialogs ...etc
Sidenote: i recommend using an MVC design pattern
Your usage context is unclear. Maybe what you need is a JTabbedPane (tutorial)?
Related
I'm working on a very complicated, multi-layered Swing GUI, and the main issue I'm running into right now involves having a JButton ActionListener perform setVisible() on a separate JFrame and immediately dispose() of the current JFrame. Because of the length of my code, it's important that main, both JFrames, and the ActionListener are all split into individual class files. I wrote a VERY simplified version of my problem, split into 4 tiny class files. Here they are:
File 1:
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JFrame g1 = new GUI1();
g1.pack();
g1.setLocation(200,200);
g1.setVisible(true);
JFrame g2 = new GUI2();
g2.pack();
g2.setLocation(400,200);
g2.setVisible(false);
}
}
File 2:
import javax.swing.*;
public class GUI1 extends JFrame {
JPanel panel;
JButton button;
public GUI1() {
super("GUI1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
button = new JButton("Create GUI2");
button.addActionListener(new Listener());
add(panel);
add(button);
}
}
File 3:
import javax.swing.*;
public class GUI2 extends JFrame {
JPanel panel;
JLabel label;
public GUI2() {
super("GUI2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
label = new JLabel("I'm alive!");
add(panel);
add(label);
}
}
File 4:
import java.awt.event.*;
public class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
GUI2.setVisible(true);
GUI1.dispose();
}
}
As you can see, the only function of the ActionListener is to set GUI2 to visible and dispose of GUI1, but it runs the error "non-static method (setVisible(boolean) and dispose()) cannot be referenced from a static context". I figure this is because both methods are trying to reference objects that were created in main, which is static. My confusion is how to get around this, WITHOUT combining everything into one class.
Any suggestions? Thanks!
EDIT:
Here's the above code compiled into one file... although it returns the exact same error.
import javax.swing.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
JFrame g1 = new GUI1();
g1.pack();
g1.setLocation(200,200);
g1.setVisible(true);
JFrame g2 = new GUI2();
g2.pack();
g2.setLocation(400,200);
g2.setVisible(false);
}
}
class GUI1 extends JFrame {
JPanel panel;
JButton button;
public GUI1() {
super("GUI1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
button = new JButton("Create GUI2");
button.addActionListener(new Listener());
add(panel);
add(button);
}
}
class GUI2 extends JFrame {
JPanel panel;
JLabel label;
public GUI2() {
super("GUI2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
label = new JLabel("I'm alive!");
add(panel);
add(label);
}
}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
GUI2.setVisible(true);
GUI1.dispose();
}
}
You have to pass instances of frame1 and frame2 to your ActionListener.
import java.awt.event.*;
public class Listener implements ActionListener {
private JFrame frame1, frame2;
public Listener(JFrame frame1, JFrame frame2) {
this.frame1 = frame1;
this.frame2 = frame2;
}
public void actionPerformed(ActionEvent e) {
frame2.setVisible(true);
frame1.dispose();
}
}
This means you have to pass an instance of frame2 to your GUI1 class.
import javax.swing.*;
public class GUI1 extends JFrame {
JPanel panel;
JButton button;
public GUI1(JFrame frame2) {
super("GUI1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
button = new JButton("Create GUI2");
button.addActionListener(new Listener(this, frame2));
add(panel);
add(button);
}
}
This means you have to create the frames in the reverse order.
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JFrame g2 = new GUI2();
g2.pack();
g2.setLocation(400,200);
g2.setVisible(false);
JFrame g1 = new GUI1(g2);
g1.pack();
g1.setLocation(200,200);
g1.setVisible(true);
}
}
I am new(ish) to Java Swing but I have not been able to find an elegant solution to my issue so I thought I'd raise a question here.
I am trying to make my current JPanel change to another JPanel based on a button click event from within the current JPanel. In essence just hiding one panel and displaying the other. I feel this can be done within my MainFrame class however I'm not sure how to communicate this back to it. Nothing I am trying simply seems to do as desired, I'd appreciate any support. Thanks
App.java
public static void main(final String[] args) {
MainFrame mf = new MainFrame();
}
MainFrame.java
public class MainFrame extends JFrame {
public MainFrame(){
setTitle("Swing Application");
setSize(1200, 800);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
// First Page Frame switch
getContentPane().add(new FirstPage());
}
}
FirstPage.java
public class FirstPage extends JPanel {
public FirstPage() {
setVisible(true);
JButton clickBtn = new JButton("Click");
clickBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
// Change to SecondPage JPanel here.
}
});
add(clickBtn);
}
}
SecondPage.java
public class SecondPage extends JPanel {
public SecondPage() {
setVisible(true);
add(new JLabel("Welcome to the Second Page"));
}
}
Any more information needed, please ask thanks :)
I think the best way is to use CardLayout. It is created for such cases. Check my example:
public class MainFrame extends JFrame {
private CardLayout cardLayout;
public MainFrame() {
super("frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cardLayout = new CardLayout();
getContentPane().setLayout(cardLayout);
getContentPane().add(new FirstPage(this::showPage), Pages.FIRST_PAGE);
getContentPane().add(new SecondPage(this::showPage), Pages.SECOND_PAGE);
setLocationByPlatform(true);
pack();
}
public void showPage(String pageName) {
cardLayout.show(getContentPane(), pageName);
}
public static interface PageContainer {
void showPage(String pageName);
}
public static interface Pages {
String FIRST_PAGE = "first_page";
String SECOND_PAGE = "second_page";
}
public static class FirstPage extends JPanel {
public FirstPage(PageContainer pageContainer) {
super(new FlowLayout());
JButton button = new JButton("next Page");
button.addActionListener(e -> pageContainer.showPage(Pages.SECOND_PAGE));
add(button);
}
}
public static class SecondPage extends JPanel {
public SecondPage(PageContainer pageContainer) {
super(new FlowLayout());
add(new JLabel("This is second page."));
JButton button = new JButton("Go to first page");
button.addActionListener(e -> pageContainer.showPage(Pages.FIRST_PAGE));
add(button);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
}
}
CardLayout is the right tool for the job.
You can simply create the ActionListener used to swap pages in JFrame class, and pass a reference of it to FirstPage:
import java.awt.CardLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
public MainFrame(){
setTitle("Swing Application");
setSize(1200, 800);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
//Create card layout and set it to the content pane
CardLayout cLayout = new CardLayout();
setLayout(cLayout);
//create and add second page to the content pane
JPanel secondPage = new SecondPage();
add("SECOND",secondPage);
//create an action listener to swap pages
ActionListener listener = actionEvent ->{
cLayout.show(getContentPane(), "SECOND");
};
//use the action listener in FirstPage
JPanel firstPage = new FirstPage(listener);
add("FIRST", firstPage);
cLayout.show(getContentPane(), "FIRST");
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
class FirstPage extends JPanel {
public FirstPage(ActionListener listener) {
JButton clickBtn = new JButton("Click");
clickBtn.addActionListener(listener);
add(clickBtn);
}
}
class SecondPage extends JPanel {
public SecondPage() {
add(new JLabel("Welcome to the Second Page"));
}
}
I want the JPanel at the center of the frame to be replaced when the corresponding buttons present in the JPanel to the left of the frame are pressed.
I am using cardlayout for replacing the panels in the center.
here is the sample code that i used for changing panels on button click ,but it doesn't work. can anyone let me know whats wrong in the code.
Library extends JFrame
Public Library(){
Container container = getContentPane();
container.setLayout( new BorderLayout() );
setExtendedState(JFrame.MAXIMIZED_BOTH);
banner = new BannerPanel();
container.add(banner,BorderLayout.NORTH);
MenuButtons = new MenuButtonPanel();
container.add(MenuButtons,BorderLayout.WEST);
SelectedButtonPanel = new SelectedPanel(container);
setLocationRelativeTo(null);
setVisible( true );
init();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
MenuButtonPanel extends JPanel and has multiple buttons in it. The inner class of it ButtonHandler implements hte actionListner for the buttons
//inner class
class ButtonEventHandler implements ActionListener {
public void actionPerformed( ActionEvent event ){
SelectedPanel selectObj = new SelectedPanel();
if("about".equals(event.getActionCommand()))
{
selectObj.showReplacePanel("about");
}
else if("checkout".equals(event.getActionCommand()))
{
selectObj.showReplacePanel("checkout");
}
else if("search".equals(event.getActionCommand()))
{
selectObj.showReplacePanel("search");
}
The SelectedPanel should display the replaced Jpanel in the center of the frame
public SelectedPanel() {}
public SelectedPanel(Container framePane)
{
addSelectedPanel(framePane);
}
public void addSelectedPanel(Container framePane)
{
cardPanel = new JPanel();
//set layout of panel
cardPanel.setLayout(new CardLayout());
cardPanel.setBorder(null);
cardPanel.setForeground(new Color(0, 0, 0));
//this.selObj = selObj;
aboutPanel = new About();
checkoutPanel = new Checkout();
searchPanel = new Search();
cardPanel.add(aboutPanel,ABOUTBUTTON);
cardPanel.add(checkoutPanel,CHECKOUTBUTTON);
cardPanel.add(searchPanel, SEARCHBUTTON);
framePane.add(cardPanel, BorderLayout.CENTER); }
The selectedPanel class also has method showReplacePanel() which is called in the actionPerformed of the buttonClick.
public void showReplacePanel(String selObj)
{
System.out.println("cardlayout entered");
CardLayout cl = (CardLayout)(cardPanel.getLayout());
System.out.println("cardlayout entered");
switch(selObj){
case "about":
cl.show(cardPanel,ABOUTBUTTON);
break;
case "search":
//this.repPanel = searchPanel;
cl.show(cardPanel,SEARCHBUTTON);
break;
case "checkout":
cl.show(cardPanel,CHECKOUTBUTTON);
//this.repPanel = checkoutPanel;
break;
I created an example for you, take a look at the actionPerformed(ActionEvent e) method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelSwap extends JPanel implements ActionListener {
JPanel firstPanel = new JPanel();
JPanel secondPanel = new JPanel();
public PanelSwap() {
super(new BorderLayout());
firstPanel.setBackground(Color.RED);
secondPanel.setBackground(Color.YELLOW);
JButton swap1 = new JButton("SwapToYellow");
swap1.addActionListener(this);
JButton swap2 = new JButton("SwapToRed");
swap2.addActionListener(this);
firstPanel.add(swap1);
secondPanel.add(swap2);
add(firstPanel);
}
/** Listens to the buttons and perfomr the swap. */
public void actionPerformed(ActionEvent e) {
for (Component component : getComponents())
if (firstPanel == component) {
remove(firstPanel);
add(secondPanel);
} else {
remove(secondPanel);
add(firstPanel);
}
repaint();
revalidate();
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("PanelSwap");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new PanelSwap();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
i'm developing a JFrame which has a button to show another JFrame. On the second JFrame i want to override WindowsClosing event to hide this frame but not close all the application. So i do like this:
On second JFrame
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
private void formWindowClosing(java.awt.event.WindowEvent evt) {
this.dispose();
}
but application still close when i click x button on the windows. why? can you help me?
I can't use
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
because i need to show again that JFrame with some information added in it during operations from first JFrame. So i init second JFrame with attribute visible false. if i use dispose i lose the information added in a second moment by the other JFrame. so i use
private void formWindowClosing(java.awt.event.WindowEvent evt) {
this.setVisible(false);
}
but it still continue to terminate my entire app.
don't create a new JFrame, for new container use JDialog, if you want to hide the JFrame then better would be override proper e.g DefaultCloseOperations(JFrame.HIDE_ON_CLOSE), method JFrame.EXIT_ON_CLOSE teminating current JVM instance simlair as calll for System.exit(int)
EDIT
but it still continue to terminate my entire app.
1) then there must be another issue, your code maybe call another JFrame or formWindowClosing <> WindowClosing, use implemented method from API
public void windowClosing(WindowEvent e) {
2) I'b preferred DefaultCloseOperations(JFrame.HIDE_ON_CLOSE),
3) use JDialog instead of JFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClosingFrame extends JFrame {
private JMenuBar MenuBar = new JMenuBar();
private static JFrame frame = new JFrame();
private static JFrame frame1 = new JFrame("DefaultCloseOperation(JFrame.HIDE_ON_CLOSE)");
private static final long serialVersionUID = 1L;
private JMenu File = new JMenu("File");
private JMenuItem Exit = new JMenuItem("Exit");
public ClosingFrame() {
File.add(Exit);
MenuBar.add(File);
Exit.addActionListener(new ExitListener());
WindowListener exitListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
frame.setVisible(false);
/*int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}*/
}
};
JButton btn = new JButton("Show second JFrame");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame1.setVisible(true);
}
});
frame.add(btn, BorderLayout.SOUTH);
frame.addWindowListener(exitListener);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setJMenuBar(MenuBar);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ClosingFrame cf = new ClosingFrame();
JButton btn = new JButton("Show first JFrame");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
}
});
frame1.add(btn, BorderLayout.SOUTH);
frame1.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame1.setPreferredSize(new Dimension(400, 300));
frame1.setLocation(100, 400);
frame1.pack();
frame1.setVisible(true);
}
});
}
}
Adding a New Code with no WindowListener part as explained by #JBNizet, the very right thing. The default behaviour just hides the window, nothing is lost, you simply have to bring it back, every value inside it will remain as is, below is the sample program for further help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFrames
{
private SecondFrame secondFrame;
private int count = 0;
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JFRAME 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
secondFrame = new SecondFrame();
secondFrame.createAndDisplayGUI();
secondFrame.tfield.setText("I will be same everytime.");
JPanel contentPane = new JPanel();
JButton showButton = new JButton("SHOW JFRAME 2");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
secondFrame.tfield.setText(secondFrame.tfield.getText() + count);
count++;
if (!(secondFrame.isShowing()))
secondFrame.setVisible(true);
}
});
frame.add(contentPane, BorderLayout.CENTER);
frame.add(showButton, BorderLayout.PAGE_END);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFrames().createAndDisplayGUI();
}
});
}
}
class SecondFrame extends JFrame
{
private WindowAdapter windowAdapter;
public JTextField tfield;
public void createAndDisplayGUI()
{
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
tfield = new JTextField(10);
addWindowListener(windowAdapter);
contentPane.add(tfield);
getContentPane().add(contentPane);
setSize(300, 300);
}
}
Is this what you want, try this code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFrames
{
private SecondFrame secondFrame;
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JFRAME 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
secondFrame = new SecondFrame();
secondFrame.createAndDisplayGUI();
secondFrame.tfield.setText("I will be same everytime.");
JPanel contentPane = new JPanel();
JButton showButton = new JButton("SHOW JFRAME 2");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (!(secondFrame.isShowing()))
secondFrame.setVisible(true);
}
});
frame.add(contentPane, BorderLayout.CENTER);
frame.add(showButton, BorderLayout.PAGE_END);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFrames().createAndDisplayGUI();
}
});
}
}
class SecondFrame extends JFrame
{
private WindowAdapter windowAdapter;
public JTextField tfield;
public void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
tfield = new JTextField(10);
windowAdapter = new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
};
addWindowListener(windowAdapter);
contentPane.add(tfield);
getContentPane().add(contentPane);
setSize(300, 300);
}
}
You could avoid the listener completely and use
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Note that the default value is HIDE_ON_CLOSE, so the behavior you want should be the default behavior. Maybe you registered another listener that exits the application.
See http://docs.oracle.com/javase/6/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation%28int%29
It's hard to pinpoint exactly why you are experiencing the behavior stated without seeing a little more of the set-up code, however it may be due to defaultCloseOperation set to EXIT_ON_CLOSE.
Here's a link to a demo displaying the properties you are looking for although the structure is a bit different. Have a look: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/FrameworkProject/src/components/Framework.java
I'm creating a very simple program.
I have created this classes :
MainJframeClass, JDesktopPaneClass, JinternalFrameClass1 and JinternalFrameClass2.
what ive done is that i instantiated my jdesktoppaneclass and named it desktoppane1 and i added it to the MainJframeclass. i have also instantiated the 2 jinternalframes and named it internal1 and internal2. Now, i have button in mainjframeclass that when i press, i add the internal1 to desktoppane1. what my problem now is how to add the internal2 to desktoppane1 using a button placed somewhere in internal1. i know that why could i just add another button to desktoppane1 and add the internal2. but i have done it already, i just want to solve this problem. if you can help me please. sorry for my english by the way.
It's simply a matter of references. The code that adds something to the JDesktopPane must have a reference to it, and so you will need to pass that reference into the class that needs it say via either a constructor parameter or a method parameter.
Edit 1
For example:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class ReferenceExample extends JPanel {
private JDesktopPane desktop = new JDesktopPane();
private Random random = new Random();
public ReferenceExample() {
JButton addInternalFrameBtn = new JButton("Add Internal Frame");
addInternalFrameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addInternalFrame();
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(addInternalFrameBtn);
setPreferredSize(new Dimension(600, 450));
setLayout(new BorderLayout());
add(new JScrollPane(desktop), BorderLayout.CENTER);
add(btnPanel, BorderLayout.SOUTH);
}
public void addInternalFrame() {
MyInternalFrame intFrame = new MyInternalFrame(ReferenceExample.this);
int x = random.nextInt(getWidth() - intFrame.getPreferredSize().width);
int y = random.nextInt(getHeight() - intFrame.getPreferredSize().height);
intFrame.setLocation(x, y);
desktop.add(intFrame);
intFrame.setVisible(true);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Reference Eg");
frame.getContentPane().add(new ReferenceExample());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class MyInternalFrame extends JInternalFrame {
// pass in the reference in the constructor
public MyInternalFrame(final ReferenceExample refEg) {
setPreferredSize(new Dimension(200, 200));
setClosable(true);
JButton addInternalFrameBtn = new JButton("Add Internal Frame");
addInternalFrameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// use the reference here
refEg.addInternalFrame();
}
});
JPanel panel = new JPanel();
panel.add(addInternalFrameBtn);
getContentPane().add(panel);
pack();
}
}
how to add the internal2 to desktoppane1 using a button placed somewhere in internal1.
In the ActionListener added to your button you can use code like the following to get a reference to the desktop pane:
Container container = SwingUtilities.getAncestorOfClass(JDesktopPane.class, (Component)event.getSource());
if (container != null)
{
JDesktopPane desktop = (JDesktopPane)container;
JInternalFrame frame = new JInternalFrame(...);
desktop.add( frame );
}