问题描述:

This code runs quite nicely. But when I put setSize(700,700) and run the code, it does not show me the JButtons but the frame only. I thought that there might be some problem with the grid layouts of the JButtons, so I changed the last two entries of every gridlayout to, say GridLayout(3,1,300,300). However, the result is same (i.e. no JButtons are visible). Why is it happening?

import java.awt.*;

import javax.swing.*;

public class Calculator extends JFrame

{

JButton jb[]=new JButton[12];

public Calculator(String title)

{

super(title);

Container c;

c=getContentPane();

setSize(100,100);

setVisible(true);

Panel p1=new Panel();

for(int h=0;h<9;h++)

{jb[h]=new JButton(""+(h+1));}

jb[9]=new JButton("=");

jb[10]=new JButton(".");

jb[11]=new JButton("0");

p1.setLayout(new GridLayout(4,3,3,3));

for(int h=0;h<12;h++){p1.add(jb[h]);}

Panel p2=new Panel(new GridLayout(3,1,3,3));

JButton jb1[]=new JButton[3];

jb1[0]=new JButton("+");

jb1[1]=new JButton("-");

jb1[2]=new JButton("*");

for(int i=0;i<3;i++){

p2.add(jb1[i]);}

Panel p4=new Panel(new GridLayout(3,1,3,3));

JButton jb4[]=new JButton[3];

jb4[0]=new JButton("%");

jb4[1]=new JButton("/");

jb4[2]=new JButton("-");

for(int i=0;i<3;i++){

p4.add(jb4[i]);}

Panel p3=new Panel();

JLabel jl0=new JLabel("INPUT:");

TextField tf=new TextField(30);

p3.add(tf);

p3.add(jl0);

jl0.setLayout(new FlowLayout(FlowLayout.LEFT));

c.add(BorderLayout.CENTER,p1);

c.add(BorderLayout.EAST,p2);

c.add(BorderLayout.WEST,p4);

c.add(BorderLayout.NORTH,p3);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

public static void main(String args[])

{new Calculator("Lets calculate ! :)");}

}

网友答案:

You have to set the setVisible(true) on the end of the method (after adding the buttons).

网友答案:

You are using setSize(100, 100); which creates a very small window. Instead, use pack(); in the end of your constructor to fit the frame to your panels.

网友答案:

because setSize() invalidates the component hierarchy, ref: http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#setSize%28int,%20int%29

you need to re validate it.

for that you can call revalidate(); or even setVisible(true) again in the end.

its better to call pack(); and then setVisible(true); in the end instead of calling setVisible() before adding any components to your jframe.

相关阅读:
Top