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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sub classes and accessing methods

Status
Not open for further replies.

Markrp

Technical User
Nov 3, 2005
4
GB
The problem is two JPanels added to a JFrame, within 1 JPanel(newTop) it has a JLabel and the other JPanel(newPanel) has a Jbutton.

I want to click a button in one panel and update the label in the other.. Any ideas

public class Gui
{
public Gui()
{
JFrame newFrame = new JFrame("Test");

guiTop newTop = new guiTop();
guiPanel newPanel = new guiPanel();


BorderLayout BorderFrame= new BorderLayout();

newFrame.setSize(500,500);
newFrame.setLayout(BorderFrame);
newFrame.add(newTop,BorderLayout.NORTH);
newFrame.add(newPanel,BorderLayout.CENTER);
newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newFrame.setVisible(true);
}
}
 
create a method 'updateLabel (/* param */)' in guiTop (which should be named GuiTop) and make GuiTop known to guiPanel (w.s.b.n. GuiPanel) - perhaps by using a parameter in the constructor:
Code:
GuiPanel newPanel = new GuiPanel (newTop);
Store that reference to the GuiPanel, add an ActionListener, and call the updateLabel-Method for this reference,when the Button is hit.


seeking a job as java-programmer in Berlin:
 
Another alternative:

Code:
public class UpdateLabelAction extends AbstractAction

JLabel lblToUpdate;

public UpdateLabelAction(JLabel aLabel, String title, Icon icon)
{
super(title, icon);
lblToUpdate = aLabel;
}

public void actionPerformed(ActionEvent e)
{
lblToUpdate.setText("Whatever you want to change it to");
}

[code]

Then, change the constructor of your newPanel class to accept the JLabel as an argument.  You could send in the whole newTop instance, but it is not necessary...only pass in what you specifically plan to control in your class.  

In your newPanel Class:

[code]

JButton aButton = new JButton();
aButton.setAction(new UpdateLabelAction(theLabel, "The Title", myIcon);

Once you understand how this works, I recommend learning how to use Observer/Observable to handle your updates. It has helped organize my code immensely.

Rich


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top