Best Practice With JFrame Constructors?
Posted
by David Barry
on Stack Overflow
See other posts from Stack Overflow
or by David Barry
Published on 2010-04-26T21:07:23Z
Indexed on
2010/04/26
21:33 UTC
Read the original article
Hit count: 336
In both my Java classes, and the books we used in them laying out a GUI with code heavily involved the constructor of the JFrame. The standard technique in the books seems to be to initialize all components and add them to the JFrame in the constructor, and add anonymous event handlers to handle events where needed, and this is what has been advocated in my class.
This seems to be pretty easy to understand, and easy to work with when creating a very simple GUI, but seems to quickly get ugly and cumbersome when making anything other than a very simple gui. Here is a small code sample of what I'm describing:
public class FooFrame extends JFrame {
JLabel inputLabel;
JTextField inputField;
JButton fooBtn;
JPanel fooPanel;
public FooFrame() {
super("Foo");
fooPanel = new JPanel();
fooPanel.setLayout(new FlowLayout());
inputLabel = new JLabel("Input stuff");
fooPanel.add(inputLabel);
inputField = new JTextField(20);
fooPanel.add(inputField);
fooBtn = new JButton("Do Foo");
fooBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//handle event
}
});
fooPanel.add(fooBtn);
add(fooPanel, BorderLayout.CENTER);
}
}
Is this type of use of the constructor the best way to code a Swing application in java? If so, what techniques can I use to make sure this type of constructor is organized and maintainable? If not, what is the recommended way to approach putting together a JFrame in java?
© Stack Overflow or respective owner