两个按钮(具有固定宽度/高度和固定的位置)与JFrame的 [英] Two buttons (with a fixed width/height and fixed position) with JFrame

查看:554
本文介绍了两个按钮(具有固定宽度/高度和固定的位置)与JFrame的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要preface,是的,这是一门功课的问题。

I want to preface that yes, this is a homework question.

我们被告知要创造增加自己的个股两个按钮。计数器部分在这里没有显示其他类完成的。

We are told to create two buttons that increment their own individual counters. The counter part is done in another class not shown here.

我首先创建一个新的的JFrame ,并用自己的文字两个按钮。

I first create a new JFrame and two buttons with their own text.

JFrame frame = new JFrame();
JButton button1 = new JButton("Click me!");
JButton button2 = new JButton("Click me too!");

我设置它们的界限。

I set their bounds.

button1.setBounds(0, 0, 100, 50);
button2.setBounds(0, 50, 100, 50);

添加这些按钮在框架上。

Adding these buttons onto the frame.

frame.add(button1);
frame.add(button2);

附加的个人行动的听众(因为他们每次递增自己的柜台)。

Attach their individual action listeners (since they each increment their own counter).

ActionListener listener = new ClickListener();
ActionListener listener2 = new ClickListener();
button1.addActionListener(listener);
button2.addActionListener(listener2);

设置帧大小和杂项设置。

Set the frame size and misc settings.

frame.setSize(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

随着中说,这是输出:

With that said, this is the output:

正如你所看到的,按钮1 背后按钮2 尽管硬codeD .setBound 属性。

As you can see, button1 is behind button2 despite the hardcoded .setBound properties.

我已经尝试了 button2.setBounds(..)改变不同的设置,但似乎没有什么,我把在实际上改变其位置或大小。改变投入按钮1 ,但是,改变其位置/大小。

I have tried changing different settings for button2.setBounds(..), but it seems nothing I put in actually changes its position or size. Changing the inputs into button1, however, changes its position/size.

怎么办?

推荐答案

您应该避免使用的setBounds(...)和空布局,因为这使得非常不灵活GUI的,虽然他们看起来好一个平台上看起来可怕在大多数其他平台或屏幕分辨率,并且很难更新和维护。

You should avoid use of setBounds(...) and null layout as this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain.

相反,如果你想在另一个的上面的一个JButton的,他们是平等的双方,为什么不直接使用网​​格布局(0,1)

Instead if you want one JButton on top of the other and that they be equal sides, why not simply use a GridLayout(0, 1)?

这篇关于两个按钮(具有固定宽度/高度和固定的位置)与JFrame的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