Reputation: 67
My code compiles without errors or warnings but the buttons are overlaying each other in the default position (center of the grid's window). How can I overcome this? I really want to avoid GridBagLayout since I find it a little bit too annoying and intricate.
I've already read a lot of stuff (from posts here and in other platforms to documentation provided by sun) about the issue but nothing really seems to work besides using the "arcane" GridBagLayout methods.
Can anyone please help me or point me to a better more fruitful direction?
I provide the code I wrote bellow.
Thanks in advance. //version 2 of the calculator (using grid) import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; //import javax.swing.JTextField;
//buttons definition and declaration, layout class definition
public class calculatorV2 extends JFrame {
private static final long serialVersionUID = 1L;
GridLayout calcGui;
//JTextField display;
public calculatorV2(){
calcGui = new GridLayout(4,4,2,2);
setSize(400,400);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
setVisible(true);
setTitle("Calculator");
setLocationRelativeTo(null);
//display = new JTextField();
//display.setHorizontalAlignment(JTextField.RIGHT);
add(new JButton("0"));
add(new JButton("1"));
add(new JButton("2"));
add(new JButton("3"));
add(new JButton("4"));
add(new JButton("5"));
add(new JButton("6"));
add(new JButton("7"));
add(new JButton("8"));
add(new JButton("9"));
add(new JButton("+"));
add(new JButton("-"));
add(new JButton("*"));
add(new JButton("/"));
add(new JButton("="));
add(new JButton("C"));
}
//run grid
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new calculatorV2();
}
});
}}
Upvotes: 0
Views: 504
Reputation: 2309
You haven't set the layout on your JFrame
, you've only instantiated one.
Before you add your components, you need to call
setLayout(calcGui);
Upvotes: 3