如何使用Java将JButton放置在JFrame中的所需位置 [英] How to place a JButton at a desired location in a JFrame using Java

查看:462
本文介绍了如何使用Java将JButton放置在JFrame中的所需位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JFrame中将Jbutton放在特定的坐标上。我为JPanel(我放在JFrame上)设置了setBounds,并为JButton设置了setBounds。但是,它们似乎没有按预期运行。

I want to put a Jbutton on a particular coordinate in a JFrame. I put setBounds for the JPanel (which I placed on the JFrame) and also setBounds for the JButton. However, they dont seem to function as expected.

我的输出:

alt text http://i49.tinypic.com/2d8kuah.jpg

这是我的代码:

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Control extends JFrame {

    // JPanel
    JPanel pnlButton = new JPanel();
    // Buttons
    JButton btnAddFlight = new JButton("Add Flight");

    public Control() {
        // FlightInfo setbounds
        btnAddFlight.setBounds(60, 400, 220, 30);

        // JPanel bounds
        pnlButton.setBounds(800, 800, 200, 100);

        // Adding to JFrame
        pnlButton.add(btnAddFlight);
        add(pnlButton);

        // JFrame properties
        setSize(400, 400);
        setBackground(Color.BLACK);
        setTitle("Air Traffic Control");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Control();
    }
}

如何放置 JButton 在坐标(0,0)处?

How can place the JButton at coordinate (0, 0)?

推荐答案

在添加组件之前应该调用以下行

Following line should be called before you add your component

pnlButton.setLayout(null);

上面会将您的内容面板设置为使用绝对布局。这意味着您必须使用 setBounds 方法明确设置组件的边界。

Above will set your content panel to use absolute layout. This means you'd always have to set your component's bounds explicitly by using setBounds method.

一般情况下我不会建议使用绝对布局。

In general I wouldn't recommend using absolute layout.

这篇关于如何使用Java将JButton放置在JFrame中的所需位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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