Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

HELP!! Jbutton help action listener 1

Status
Not open for further replies.

tig12

Programmer
Feb 27, 2007
20
GB
Hi,

Could anyone help me create a button which has an action listener. But the button when pressed is linked to another frame or panel.

For example, a button pressed on an interface takes you to the next page.

thanks
 
Well - simply call nextPage () from the actionListener.
Of course, the context which knows how to create or activate the next page, has to have a method nextPage.
And the ActionListener needs to know the context.
Just tell the AL in its constructor from the context "here I'am", in java-lang: "this".

Code:
 import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class NextPageListener implements ActionListener
{
	private NextPage nextPage;
		
	public NextPageListener (NextPage nextPage)
	{
		this.nextPage = nextPage;
	}
	
	public void actionPerformed (ActionEvent e)
	{
		String cmd = e.getActionCommand ();
		if (cmd.equals ("next page"))
		{
			nextPage.nextPage ();
		}
	}
}

public class NextPage extends JFrame
{
	private JButton jb;
	private JPanel mainpanel;

	public NextPage ()
	{
		mainpanel = new JPanel ();
		mainpanel.setLayout (new BorderLayout ());
		this.getContentPane ().add (mainpanel);
		
		jb = new JButton ("next page");
		jb.addActionListener (new NextPageListener (this));
		
		JTextField jtext = new JTextField ("first Page");
		JPanel page1 = new JPanel ();
		page1.add (jtext);
		mainpanel.add (jb, BorderLayout.SOUTH);
		
		mainpanel.add (page1, BorderLayout.CENTER);

		setSize (400, 400);
		setLocation (300, 300);
		setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
		setVisible (true);
	}

	public static void main (String args[])
	{
		new NextPage ();
	}

	public void nextPage ()
	{
		JPanel page2 = new JPanel ();
		JLabel jlabel = new JLabel ("page 2");
		page2.add (jlabel);
		mainpanel.removeAll ();
		mainpanel.add (page2, BorderLayout.CENTER);
		mainpanel.updateUI ();
	}
}

don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top