我已經嘗試setLocation(x,y)和setLocationRelativeTo(null)通過將JFrame的佈局設置爲null,但沒有解決。在搜索時,我發現這個問題已經被問到兩個或三個人,但他們通過setLocation()和setLocationRelativeTo(null)完成。如何手動設置JComponents的位置等
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.FlowLayout;
public class StartMenu{
JPanel startPanel;
JLabel title;
JButton startTest;
JButton exit;
JFrame menuFrame;
public StartMenu(){
menuFrame = new JFrame("Start Menu");
menuFrame.setLayout(null);
startPanel = new JPanel();
title = new JLabel("Adaptive Test",JLabel.CENTER);
title.setLocation(20,20);
startPanel.add(title);
startTest = new JButton("Start");
startTest.setLocation(40,40);
startPanel.add(startTest);
exit = new JButton("Exit");
exit.setLocation(100,100);
startPanel.add(exit);
menuFrame.setContentPane(startPanel);
menuFrame.setVisible(true);
menuFrame.setSize(500, 500);
menuFrame.setResizable(false);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Java GUI必須使用不同語言環境中使用不同PLAF的不同OS,屏幕大小,屏幕分辨率等。因此,它們不利於像素的完美佈局。請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[white space]的佈局填充和邊框(http://stackoverflow.com/a/17874718/ 418556)。 –
我投票結束這個問題作爲題外話,因爲它要求如何實施黑客,當更好的策略是使用佈局,邊界和填充。 –
您的'startPanel'仍然具有默認的'FlowLayout'作爲佈局。只改變startPanel的佈局爲null(不是框架的),並使用'setBounds()'...這隻適用於你真的想要一個空佈局,當然(爲了學習理由或其他)。 - 如果沒有必要,請使用[佈局管理器](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html)。 –