Need to size JPanel to fill JFrame window - java

I have a JPanel that holds the main menu screen for a game project in my computer science class. The MainMenu class creates a panel that holds a button to start the game as well as a background image. However, when I add the panel to the parent JFrame (defined in OgGui class), there is about a cm of space between the top of the frame and where the panel/background image starts.
Does anyone know how to fill the frame window with the image?
//Creates parent JFrame to hold all game components
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class OgGui extends JPanel{
public static void main(String[] args){
JFrame frame = new JFrame ("OG Ball");
boolean start=true;
MainMenu mainm=new MainMenu();
while (start==true) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 600);
frame.setVisible(true);
frame.add(mainm);
start=mainm.returnscreen();
}
frame.add(new Draw());
//frame.pack();
}
}
MainMenu
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JButton;
public class MainMenu extends JPanel{
//Creates JFrame and menu background
JPanel main = new JPanel();
ImageIcon icon = new ImageIcon("og.png");
JLabel menu = new JLabel(icon);
//Sets up button to begin play
JButton startBtn = new JButton();
boolean gamestart;
public MainMenu(){
startBtn.setSize(4, 4);
startBtn.setVisible(false);
startBtn.addActionListener(new startScreen());
main.add(menu);
main.add(startBtn);
main.revalidate();
this.add(main);
}
public boolean returnscreen() {
return gamestart; }
private class startScreen implements ActionListener{
public void actionPerformed(ActionEvent event){
gamestart=false;
}
}
}

Related

How to set size and location of JButton in JPanel

