How do I insert an image in the center of my JFrame?

Answered

Hello guys,

I am trying to create a game launcher (as I have to do that for homework) and I am trying to insert an image. However, I am not able to do it!

If someone could help me, I would appreciate it a lot.

Here is the code:

package javatutorial.net;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;


public class SimpleJButton {


SimpleJButton() {

//WINDOW
JFrame f = new JFrame("Launcher");
f.setBounds(650, 300, 720, 480);
f.getContentPane().setBackground(Color.black);

//PLAY BUTTON
JButton b = new JButton("Jugar");
b.setBounds(215, 450, 150, 50);
b.setFont(new Font("Courier New", 15, 30));
b.setForeground(Color.YELLOW);
b.setBackground(Color.BLACK);


//SELECT GAME
JLabel label = new JLabel();
label.setText("Seleccionar joc:");
label.setFont(new Font("Arial Black", 15, 30));
label.setForeground(Color.RED);
label.setBounds(150, 5, 1000, 100);


//empty label which will show event after button clicked
JLabel label1 = new JLabel();
label1.setBounds(10, 110, 200, 100);


//OPTIONS
JComboBox game = new JComboBox();
game.setBounds(160, 100, 250, 50);
game.setForeground(Color.white);
game.setBackground(Color.darkGray);


//comboboxmodel
DefaultComboBoxModel gamemodel = new DefaultComboBoxModel();

//IMAGE
JLabel jl = new JLabel();
jl.setIcon(new ImageIcon("games.jpg"));
jl.validate();


//FINESTRETA
f.add(label1);
f.add(label);
f.add(b);
f.add(game);
f.setSize(600, 600);
f.add(jl);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

game.setModel(gamemodel);
gamemodel.addElement("Ping Pong");
gamemodel.addElement("Snake");
gamemodel.addElement("Brick Breaker");

//action listener
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String selected = (String) game.getSelectedItem();
try {
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "C:\\Users\\Jose\\IdeaProjects\\PingPong\\out\\artifacts\\PingPong_jar\\PingPong.jar");
ProcessBuilder sb = new ProcessBuilder("java", "-jar", "C:\\Users\\Jose\\IdeaProjects\\Snake\\out\\artifacts\\Snake_jar\\Snake.jar");
ProcessBuilder bb = new ProcessBuilder("java", "-jar", "C:\\Users\\Jose\\IdeaProjects\\Brick Breaker\\out\\artifacts\\Brick_Breaker_jar\\Brick Breaker.jar");

ProcessBuilder selectedGame = null;

if(selected.equals("Ping Pong")){
selectedGame = pb;
}
else if(selected.equals("Snake")){
selectedGame = sb;
}
else if(selected.equals("Brick Breaker")){
selectedGame = bb;
}
else{
System.out.println("Joc desconegut...");
}

selectedGame.start();
} catch (IOException e) {
e.printStackTrace();
}
}

private void gamemodel(String selectedItem) {
}
});
}
public static void main(String[] args) {
new SimpleJButton();
}
}
0

Please sign in to leave a comment.