Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Delegating Swing components to other objects  RSS feed

 
Guy Shahar
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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");
}
}
}
 
Joe Ess
Bartender
Posts: 9406
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!