I'm trying to set the size and location of a button on a panel using setBounds. It works when I put the button on the frame and have setLayout(null). But when placed on the panel, the button is always a set size at the top of the panel, if I set the layout to null, the frame just shows up blank.
import javax.swing.JFrame;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
MyFrame cl=new MyFrame("A");
cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener{
MyPanel panel;
Container cont;
JButton b;
public MyFrame(String title) {
super(title);
panel= new MyPanel();
b = new JButton();
b.setBounds(100, 100, 100, 100 );
cont= this.getContentPane();
cont.setLayout(new BorderLayout());
cont.add(panel, BorderLayout.CENTER);
panel.add(b);
this.setLayout(null);
this.setVisible(true);
this.setSize(1000,1000);
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyPanel extends JPanel {
public MyPanel() {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.BLACK);
}
}

How do I add a background image on a JFrame using a JLabel?

I am trying to display a background image on the JFrame using a JLabel. The code runs and the buttons appear, but the image does not. I have researched for solutions, yet I have not found one for my code specifically. Any help would be greatly appreciated.
/**
* Adds details to interface and programs buttons
*
* Imani Davis
* Final Project
*/
import java.awt.*;
import java.awt.GridBagLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.border.EmptyBorder;
public class Use_PF_Interface extends JFrame implements Pet_Fish_Interface
{
// instance variables - replace the example below with your own
private JFrame window;
private JPanel panel1, panel2, panel3;
private JLabel lblBackgroundImage = new JLabel();
private JButton feedButton = new JButton("Feed Fish");
private JButton playGamesButton = new JButton("Play Game");
/**
* Constructor for objects of class Use_PF_Interface
*/
public Use_PF_Interface()
{
setTitle("Virtual Pet Fish");
setSize(650, 650);
//initializes panels and panel layout
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel1.setLayout(new FlowLayout());
panel2.setLayout(new FlowLayout());
panel3.setLayout(new FlowLayout());
lblBackgroundImage.setLayout(new FlowLayout());
//sets background image of panel
lblBackgroundImage.setIcon(new ImageIcon("C:\\Users\\This PC\\Desktop\\OCEAN2.JPEG"));
panel1.add(lblBackgroundImage);
validate();
//adds button to panels
panel2.add(feedButton);
panel2.add(playGamesButton);
//add panels to frame
add(panel1);
add(panel2);
}
}
JFrame uses a BorderLayout by default, a BorderLayout can only manage a single component within any of the five available positions it provides, this means that panel2 is most likely the only component getting shown.
An alternative is to add you components to the JLabel, but remember, JLabel doesn't have a default layout manager. Also, remember, JLabel only uses the icon and text properties to calculate its preferred size, so if the contents require more space, they will be clipped.
Start by having a look at How to Use BorderLayout for more details
Also, remember, most Swing components are opaque generally, so you need to set them transparent when you want to do something like this
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Use_PF_Interface extends JFrame {
// instance variables - replace the example below with your own
private JPanel panel2;
private JLabel lblBackgroundImage = new JLabel();
private JButton feedButton = new JButton("Feed Fish");
private JButton playGamesButton = new JButton("Play Game");
/**
* Constructor for objects of class Use_PF_Interface
*/
public Use_PF_Interface() {
setTitle("Virtual Pet Fish");
setSize(650, 650);
//initializes panels and panel layout
panel2 = new JPanel();
panel2.setOpaque(false);
panel2.setLayout(new FlowLayout());
lblBackgroundImage.setLayout(new FlowLayout());
//sets background image of panel
lblBackgroundImage.setIcon(new ImageIcon("..."));
lblBackgroundImage.setLayout(new BorderLayout());
//adds button to panels
panel2.add(feedButton);
panel2.add(playGamesButton);
lblBackgroundImage.add(panel2);
add(lblBackgroundImage);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new Use_PF_Interface();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Try this,
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageInFrame {
public static void main(String[] args) throws IOException {
String path = "Image1.jpg";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}

How to create a game menu with 3 interfaces

How to create a game menu with three interfaces,1st interface has two option exit and continue,choose team and continue or back,3rd playing interface
package SimpleSoccer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
/** * * #author Andyblem */ public class TopLevelDemo {
static JButton startButton = new JButton("START");
static JButton exitButton = new JButton("EXIT");
static JButton backButton = new JButton("MENU");
static JPanel panel = new JPanel(new FlowLayout());
static JFrame frame;
private static void createAndShowGUI(){
frame = new JFrame("Top Level Demo");
frame.setSize(400,400);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar cyanMenuBar = new JMenuBar();
cyanMenuBar.setOpaque(true);
cyanMenuBar.setBackground(Color.cyan);
cyanMenuBar.setPreferredSize(new Dimension(200,180));
JLabel yellowLabel = new JLabel();
yellowLabel.setOpaque(true);
yellowLabel.setBackground(Color.yellow);
yellowLabel.setPreferredSize(new Dimension(200,20));
frame.setJMenuBar(cyanMenuBar);
frame.getContentPane().add(panel);
panel.add(startButton);
panel.add(exitButton);
// frame.getContentPane().add(exitButton);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]){
createAndShowGUI();
}
}
Your "question" (if you could even call it that) is kind of unclear. Seems like you just don't know where to begin. So I'll give you a tip.
What I would do is:
Use a CardLayout. What the layout does is "layer" panels, making them navigable with methods like show(pickAPanelToShow), next(nextPanel), and previous(previousPanel).
What you can do is on first page have a the two buttons, if continue is pressed, then the next() method can take you to the chooseTeamPanel. And from that panel you can navigate to the gamePanel after the team is chosen.
You can see more at How to use CardLayout and you can see an example here

JPanel transition, what is wrong with my code?

I am new to java, and learning new things everyday.
Today i stumbled upon an error i just can not get fixed.
So i've got a JFrame with a JPanel inside, now I want to remove the Jpanel when i click on my Start game JLabel, and make it transition into my game JPanel ( for now i use a test JPanel)
JFrame class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainMenu extends JFrame {
JPanel panel;
JFrame frame;
JButton playlabel;
public void mainmenu() {
frame = new JFrame();
panel = new JPanel();
playlabel = new JButton ("Nieuw Spel");
//frame
frame.setSize(new Dimension(800, 600));
frame.getContentPane().setBackground(new Color(14,36,69));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(frame.getMinimumSize());
frame.setVisible(true);
//panel
Dimension expectedDimension = new Dimension(690, 540);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setPreferredSize(expectedDimension);
panel.setMaximumSize(expectedDimension);
panel.setMinimumSize(expectedDimension);
panel.setBackground(new Color(14, 36, 69));
panel.add(playlabel);
playlabel.setAlignmentX(JComponent.CENTER_ALIGNMENT);
//playlabel
playlabel.setFont(new Font("Old English Text MT", Font.BOLD, 40));
playlabel.setBounds(250, 350, 50, 20);
playlabel.setForeground(new Color(217,144,39));
playlabel.setBackground(new Color(14,36,69));
playlabel.setBorderPainted(false);
playlabel.setFocusPainted(false);
playlabel.addActionListener(new PlayListener());
}
private class PlayListener extends JFrame implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPanel panelgame = Game.Game();
this.remove(panel);
this.add(panelgame);
this.revalidate();
}
}
}
Game class:
package labyrinthproject.View;
import java.awt.Color;
import javax.swing.JPanel;
public class Game {
public static JPanel Game(){
JPanel panel = new JPanel();
panel.setSize(690, 540);
panel.setBackground(new Color(255,36,69));
return panel;
}
}
if anyone could explain this to me why this doesn't work, it would be greatly appreciated!
Thank you very much!
Sincerely,
A beginner java student.
There are quite some issues in your code
Create the GUI on the event dispatch thread
Don't extend JFrame (you have three (three!) JFrames floating around there!)
Follow the naming conventions
Don't overuse static methods
Only store the instance variables that you really need to represent your class state
Don't use manual setSize or setBounds calls. Use a LayoutManager instead
The call to frame.setVisible(true) should be the last call, after the frame has been completely assembled
Consider a CardLayout for switching between panels ( http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html )
Slightly cleaned up, but the exact structure depends on what you actually want to achieve at the end:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainMenu extends JPanel
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainMenu = new MainMenu();
mainFrame.getContentPane().add(mainMenu);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
MainMenu()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Dimension expectedDimension = new Dimension(690, 540);
setPreferredSize(expectedDimension);
setBackground(new Color(14, 36, 69));
JButton newGameButton = new JButton ("Nieuw Spel");
newGameButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
newGameButton.setFont(new Font("Old English Text MT", Font.BOLD, 40));
newGameButton.setForeground(new Color(217,144,39));
newGameButton.setBackground(new Color(14,36,69));
newGameButton.setBorderPainted(false);
newGameButton.setFocusPainted(false);
newGameButton.addActionListener(new PlayListener());
add(newGameButton);
}
private class PlayListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
removeAll();
GamePanel gamePanel = new GamePanel();
add(gamePanel);
revalidate();
}
}
}
class GamePanel extends JPanel
{
GamePanel()
{
setBackground(new Color(255,36,69));
}
}
You should use a JButton and not a JLabel. Then:
you add to your JButton : Your_JB.addActionListener(this); (don't forget to implement ActionListener to your class).
Now, we are gonna add the detector:
#Override
public void actionPerformed(ActionEvent e){
Object src = e.getSource();
if(src == Your_JB){
panel.setVisible(false);
}
}
When you click the button, it will make your panel disapear.
Try this:
this.remove(panel);
this.validate();
this.repaint(); //if you use paintComponent
this.add(panelgame);
this.revalidate();
Swing is hard to making nice UI. You just need to use validate() after remove().
I hope it's helpfull.

CardLayout in Java change by action in one of the 'cards'

I am making a simple game using a JFrame. I have made a simple "Start" screen which basically consists of a String and a JButton. I am picking up the button click with the actionPerformed(ActionEvent e) method. I don't know how to change the cards using a button click. This may seem like a simple problem to solve, but the twist comes with this: My main JFrame, my StartScreen and my JPanel where the game takes place are all in separate files. My main file, Virus.java, is where I create the JFrame. My file VirusGamePanel.java is where the game takes place. My file StartScreen.java is the screen with the button. I want to change 'cards' to the game screen when the player clicks the button. How can I do this?
My StartScreen.java file:
package virus;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.CardLayout;
public class StartScreen extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
JButton start = new JButton("Start");
public StartScreen(){
start.addActionListener(this);
start.setBounds(new Rectangle(400,300,100,30));
this.add(start);
}
public void paint(Graphics g){
super.paint(g);
g.setFont(new Font("Impact",Font.BOLD,72));
g.setColor(Color.MAGENTA);
g.drawString("Virus",275,300);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==start)
{
//what to do here?
}
}
}
My Virus.java file:
package virus;
import javax.swing.*;
import java.awt.CardLayout;
import virus.StartScreen;
public class Virus extends JFrame{
private static final long serialVersionUID =1L;
JFrame jf = new JFrame("Virus");
static JPanel thegame = new JPanel(new CardLayout());
JPanel game = new VirusGamePanel();
JPanel start = new StartScreen();
public Virus(){
jf.setResizable(false);
jf.setSize(600,600);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
jf.setVisible(true);
jf.add(thegame);
thegame.add(start);
thegame.add(game);
}
public static void main(String[] args) {
new Virus();
}
}
You simply have to right this in your actionPerformed(...) method :
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==start)
{
//what to do here?
CardLayout cardLayout = (CardLayout) Virus.thegame.getLayout();
cardLayout.next(Virus.thegame);
}
}
As very much pointed out by #kleopatra (THE EMPRESS) herself, don't override paint() instead do your painting stuff inside paintComponent(Graphics g) method of any JPanel/JComponent. Moreover, first add the components to your JFrame, once it's size is realized, then only set it to Visible, not before that. Instead of setting sizes for the JFrame simply override the JPanel's method getPreferredSize(), make it return some valid Dimension Object.
Do watch this sequence, as you write your code the next time :
public Virus(){
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setResizable(false);
thegame.add(start);
thegame.add(game);
jf.add(thegame);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
Here is your full code :
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.CardLayout;
public class Virus extends JFrame{
private static final long serialVersionUID =1L;
JFrame jf = new JFrame("Virus");
static JPanel thegame = new JPanel(new CardLayout());
JPanel game = new VirusGamePanel();
JPanel start = new StartScreen();
public Virus(){
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setResizable(false);
thegame.add(start);
thegame.add(game);
jf.add(thegame);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
public static void main(String[] args) {
new Virus();
}
}
class StartScreen extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
JButton start = new JButton("Start");
public StartScreen(){
start.addActionListener(this);
start.setBounds(new Rectangle(400,300,100,30));
this.add(start);
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setFont(new Font("Impact",Font.BOLD,72));
g.setColor(Color.MAGENTA);
g.drawString("Virus",275,300);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(600, 600));
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==start)
{
//what to do here?
CardLayout cardLayout = (CardLayout) Virus.thegame.getLayout();
cardLayout.next(Virus.thegame);
}
}
}
class VirusGamePanel extends JPanel
{
public VirusGamePanel()
{
JLabel label = new JLabel("I am ON", JLabel.CENTER);
add(label);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(600, 600));
}
}
Your StartScreen class has to have access to the instance of the CardLayout of the JFrame and the instance of the VirusGamePanel class. You can pass these instances in the constructor or a setLayout method and setVirusGamePanel method of your StartScreen class.
Something like:
layout.next(virusGamePanel);
should work.

Categories