Monday, March 19, 2018

Two way navigation in frames

Note : Save this class inside UiOne.java file in Eclipse IDE


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class UiOne extends JFrame implements ActionListener
{
private JButton btn;

public UiOne()
{
// provide dimensions of frame
super.setBounds(100, 100, 600, 500);

// provide title of frame
super.setTitle("One");

// make the frame non-resizable
super.setResizable(false);

// create a button
btn = new JButton("i am button one");

// provide dimension of button
btn.setBounds(200, 200, 200, 25);

// add button to the frame
super.add(btn);

// register the button for event-handling
btn.addActionListener(this);

// set the layout of frame to null
super.setLayout(null);

// show frame on screen
super.setVisible(true);

// terminate the application when a frame is closed
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args)
{
UiOne obj = new UiOne();
}

// override action-performed method
// this method will be invoked when a button is clicked
@Override
public void actionPerformed(ActionEvent e)
{
// check on which button we clicked
if(e.getSource() == btn)
{
// create object of next frame
UiTwo u2 = new UiTwo();

// dispose this frame (make this frame disappear)
super.dispose();
}
}
}


-----------------------------------------------------------------------------

Note : Save this class inside UiTwo.java file in Eclipse IDE

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class UiTwo extends JFrame implements ActionListener
{
private JButton btn;
public UiTwo()
{
// provide dimensions of frame
super.setBounds(200, 200, 600, 500);
// provide title of frame
super.setTitle("Two");
// make the frame non-resizable
super.setResizable(false);
// create a button
btn = new JButton("i am button one");
// provide dimension of button
btn.setBounds(200, 200, 200, 25);
// add button to the frame
super.add(btn);
// register the button for event-handling
btn.addActionListener(this);
// set the layout of frame to null
super.setLayout(null);
// show frame on screen
super.setVisible(true);
// terminate the application when a frame is closed
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
UiTwo obj = new UiTwo();
}
// override action-performed method
// this method will be invoked when a button is clicked
@Override
public void actionPerformed(ActionEvent e)
{
// check on which button we clicked
if(e.getSource() == btn)
{
// create object of next frame
UiOne u1 = new UiOne();
// dispose this frame (make this frame disappear)
super.dispose();
}
}
}