-1

I am trying to make a calculator in java. I am new to Layout Managers. I created a JFrame object with GridBagLayout. I created 2 JPanel's, one for the numbers and the other for the operations. Both the JPanel use GridLayout.

This is how they are arranged in JFrame.

window=new JFrame("Calculator");

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridBagLayout());

//Creating window
GridBagConstraints gbc=new GridBagConstraints();
btns=new JPanel();                 //JPanel for numbers
operations=new JPanel();           //JPanel for operations
numdisp=new JTextField(15);        //JTextFIeld which displays the number
gbc.gridx=1;
gbc.gridy=1;
window.add(numdisp,gbc);

addbtn();                         //method which defines all the variables

gbc.gridx=1;
gbc.gridy=2;
window.add(btns,gbc);
gbc.gridx=2;
gbc.gridy=2;
window.add(operations,gbc);
btns.setLayout(new GridLayout(4,3,0,0));         //Layout for both JPanel's    
operations.setLayout(new GridLayout(7,1,1,1));

window.pack();
window.setVisible(true);

But this is how the result looks like...

Result

I don't understand why there is a large gap between my number panel and number display. Why is the problem occurring? How could it be resolved?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
S.Srihari
  • 39
  • 9
  • 1
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) See also this [calculator example](http://stackoverflow.com/a/7441804/418556). It uses `ScriptEngine` to evaluate the expression in the text field. 3) See also [`GridBagConstraints.fill`](http://docs.oracle.com/javase/8/docs/api/java/awt/GridBagConstraints.html#fill). – Andrew Thompson Feb 10 '17 at 12:54

1 Answers1

-1

Your entire window is also GridBagLayout. So you have 2x2 grid with first column of fixed size of 15

numdisp=new JTextField(15)

So layout manager also fixes the numbers grid also to the width of numdisp. If you remove this fixed size it should adjust to the size of numbers grid.

Lemonov
  • 476
  • 4
  • 17
  • If I remove the number of Columns, how could I adjust the width of JTextField? – S.Srihari Feb 10 '17 at 13:48
  • You can always change this size to fit size of number panel. You must be aware that changing the width and/or height of each cell in grid layout will also change size of adjacent cells. Maybe try using different layout model instead of GridBagLayout if you need the panels to be different size. The reorganization of components (move them to different panels) might also do the trick. – Lemonov Feb 10 '17 at 13:55
  • this doesn't fix the gap that persists between the `numdisp` and the number grid – S.Srihari Feb 11 '17 at 08:28
  • *"this doesn't fix the gap"* Why don't you fix that 'no MCVE' problem first. I could have had this sorted by now. Also, did you look into the `fill` constraint as I suggested? – Andrew Thompson Feb 12 '17 at 12:23