Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/402.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 按钮位置不工作_Java_Swing_Jpanel_Jbutton_Null Layout Manager - Fatal编程技术网

Java 按钮位置不工作

Java 按钮位置不工作,java,swing,jpanel,jbutton,null-layout-manager,Java,Swing,Jpanel,Jbutton,Null Layout Manager,我是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;

我是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();    
}

这是因为您没有调用
canvas
方法,这就是它没有显示的原因

解决方案:

 public TitleScreen()

{
 window.setTitle("Test");
 window.setSize(500,500);
 window.setLocationRelativeTo(null);
 screen.setBackground(Color.BLUE);
 window.setVisible(true);
 canvas();
}
有几点:
  • 不要使用
    null
    layout,而是根据需要使用合适的布局

    值得一读

  • 使用
    SwingUtilities.invokeLater()
    确保正确初始化

    阅读更多

  • 添加所有组件后,始终在最后调用
    JFrame#setVisible(true)

  • 阅读更多


应该是这样的:

public void canvas() {
    screen.setBackground(Color.BLUE);
    screen.add(start);
    window.add(screen);             
}

public TitleScreen() {
    ...
    canvas();
    window.setVisible(true); 
}

public static void main(String[] args) {        
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            TitleScreen TitleScreen = new TitleScreen();
        }
    });
}

另外,为什么window.setBackground不会使屏幕变蓝。再次感谢。@user2451511不要设置帧背景,而是将其设置为您的jpanel。Edited see Upper更改代码行顺序是错误的,因为您设置了canvas();设置可见窗口。设置可见(真)@Rod_Algonquin是的,在本例中可能是wokrs,但关于基本错误,有关更多信息,请参阅Braj回答中的代码