I am developing a GUI using Swing, but before my project gets too complex. I would like to have a good design structure. I have a few ideas and will use a simple example to illustrate. Some feedback on whether or not this is a good approach would be great.
This is what my GUI looks like:
There are 2 Jpanels LeftPanel
and RightPanel
. When Show Name is clicked the name in that panel pops up.
My approach for this is:
If a component is used more than once, I write a class(
GetNameButton
,NameLabel
).I write a class for each panel. As the project gets bigger, the JFrame class won't get too cluttered and changes to a panel won't affect the JFrame class.
Here is the code:
public class MyFrame extends JFrame{
public MyFrame(){
this.setLayout(null);
this.setBounds(100,100,400,400);
this.add(new LeftPanel());
this.add(new RightPanel());
this.setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
LeftPanel
public class LeftPanel extends JPanel implements ActionListener{
CloseButton cb = new CloseButton();
JLabel name = new JLabel("foo");
GetNameButton gnb = new GetNameButton();
public LeftPanel(){
this.setLayout(null);
this.setBounds(20, 20, 160, 320);
this.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null, null, null));
this.add(new NameLabel());
name.setBounds(50,10,40,10);
this.add(name);
this.add(cb);
this.add(gnb);
gnb.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==gnb){
JOptionPane.showMessageDialog(null, name.getText());
}
}
}
RightPanel
public class RightPanel extends JPanel implements ActionListener{
JLabel name = new JLabel("bar");
GetNameButton gnb = new GetNameButton();
public RightPanel(){
this.setLayout(null);
this.setBounds(200, 20, 160, 320);
this.setBorder(new SoftBevelBorder(BevelBorder.RAISED, null, null, null, null));
this.add(new NameLabel());
JLabel name = new JLabel("bar");
name.setBounds(50,10,40,10);
this.add(name);
this.add(gnb);
gnb.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==gnb){
JOptionPane.showMessageDialog(null, name.getText());
}
}
}
GetNameButton
public class GetNameButton extends JButton{
public GetNameButton(){
this.setText("Show Name");
this.setBounds(20,100,120,20);
}
}
NameLabel
public class NameLabel extends JLabel{
public NameLabel(){
this.setBounds(10,10,40,10);
this.setText("NAME: ");
}
}
CloseButton
public class CloseButton extends JButton implements ActionListener{
public CloseButton(){
this.setText("Close");
this.setBounds(20,50,100,20);
this.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==this){
System.exit(8);
}
}
}
JPanel
. \$\endgroup\$