Forums Register Login

Delegating Swing components to other objects

+Pie Number of slices to send: Send
I am trying to make an application that delegates some of the JFrame components to other classes, as in the simple example below, but while I would expect four sections to show up, there is only one. Can anybody help?

public class RunTest{

JFrame frame = new JFrame();
Container cont = frame.getContentPane();
ArrayList<Test> tests = new ArrayList<Test>();
Test test1 = new Test();
Test test2 = new Test();
Test test3 = new Test();
Test test4 = new Test();

public static void main(String[] args){

new RunTest().makeGUI();
}

public void makeGUI(){

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);

tests.add(test1);
tests.add(test2);
tests.add(test3);
tests.add(test4);

for (Test t: tests){

t.makePanel();
cont.add(t.getPanel());
}


frame.setVisible(true);
}
}



public class Test{

JPanel panel;
private JLabel label;

public void makePanel(){

panel = new JPanel();

JButton option1 = new JButton("Option 1");
JButton option2 = new JButton("Option 2");
label = new JLabel();

panel.add(option1);
panel.add(option2);
panel.add(label);

option1.addActionListener(new Hello());
option2.addActionListener(new GoodBye());
}

public JPanel getPanel(){

return panel;
}


public class Hello implements ActionListener{

public void actionPerformed(ActionEvent a){

label.setText("Hello");
}
}

public class GoodBye implements ActionListener{

public void actionPerformed(ActionEvent a){

label.setText("Goodbye");
}
}
}
+Pie Number of slices to send: Send
A content pane uses BorderLayout by default. If you invoke add() with only one argument on a component using BorderLayout, that component gets placed in the center of the layout, overlaying any existing components. Spend a little time with the Java Tutorial on Laying Out Components. It will save you time and aggrivation going forward.
Fire me boy! Cool, soothing, shameless self promotion:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 552 times.
Similar Threads
Java Programming Help (conversions)
JFrame won't repaint...
Adding JPanels from other objects
problem with label
calling another GUI class
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 00:28:37.