【发布时间】:2017-09-04 15:08:06
【问题描述】:
我不熟悉在 Java 中使用 GUI,我在移动文本和按钮时遇到问题。无论我给我的按钮或任何其他 JLabel 提供什么坐标,它都不会移动,我想知道如何修复它,以便我可以将组件放置在 JPanel 上的任何我想要的位置
public class IntroPage extends JFrame {
public static void main(String[] args) {
IntroPage main = new IntroPage();
main.setVisible(true);
}
private JPanel contentPane;
public IntroPage (){
//make sure the program exits when the frame closes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Welcome");
contentPane = new JPanel();
setSize(400,700);
//This will center the JFrame in the middle of the screen
setLocationRelativeTo(null);
//Welcome Page stuff :D
JLabel ApplauseLabel = new JLabel("Welcome to U.X.Dot.X");
ApplauseLabel.setFont(new Font("Gill Sans MT", Font.PLAIN, 30));
ApplauseLabel.setLocation(100, 50);
contentPane.add(ApplauseLabel);
JLabel slogan = new JLabel("Register below");
slogan.setFont(new Font("Gill Sans MT", Font.PLAIN, 15));
slogan.setLocation(100, 400);
contentPane.add(slogan);
//FacebookSignUp.
JButton FBbutton = new JButton("Login With FaceBook");
FBbutton.setBackground(Color.BLUE);
FBbutton.setSize(50,50);
FBbutton.setLocation(20, 40);
FBbutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Add JPanel to go to FB API. Much later
}
});
contentPane.add(FBbutton);
add(contentPane);
//make sure the JFrame is visible
setVisible(true);
}
}
【问题讨论】:
-
1) 以最小尺寸提供 ASCII 艺术或 GUI 的预期布局的简单绘图,如果可调整大小,则具有更大的宽度和高度。 2) 请学习常见的 Java 命名法(命名约定 - 例如
EachWordUpperCaseClass、firstWordLowerCaseMethod()、firstWordLowerCaseAttribute,除非它是UPPER_CASE_CONSTANT)并始终如一地使用它。 3) Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作,在不同的语言环境中使用不同的 PLAF。因此,它们不利于像素完美布局。相反.. -
.. 使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。 4)
new Font("Gill Sans MT", Font.PLAIN, 15)这是设置Font的一种简单方法。大多数系统都不会安装它,所以最好先检查它是否存在,然后如果需要,默认为Font.SERIF或Font.SANS_SERIF等“通用”字体之一。通用字体将始终可用(尽管可能会因操作系统而异 - 另一个不使用精确定位的原因)。 -
那我应该用什么来代替我的东西? @安德鲁汤普森。我使用的是
GridBag,但将它们设置为 1,0 或 4,0 会使其不动。 -
“那我应该用什么来代替我的东西?” 布置 GUI 可能需要一点时间(习惯于布局的工作方式)。为什么不按照我第一条评论中的建议画出 GUI 应该是什么样子?
-
其实没什么特别的,我想做的就是把我的文字和按钮放在屏幕的中间下方。 @安德鲁汤普森。理想情况下,我想在面板上的任何位置。
标签: java swing layout-manager