-1

I'm new to java but know the basics of swing and a majority of the libraries and I was wondering why this practice program I recently made is not positioning a JButton at the right coordinates. I'm stumped. Here is the source code.

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();    
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
user2451511
  • 117
  • 1
  • 1
  • 8

2 Answers2

2

That is because you didn't call the canvas method that is why it is not showing.

solution:

 public TitleScreen()

{
 window.setTitle("Test");
 window.setSize(500,500);
 window.setLocationRelativeTo(null);
 screen.setBackground(Color.BLUE);
 window.setVisible(true);
 canvas();
}
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
2

Some points:


It should be like this:

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();
        }
    });
}
Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76