【问题标题】:Why can't I position the JButton using setLocation in this code?为什么我不能在此代码中使用 setLocation 定位 JButton?
【发布时间】:2016-02-25 04:13:47
【问题描述】:

我很新,还有很多东西要学。非常感谢任何花时间帮助我的人。我尝试了多种不同的方法来将我的按钮定位在与框架的特定坐标处,但由于某种原因,用于放置 JButtons 的常用语句都不起作用。有什么建议吗?

这是我当前的工作代码

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class GUI extends JFrame
{

JButton b1; // Declares Swing button variable and gives identifier (b1)
JButton b2;  // Declares Swing label variable and gives identifier (l1)

public GUI()
{
setTitle("Virus Explortation");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Pictures\\matrix.gif")));
setLayout(new FlowLayout());
b1=new JButton("I am a button");
add(b1);

b2=new JButton("I am also a button");
add(b2);

setSize(399,399);
setSize(400,400);


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

【问题讨论】:

  • 您需要了解布局管理器为您做什么,更多详情请参阅Laying Out Components Within a Container
  • 在有人告诉你之前,我也会避免使用null 布局,像素完美的布局是现代 UI 设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正
  • 作为one possible example 另一个是制作自己的布局管理器
  • @Jones 你可以看看下面我的解决方案。

标签: java swing jbutton layout-manager


【解决方案1】:

为什么我不能在这段代码中使用 setLocation 定位 JButton?

这是因为 Java swing 中的所有容器都有一个默认布局。您将按钮直接添加到 JFrame 中,我看到您使用 BorderLayout 作为框架。 (BorderLayout 也是 JFrame 的默认布局)。

使用布局时,布局管理器将决定您添加的组件的位置(有时是尺寸)。这意味着您手动设置位置的尝试可能是徒劳的。

如果你想将组件的位置设置到你想要的位置,你必须将容器的布局(例如 JFrame 或 JPanel)设置为null

JPanel pnlMain = new JPanel();
pnlMain.setLayout(null);

将其设置为 null 后,您必须为添加到容器中的每个组件设置位置。如果没有,它不会出现。您可以使用 setBounds 方法来设置大小和位置:

JButton btn = new JButton();
btn.setBounds(x, y, width, height);

但是,出于多种原因,不推荐将布局设置为null。最突出的原因之一是您无法控制和预测您的 UI 在不同系统上的呈现方式以及用户的不同使用方式。


建议不要从JFrame 扩展,而是从JPanel 之类的容器扩展。然后将容器添加到框架中。需要自定义JFrame的情况很少见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多