Building a user interface in Java Swing is not so much hard as it is laborious. There are, of course, whysiwyg editors for such, but I have never found them worth the trouble. So, since they are also not readily available for Eclipse, this discussion will address issues for building them manually.One strong suggestion is that you not try to build them from start to finish in a single sequence of statements but, rather, build them in several layers. That is, use several layers of supporting methods to build up basic components, such as a TextField with label or a row of Buttons, aggregate these into subsections of the interface, and, finally, compose the whole structure.
The examples below work from the top down, also illustrating Swing's use of the ContentPane.
Top-Level Build
public void buildUI () { // get and modify containerPanel Container containerPanel = this.getContentPane(); containerPanel.setBackground ( getColorBackground() ); containerPanel.setLayout ( new FlowLayout () ); // build constituent panels JPanel dataPanel = buildDataPanel(); JPanel buttonPanel = buildButtonPanel(); JPanel MessagePanel = buildMessagePanel();// add constituient panels to containerPanel containerPanel.add ( buildDataPanel() ); containerPanel.add ( buildButtonPanel() ); containerPanel.add ( buildMessagePanel() );}
private JPanel buildButtonPanel() { // build button panel JPanel buttonPanel = new JPanel(); buttonPanel.setLayout ( new GridLayout ( 3, 1 ) ); buttonPanel.setBackground( getColorBackground() ); // add individual rows of buttons to panel buttonPanel.add ( buildItemButtonSetSearch() ); buttonPanel.add ( buildItemButtonSetStep() ); buttonPanel.add ( buildItemButtonSetClear() ); return buttonPanel;
}
private JPanel buildItemButtonSetSearch() { // define panel JPanel itemPanel = new JPanel(); itemPanel.setBackground( getColorBackground() ); itemPanel.setLayout ( new GridLayout ( 1, 2) );
// define empty panel JPanel emptyPanel = new JPanel(); emptyPanel.setBackground( getColorBackground() );
// define button panel JPanel buttonPanel = new JPanel(); buttonPanel.setLayout ( new FlowLayout( FlowLayout.LEFT ) ); buttonPanel.setBackground( getColorBackground() );// define buttons buttonAdd = new JButton ( "Add" ); buttonAdd.setBackground ( getColorYellow() ); buttonAdd.addActionListener ( this );
// other buttons omitted// add buttons to button panel buttonPanel.add( buttonAdd); // other buttons omitted // add empty and button panel to item panel itemPanel.add( emptyPanel ); itemPanel.add( buttonPanel ); return itemPanel;
}