java awt button,如何添加按钮和面板帧在Java AWT

这篇博客解决了在Java AWT中创建GUI的问题,指出应使用Swing库而不是AWT,并强调了正确使用布局管理器的重要性。作者提供了一个示例程序,该程序包含文本字段和多行按钮,但程序没有正确显示。解决方案包括将组件添加到顶级窗口,避免使用已弃用的方法,并学习布局管理器以改善组件排列和间距。
摘要由CSDN通过智能技术生成

How to make java awt program in which first line contains text-field,next 5 lines contain 5 buttons each and next 4 lines contain 4 buttons each. And how to set the size of those buttons and space between them ? I have tried this using 3 panels but not working.

(sample program made by me but is not showing anything)

`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();}

}`

解决方案

Don't use AWT library components for your GUI, but rather use the Swing library's components such as JFrame, JPanel, JButton...

To view something on the top level window, you have to add your components to the displayed top level window, and you never do this. In other words you need to add your Panels (which should be JPanels) to the main class via the add(...) method. You add them to a Frame object you call f, but you display the Frame that represents the current class, the this -- two very completely different objects.

One way to get your code working is to not have your class extend a top level window, but instead to create a top level window (as you're doing) and display it after adding components (as you're not doing).

Avoid calling deprecated methods like show(). Doing this can be dangerous, your compiler should give you a warning about this, and you should heed the warning.

Learn about the layout managers and use them. You are currently using them since your components come with default layout managers, but are not using them correctly.

Most important, read the tutorials which you can find here, as you can't guess at this stuff.

Don't post code here that is all left justified as it is very hard to read.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值