I have the following:
public class Frame {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame Demo");
Panel panel = new Panel();
frame.add(panel);
frame.setBounds(250,100,800,500);
frame.setVisible(true);
}
}
public class Panel extends JPanel {
JButton singlePlayerButton;
JButton multiPlayerButton;
BufferedImage image;
Gui gui;
public Panel() {
gui = new Gui();
add(gui);
try {
image = ImageIO.read(new File("C:\\Users\\void\\workspace\\BattleShips\\src\\Testumgebung\\background\\battleship_main.jpg"));
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
}
}
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
}
JLabel text;
JPanel mainMenuPanel;
private class Gui extends JPanel {
public Gui() {
setVisible(true);
setSize(500, 300);
setLayout(null);
mainMenuPanel = new JPanel();
mainMenuPanel.setLayout(null);
mainMenuPanel.setBackground(Color.BLUE);
mainMenuPanel.setBounds(150, 10, 200, 230);
add(mainMenuPanel);
mainMenuPanel.setVisible(true);
singlePlayerButton = new JButton("Single Player");
singlePlayerButton.setBounds(100,50 , 150, 40);
singlePlayerButton.setVisible(true);
mainMenuPanel.add(singlePlayerButton);
multiPlayerButton = new JButton("Multi Player");
multiPlayerButton.setBounds(100, 100, 150, 40);
multiPlayerButton.setVisible(true);
mainMenuPanel.add(multiPlayerButton);
repaint();
}
}
}
I just want a MainMenu with a BackgroundImage and buttons like Singleplayer etc. Do I have to set a Layout or is it possible without one. I just started with GUI, as you can probably assume from the code. Thanks in advance...
As a general rule of thumb, yes, you should make use of a layout manager where ever it's possible, it will save you a lot of work in the long run.
Based on you code and what I presume you want to do, I would suggest having a look at:
As additional advice:
null
layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectifysrc
ever, it will no exist once the program is exported. Try and avoid absolute paths as well, as different computers will place your program in different locations (and not all OS's have a concept of drive letters). Instead, in your case, you should be using something likegetClass().getResource("/Testumgebung/background/battleship_main.jpg")
super.paintComponent
before performing any custom painting as a general rule.setOpaque(false)
) so the background can show through.Panel
should do nothing but manage the background image and should not be managing anything else, this would mean having theGui
added to thePanel
as a separate step and not part of thePanel
s initialisationAs a conceptual example...