Oftentimes, when beginning to work with Swing, it will seem simpler to set a null layout and to arrange your components with Cartesian pixel coordinates.
This is inadvisable as you can quickly run into trouble when doing things like resizing your window or when your gui responds to mouse input in unexpected ways.
It is much better to get to grips with how the various layout managers work right way. You can begin with something simple like BorderLayout
. Don't forget, you can use nested containers like JPanel
, each with their own layout manager.
Below is a tiny template GUI that you can use and adapt.
You can download the source code HERE.
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class FB extends JFrame implements ActionListener {
private JButton b;
public void actionPerformed(java.awt.event.ActionEvent e) {
// Do it
}
private void setGui() {
try {
setLocation(0, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = getContentPane();
JPanel bPanel = new JPanel();
b = new JButton("Click");
b.addActionListener(this);
bPanel.add(b);
cp.add(bPanel, BorderLayout.SOUTH);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
FB f = new FB();
f.setGui();
f.setSize(200, 200);
f.setVisible(true);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class FB extends JFrame implements ActionListener {
private JButton b;
public void actionPerformed(java.awt.event.ActionEvent e) {
// Do it
}
private void setGui() {
try {
setLocation(0, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = getContentPane();
JPanel bPanel = new JPanel();
b = new JButton("Click");
b.addActionListener(this);
bPanel.add(b);
cp.add(bPanel, BorderLayout.SOUTH);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
FB f = new FB();
f.setGui();
f.setSize(200, 200);
f.setVisible(true);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}