2014-04-12 56 views
1

如何使java awt程序的第一行包含文本字段,接下来的5行每行包含5个按钮,接下来的4行每行包含4个按钮。以及如何设置它们之间的按钮和空间的大小?我已经尝试过使用3个面板但不工作。如何在java框架中添加按钮和面板awt

(我做的,但示例程序没有显示任何东西)

`import java.awt.*; 
class cal extends Frame { 
cal(){ 
Panel p1=new Panel(); 
Panel p2=new Panel(); 
Panel p3=new Panel(); 
p1.setLayout(new GridLayout(2,3)); 
p2.setLayout(new GridLayout(2,2)); 
TextField k=new TextField("0",20); 
Button a=new Button("HI"); 
Button b=new Button("HI"); 
Button c=new Button("HI"); 
Button d=new Button("HI"); 
Button e=new Button("HI"); 
Button l=new Button("Hello"); 
Button g=new Button("Hello"); 
Button h=new Button("Hello"); 
Button i=new Button("Hello"); 
p1.add(a); 
p1.add(b); 
p1.add(c); 
p1.add(d); 
p1.add(e); 
p2.add(l); 
p2.add(g); 
p2.add(h); 
p2.add(i); 
Frame f=new Frame(); 
f.setSize(500,500); 
f.add(p3); 
f.add(p1); 
f.add(p2); 

show(); 
} 
public static void main(String[] args){ 
new cal();} 
}` 

回答

3
  1. 不要使用AWT库组件的图形用户界面,而是使用Swing库的组件,例如JFrame的,JPanel中,一个JButton ...
  2. 要查看顶级窗口中的内容,您必须将组件添加到显示的顶级窗口中,而且您从不这样做。换句话说,您需要通过add(...)方法将面板(应该是JPanels)添加到主类。您可以将它们添加到您称为f的Frame对象,但您会显示表示当前类的Frame,即this - 两个完全不同的对象。
  3. 让代码正常工作的一种方法是使用而不是让您的类扩展顶层窗口,而是创建顶层窗口(如您所做的那样)并在添加组件后显示它(如同不这样做)。
  4. 避免调用不推荐的方法,如show()。这样做可能是危险的,你的编译器应该给你一个警告,你应该留意警告。
  5. 了解布局管理器并使用它们。您目前正在使用它们,因为您的组件带有默认布局管理器,但没有正确使用它们。
  6. 最重要的是,阅读教程,你可以找到here,因为你无法猜测这个东西。
  7. 不要在这里发布代码,这是所有左对齐,因为它是很难阅读。
0

需要P1和P2的网格布局值替换到

p1.setLayout(new GridLayout(5,5));//To incease gap between components you need to use new GridLayout(5,5,hgap,ygap) 
p2.setLayout(new GridLayout(4,4));//similar here. 

,你的代码是不正确这里完成删除Show()函数将其替换为:

f.setLayout(new GridLayout(3,1));// you may want three rows and 1 column for this. 
f.setVisible(true);//for frame should be visible. 

请按照链接如何增加gridlayout中组件之间的差距:http://docs.oracle.com/javase/tutorial/uiswing/layout/group.html

为什么不使用Java swing。它更好,并具有先进的功能。

您的修改后的代码将是这样的:

import java.awt.*; 
public class Cal extends Frame { 
Cal(){ 

Panel p1=new Panel(); 
Panel p2=new Panel(); 
Panel p3=new Panel(); 

p1.setLayout(new GridLayout(5,5)); 
p2.setLayout(new GridLayout(4,4)); 

TextField k=new TextField(); 

Button a=new Button("HI"); 
Button b=new Button("HI"); 
Button c=new Button("HI"); 
Button d=new Button("HI"); 
Button e=new Button("HI"); 
Button l=new Button("Hello"); 
Button g=new Button("Hello"); 
Button h=new Button("Hello"); 
Button i=new Button("Hello"); 

p1.add(a); 
p1.add(b); 
p1.add(c); 
p1.add(d); 
p1.add(e); 
p2.add(l); 
p2.add(g); 
p2.add(h); 
p2.add(i); 
p3.add(k); 

Frame f=new Frame(); 
f.setLayout(new GridLayout(3,1)); 
f.setSize(500,500); 
f.add(p3); 
f.add(p1); 
f.add(p2); 
f.setVisible(true); 
} 
public static void main(String[] args){ 
new Cal();} 
} 
相关问题