Reputation: 1
public void paintComponent(Graphics g){
g.drawImage(back,0,0,this);
if(winner || loser){
g.setColor(Color.white);
g.setFont(new Font(null,Font.BOLD,55));
g.drawString("SCORE:",350,250);
g.drawString(""+score,600,250);
g.drawImage(enemy,100,500,this);
g.drawImage(enemy2,175,500,this);
g.drawImage(enemy3,250,500,this);
g.drawImage(enemy5,700,515,this);
g.drawImage(enemy6,775,515,this);
g.drawImage(enemy7,850,515,this);
g.drawImage(enemy4,495,515,this);
if(winner){
g.drawImage(winnerPic,200,50,this);
}
else{
g.drawImage(gameOver,220,50,this);
}
g.drawImage(endingTitle,190,590,this);
JButton menu=new JButton("Return to menu");
menu.setSize(200,100);
menu.setLocation(400,400);
}
}
How do I make a button appear on the screen. Please be very detailed, idk how to work with swings layout styles.
Upvotes: 0
Views: 1308
Reputation: 317
First of all you have a container (such as a JPanel for example) that is displayed on a JFrame. After crating your button, you have to add it to the container. Most of the time you want your container to have a Layout, such as a BorderLayout.
JButton menu = new JButton("Back to the menu");
container.add(menu, BorderLayout.CENTER);
EDIT: If this isn't the way you want to implement it, it will atleast help you understand the hierarchy.
public void buttonExample(){
JFrame frame = new JFrame("Button Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setPreferredSize(new Dimension(200, 100));
JButton button = new JButton("Return to the menu");
panel.add(button, BorderLayout.CENTER);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
Upvotes: 2