gpt4 book ai didi

java - java jframe中的按钮不会调整大小?

转载 作者:行者123 更新时间:2023-12-01 18:42:03 25 4
gpt4 key购买 nike

我昨天开始java编程,并且开发了这个。我遇到了一个问题,因为按钮无法调整大小。如果可以的话请提供帮助,并提前致谢。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

class BgPanel extends JPanel {
Image bg = new ImageIcon("C:\\Users\\********\\Pictures\\tiger.jpg").getImage();
@Override
public void paintComponent(Graphics g) {
g.drawImage(bg, 0, 0, getWidth(), getHeight(), this);
}
}

public class FrameTestBase extends JFrame {
public static void main(String args[]) {
JPanel bgPanel = new BgPanel();
bgPanel.setLayout(new BorderLayout());

final FrameTestBase t = new FrameTestBase();
ImageIcon img = new ImageIcon("C:\\Users\\********\\Pictures\\gear-icon.png");
t.setLayout(null);
t.setIconImage(img.getImage());
t.setTitle("Login");
t.setSize(600,600);
t.setLocationRelativeTo(null);
t.setContentPane(bgPanel);
t.setDefaultCloseOperation(EXIT_ON_CLOSE);
t.setVisible(true);

JButton registerButton = new JButton("register");
registerButton.setBounds(80, 80, 80, 80);
t.add(registerButton);
}
}

最佳答案

I have run into a problem, as the button will not resize. Please help if you can and thank you in advance.

 bgPanel.setLayout(new BorderLayout());
// --------- your other code
t.setLayout(null);
//--------------- your other code
t.setContentPane(bgPanel); // you are setting bgPanel which has BorderLayout
JButton registerButton = new JButton("register");
registerButton.setBounds(80, 80, 80, 80);
t.add(registerButton); // t is the JFrame, your main window

任何JFrame.add(component)本质上都会将您的组件添加到JFrame的内容 Pane 中。将布局设置为 null 后,您已将 bgPanel 作为内容 Pane 添加到 JFrame,该 JFrame 将 BorderLayout 作为其布局管理器。将按钮添加到内容 Pane ,即 bgPanel 将会添加带有 BorderLayout.Center 约束的 registerButton 。这就是为什么这个按钮扩展到屏幕大小的原因。

由于您非常渴望看到输出,请执行以下操作:

    // registerButton.setBounds(80, 80, 80, 80); comment out this line
registerButton.setPreferedSize(new Dimension(80, 80));
t.add(registerButton, BorderLayout.PAGE_START)

现在,关于使用 NULL 布局:

在您自己的示例中,您找不到按钮扩展到窗口大小的原因。在不久的将来,您将看到您的一个组件有头部,但由于超出了窗口边框而失去了尾部。您将看到您的一个组件将无缘无故地跳过另一个组件。您将看到您已经更改了组件相对于另一个组件的位置,但它将与其他组件建立关系。好吧,您将能够找到浪费时间的问题,并通过设置 xxxSize 、 setLocation 、 setBounds 等来解决,但是......

人可以在金钱上富有,但不能在时间上富有。

开始学习LayoutManager:Lesson: Laying Out Components Within a Container

关于java - java jframe中的按钮不会调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19572390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com