Link to home
Start Free TrialLog in
Avatar of Gregg
GreggFlag for United States of America

asked on

Question about Action Events

Below is a sample application that I am using to learn about events. It simply changes the background color of my JPanel. If I wanted to change the application title as well, how would i implement that?

Do i reference the JFrame in my ButtonList class and set the title in the makeButton() method? How might i go about doing that? Or what method would you recommend if i wanted to change background color and App Title when a button is clicked.

Thank you.

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

/**
 * Driver Class
 */
public class TestApplication
{
	public static void main(String[] args)
	{
		EventQueue.invokeLater(new Runnable()
			{
				public void run() 
				{
					AppFrame frame = new AppFrame();
					frame.init();
				}
			}
		);
	}
}//end class

/**
 * This class represents the JFrame object
 */
class AppFrame extends JFrame
{

	//*********************
	// Attributes
	//*********************
	
	//*********************
	// Constructors
	//*********************
	public AppFrame()
	{
		super();
	}
	
	//*********************
	// Methods
	//*********************
	public void init() {
		//Set Title
		setTitle("Test 1");
		
		//Set Window State
		setExtendedState(JFrame.MAXIMIZED_BOTH);
		
		//Build Buttons Menu
		ButtonList bl = new ButtonList();
		add(bl.getButtonList());
		
		//Set Visible
		setVisible(true);
		
		//Set Close
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
	}
	
}//end appFrame class

/** 
 * This class represents the Button JPanel
 */
class ButtonList extends JPanel
{	
	//*********************
	// Attributes
	//*********************
	
	//*********************
	// Constructors
	//*********************
	public ButtonList() 
	{
		super();
		//Create Buttons
		makeButton("Blue", Color.BLUE);
		makeButton("Green", Color.GREEN);
		makeButton("Orange", Color.ORANGE);
		makeButton("Yellow", Color.YELLOW);
	}
	
	//*********************
	// Methods
	//*********************
	public JPanel getButtonList() {
		return this;
	}
	
	public void makeButton(String title, final Color color)
	{
		JButton b = new JButton(title);
		b.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent event) {
					setBackground(color);
				}
			}
		);
		add(b);
	}
}//end class

Open in new window

Avatar of for_yan
for_yan
Flag of United States of America image

I would pass instance of your JFrame to class ButtonLisrt in the constructor
and then use this instance call setTitle("name") in actionListener
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Gregg

ASKER

Answer was perfect! Thanks for your help for_yan.