JButton职位不起作用

时间:2014-06-14 14:18:22

标签: 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;
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();    
}

2 个答案:

答案 0 :(得分:2)

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

<强>溶液

 public TitleScreen()

{
 window.setTitle("Test");
 window.setSize(500,500);
 window.setLocationRelativeTo(null);
 screen.setBackground(Color.BLUE);
 window.setVisible(true);
 canvas();
}

答案 1 :(得分:2)

有些观点:


应该是这样的:

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