gpt4 book ai didi

java - 将 JButton 放置在特定坐标上 [需要帮助]

转载 作者:行者123 更新时间:2023-12-01 23:31:09 25 4
gpt4 key购买 nike

我想将 Jbutton 放在 JFrame 中的特定坐标上。我尝试过使用 setLocation 和 setBounds 但它们都不起作用。我想我肯定做错了什么。我是 Java 新手,并尝试过搜索此内容

我的输出:

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

public class BingoHelper extends JFrame implements WindowListener, ActionListener{
JTextField text = new JTextField(10);

private JButton b; {
b = new JButton("Click to enter name");
}

public void actionPerformed (ActionEvent e) {
String fn = JOptionPane.showInputDialog("Username:");
String sn = JOptionPane.showInputDialog("Password:");
JOptionPane.showMessageDialog(null, "Welcome " + fn + " " + sn + ".", "", JOptionPane.INFORMATION_MESSAGE);
text.setText(fn + " " + sn);
b.setVisible(false);
text.setVisible(true);
text.setBounds(100,20,49,90);
b.setBounds(100,90,22,30);
}

public BingoHelper(){
super("BINGO");
setLayout(new FlowLayout());
add(b);
add(text);
text.setVisible(false);
b.setVisible(true);
b.setBounds(0,0,220,30);
b.addActionListener(this);
}

public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);

}
public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
}

最佳答案

大多数时候,没有理由通过坐标来定位 UI 元素。您确实应该检查一下布局管理器。你正在打开一 jar 蠕虫,我认为你不想处理它。例如,当用户尝试调整屏幕大小时,您可能会遇到麻烦。

请查看此文档:http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

GridBagLayout 确实很笨重并且使用起来很痛苦,但它应该足够灵活以适应您想要完成的任何事情。但是,您还应该研究其他布局管理器。您可以结合使用其中的一个或多个来实现您想要的外观和感觉。

话虽这么说,我讨厌 Java 的内置布局管理器。一旦您了解了它们的工作原理,您绝对应该转向第三方布局系统。 MIGLayout老板很漂亮。

关于java - 将 JButton 放置在特定坐标上 [需要帮助],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19254301/

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