java JButton位置不起作用
我是java新手,但了解swing的基础知识和大多数库,我想知道为什么我最近制作的这个实践程序没有将JButton定位在正确的坐标上。我被难住了。这是源代码
package game;
import java.awt.Color;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JButton;
public class TitleScreen extends JFrame
{
JFrame window = new JFrame();
JPanel screen = new JPanel();
JButton start = new JButton("Play Game");
JButton end = new JButton("Quit Game");
ImageIcon thing = new ImageIcon("lol.png");
Image pic = thing.getImage();
public TitleScreen()
{
window.setTitle("Test");
window.setSize(500,500);
window.setBackground(Color.BLUE);
window.setLocationRelativeTo(null);
window.setResizable(false);
window.setVisible(true);
}
public void canvas()
{
screen.setLayout(null);
window.add(screen);
start.setBounds(250,250,100,50);
screen.add(start);
}
public static void main(String[] args)
{
TitleScreen TitleScreen = new TitleScreen();
}
# 1 楼答案
一些要点:
不要使用
null
布局,而是根据需要使用合适的布局值得一读的是How to Use Various Layout Managers
使用
SwingUtilities.invokeLater()
确保EDT已正确初始化阅读更多
Why to use SwingUtilities.invokeLater in main method?
SwingUtilities.invokeLater
在添加所有组件之后,始终在最后调用
JFrame#setVisible(true)
阅读更多what is the purpose of JFrame setBackground
应该是这样的:
# 2 楼答案
这是因为您没有调用
canvas
方法,这就是它没有显示的原因解决方案: