This question already exists:
generic Menu in java swing [closed]
Closed 23 days ago.
I'm building a brick breaker game using java swing.
I'm writing the game's menu and I encountered a problem when I wanted to put a background image because it override the other elements on the screen.
I tried several ways in all kinds of ways but nothing worked :(
I want the game's menu to be responsive, which means that regardless of which computer the screen will be run on, the proportions will be the same and I think this is the reason that in this implementation I am unable to put a background image.
If someone finds a solution for a background image and can suggest an improvement in the implementation that would be very helpful!!!!
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Menu extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private JFrame frame;
private JButton instructionsButton;
private JButton singlePlayerButton;
private JButton multiplayerButton;
private JButton quitButton;
public Menu()
{
frame = new JFrame("Brick Breaker Game"); //generate our frame
JPanel header_panel = new JPanel();
JPanel button_panel = new JPanel();
//header_panel.setLayout(new BorderLayout());
button_panel.setLayout(new BoxLayout(button_panel,BoxLayout.Y_AXIS));
// To adjust the frame size according to screen size
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(screenSize.width / 2, screenSize.height - (screenSize.height / 3));
frame.setLocation(screenSize.width / 4, screenSize.height / 6);
//Dimension frame_size = frame.getBounds().getSize();
//header_panel.setPreferredSize(new Dimension(screenSize.width / 2, screenSize.height - (screenSize.height / 3)));
button_panel.setPreferredSize(new Dimension(200, 200));
/*JLabel background_image = new JLabel();
//ImageIcon imageIcon = new ImageIcon(new ImageIcon(Constants.CLEAN_ANIMATION_GIF).getImage().getScaledInstance(screenSize.width / 2, screenSize.height - (screenSize.height / 3), Image.SCALE_DEFAULT));
ImageIcon imageIcon = new ImageIcon(new ImageIcon(Constants.CLEAN_ANIMATION_GIF).getImage().getScaledInstance(screenSize.width / 2, screenSize.height - (screenSize.height / 3), Image.SCALE_DEFAULT));
background_image.setIcon(imageIcon);
background_image.setOpaque(true);*/
JLabel headerlabel = new JLabel("Brick Breaker");
headerlabel.setHorizontalTextPosition(JLabel.CENTER);
headerlabel.setVerticalTextPosition(JLabel.CENTER);
headerlabel.setFont(new Font("Segoe Script", Font.BOLD, Constants.HEADER_SIZE));
instructionsButton = new JButton("Instructions");
instructionsButton.setMaximumSize(new Dimension(200, 70));
instructionsButton.setAlignmentX(Component.CENTER_ALIGNMENT);
instructionsButton.addActionListener(this);
//images_button.setBackground(Color.DARK_GRAY);
singlePlayerButton= new JButton("Single player");
singlePlayerButton.setMaximumSize(new Dimension(200, 70));
singlePlayerButton.setAlignmentX(Component.CENTER_ALIGNMENT);
singlePlayerButton.addActionListener(this);
multiplayerButton= new JButton("Multiplayer");
multiplayerButton.setMaximumSize(new Dimension(200, 70));
multiplayerButton.setAlignmentX(Component.CENTER_ALIGNMENT);
multiplayerButton.addActionListener(this);
quitButton= new JButton("Quit");
quitButton.setMaximumSize(new Dimension(200, 70));
quitButton.setAlignmentX(Component.CENTER_ALIGNMENT);
quitButton.addActionListener(this);
header_panel.add(headerlabel);
button_panel.add(Box.createRigidArea(new Dimension(0, 40)));
button_panel.add(instructionsButton);
button_panel.add(Box.createRigidArea(new Dimension(0, 30)));
button_panel.add(singlePlayerButton);
button_panel.add(Box.createRigidArea(new Dimension(0, 30)));
button_panel.add(multiplayerButton);
button_panel.add(Box.createRigidArea(new Dimension(0, 30)));
button_panel.add(quitButton);
/*JLabel background_image = new JLabel();
ImageIcon imageIcon = new ImageIcon(new ImageIcon(Constants.CLEAN_ANIMATION_GIF).getImage().getScaledInstance(screenSize.width / 2, screenSize.height - (screenSize.height / 3), Image.SCALE_DEFAULT));
background_image.setIcon(imageIcon);
frame.getContentPane().add(background_image);*/
frame.getContentPane().add(header_panel, BorderLayout.NORTH);
frame.getContentPane().add(button_panel, BorderLayout.CENTER);
//frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false); //fix the size
frame.setVisible(true);
}
/*public void paintComponent(Graphics g)
{
g.drawImage(new ImageIcon(Constants.CLEAN_ANIMATION_GIF).getImage().getScaledInstance(65, 70, 80), Image.SCALE_DEFAULT), 0, 0, this.getWidth(), this.getHeight(), null);
}*/
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == instructionsButton)
{
JOptionPane.showMessageDialog(null, "YOU HAVE CLICKED ON instructions BUTTON");
}
else if(e.getSource() == singlePlayerButton)
{
frame.dispose();
new ManageGame();
}
else if(e.getSource() == multiplayerButton)
{
try {
frame.dispose();
new Client();
} catch (ClassNotFoundException | IOException | InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else // Quit button
frame.dispose();
}
}
Related
I have program that resizes a button.
I just want to keep the center point in the center.
Perhaps by moving it by the distance between the center and…the upper left corner
Like when I resize the box in JSwing.
I want the center point to remain in the same spot.
How can I change the x, y of the upper left coordinates as the box increases
while keeping the center point in the same spot?
What woulf be the steps to get this done?
I guess my using the distance between the center and the upper left corner but how would that help
https://pastebin.com/0r8Vhez7
here's the code for context.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class Buttons
{
public static void main(String[] args)
{
//Buttons.JLabelExperiments JE = new Buttons().new JLabelExperiments();
//JE.ASY();
Buttons.JButtonExperiments JEB = new Buttons().new JButtonExperiments();
JEB.Print();
}
class JLabelExperiments
{
public static void ASY()
{
JFrame frame = new JFrame();
frame.setSize(1200, 1200);
JLabel lol = new JLabel(new Scanner(System.in).nextLine());
lol.setBounds(500, 400, 380, 200);
lol.setBorder(BorderFactory.createLineBorder(Color.BLACK));
frame.add(lol);
JSlider J = new JSlider(JSlider.VERTICAL, 0, 200, 0);
J.setMinorTickSpacing(2);
J.setMajorTickSpacing(10);
J.setPaintLabels(true);
J.setPaintTicks(true);
J.setPaintTrack(true);
J.addChangeListener(e ->
{
{
lol.setHorizontalAlignment(J.getValue());
JLabel LOL = new JLabel(String.valueOf(J.getValue()));
LOL.setBounds(700, 700, 100, 150);
frame.add(LOL);
}
});
frame.add(J);
JSlider j = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
j.setMajorTickSpacing(10);
j.setMinorTickSpacing(2);
j.setPaintTrack(true);
j.setPaintTicks(true);
j.setPaintLabels(true);
j.setBounds(200, 700, 400, 100);
j.addChangeListener(e ->
{
lol.setVerticalAlignment(j.getValue());
JLabel HUH = new JLabel(String.valueOf(j.getValue()));
HUH.setBounds(950, 700, 100, 150);
frame.add(HUH);
});
System.out.printf("%1$s, %2$s", J.getChangeListeners(), j.getChangeListeners());
frame.add(j);
frame.setVisible(true);
}
public static void asy()
{
}
}
class JButtonExperiments
{
public static void Print()
{
JFrame frame = new JFrame();
frame.setLayout(null);
frame.setSize(1200, 1200);
JButton B = new JButton("w");
B.setBounds(600, 600, 160, 160);
B.setText(new Scanner(System.in).nextLine());
frame.add(B);
JSlider width = new JSlider(SwingConstants.VERTICAL, 0, 0, 100);
JSlider height = new JSlider(JSlider.VERTICAL, 0, 0, 100);
width.setLocation(200, 600);
JLabel widthBox = new JLabel("Width");
widthBox.setBounds(20, 500, 120, 120);
height.setLocation(1000, 600);
JLabel heightBox = new JLabel("Height");
heightBox.setBounds(1180, 500, 120, 120);
width.setSize(100, 600);
height.setSize(100, 600);
frame.setVisible(true);
AtomicInteger counter = new AtomicInteger();
B.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
counter.getAndIncrement();
if(counter.get() == 1)
{
frame.add(width, height);
}
if(counter.get() == 3)
{
width.addChangeListener(E ->
{
B.setSize(B.getWidth()+width.getValue(), B.getHeight());
}
);
height.addChangeListener(E ->
{
B.setSize(B.getWidth(), B.getHeight()+height.getValue());
}
);
}
}
});
}
}
}
This was just a practice project but it seems this information may be more useful so please before forgive any lack of readability.
This code when run will make a button if you click it twice it will activate sliders that allow you to change the width and height of the button. By adding the value of the sliders to the value of the Button's width and height.
Use an appropriate layout manager, get it for free...
Now your button is always in the middle...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(new Insets(50, 50, 50, 50)));
setLayout(new GridBagLayout());
JButton btn = new JButton("Button in the middle");
GridBagConstraints gbc = new GridBagConstraints();
gbc.ipadx = 100;
gbc.ipady = 100;
add(btn, gbc);
}
}
}
Change the text and see what happens ... for free
See Laying Out Components Within a Container
I'm working on a group project and I'm the one making the GUI figuring it'd be good to practice with it. The program is supposed to be a pizza ordering system (pretty standard stuff) and what I'm trying to accomplish is that I have a main class that creates an application window. Inside this window is a panel that uses CardLayout with a button that when pressed calls another JPanel from another class dedicated specifically to that panel and places it as a card in the layout to be swapped back and forth from as normal.
What I have so far are the different panels I wish to call and the main class which has the window and main card panel. I can have it swap easily between panels created within the main class but when I try to use the panels from the other classes it just swaps to a blank panel when it should show the other class's panel.
The main class
package PizzaGUI;
import java.awt.EventQueue;
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Font;
public class PizzaSystem {
private JFrame frame;
Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setBounds(100, 100, 893, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(10, 10, 859, 470);
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(cl);
JPanel panel_2 = new JPanel();
mainPanel.add(panel_2, "test");
panel_2.setLayout(null);
JLabel lblNewLabel = new JLabel("It Worked");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 45));
lblNewLabel.setBounds(282, 118, 312, 103);
panel_2.add(lblNewLabel);
JPanel panel_1 = new JPanel();
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.setBounds(175, 72, 199, 154);
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
}
and one of the classes with the panel (format is messed up but should work still)
package PizzaGUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel();
panel1.setBounds(100, 100, 893, 572);
panel1.setBackground(Color.PINK);
panel1.setLayout(null);
panel1.setVisible(true);
JLabel logoLabel = new JLabel("");
logoLabel.setBounds(10, 10, 100, 110);
panel1.add(logoLabel);
ImageIcon image1 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane1.png");
logoLabel.setIcon(new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane.png"));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(133, 113, 548, 402);
tabbedPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
tabbedPane.setBackground(Color.PINK);
tabbedPane.setForeground(Color.GRAY);
tabbedPane.setFont(new Font("Tahoma", Font.PLAIN, 20));
tabbedPane.setToolTipText("");
panel1.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
panel.setLayout(null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
pizza1Image.setBounds(6, 25, 100, 100);
panel.add(pizza1Image);
ImageIcon image2 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\Pepperoni.jpg");
Image pizza1 = image2.getImage();
Image pepperoni = pizza1.getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH);
image2 = new ImageIcon(pepperoni);
pizza1Image.setIcon(image2);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
pepperoniLabel.setBounds(110, 25, 86, 48);
pepperoniLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.setBounds(110, 79, 86, 47);
panel.add(pepperoniOrderBtn);
pepperoniOrderBtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
accountButton.setBounds(10, 414, 113, 39);
accountButton.setBackground(Color.WHITE);
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
checkoutButton.setBounds(713, 438, 138, 31);
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
logoutButton.setBounds(10, 463, 113, 52);
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea();
txtrOrderInfoGoes.setBounds(703, 10, 154, 418);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
clearOrderButton.setBounds(723, 479, 113, 36);
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
titleLabel.setBounds(147, 10, 534, 65);
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
storeInfoLabel.setBounds(10, 130, 113, 274);
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(406, 85, 2, 2);
panel.add(scrollPane);
logoutButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
I can't tell where I've gone wrong and I've spent roughly the last three hours trying to fix this and searching the internet for answers to no avail so thank you in advance if you can help me out.
Also I apologize in advance, I know I end up misusing the proper terminology for programming alot, I understand what things are just forget what to properly call them sometimes.
So, basically, I took out all the null layouts and "manual" layout code, as it's just going to mess with you to no end AND added add(panel1); to the end of the MainMenu constructor - as, I've said, NOTHING was added to MainMenu, so, nothing was going to get displayed.
Before you tell me that "this isn't the layout I want", understand that I understand that, but my point is, null layouts are a really bad idea, as almost the entire Swing API relies the layout managers in one way or another.
I appreciate that layout management can seem like a complex subject, but it solves some very complex problems and it's worth taking the time to learn them. Remember, you're not stuck to a single layout manager, you can use component components to adjust individual containers to their individual needs.
You can take a look at:
Layout using Java Swing
Which Layout Manager to use?
How I can do swing complex layout Java
How to use Java Swing layout manager to make this GUI?
*Which java swing layout should I use
to some ideas how you might approach designing a complex UI.
You should also take a look at Laying Out Components Within a Container
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class PizzaSystem {
private JFrame frame;
// Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel(cl);
frame.getContentPane().add(mainPanel);
JPanel panel_1 = new JPanel(new GridBagLayout());
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
frame.pack();
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel(new BorderLayout());
JLabel logoLabel = new JLabel("Logo");
panel1.add(logoLabel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setToolTipText("");
panel1.add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
panel.add(pizza1Image);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea(10, 20);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane);
logoutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
add(panel1);
}
}
}
I am trying to create a game but my key bindings are not working and I am not sure why. the code included will run if given pictures and graphics data for image icons. When running the game the key bind gets input into the key map but it cannot be used for some odd reason. If anyone has any clue as to why it might be doing this that would be much appreciated.
graphics/ui:
package Ballerz;
import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import java.io.*;
public class GraphicsPn extends Game{
public GraphicsPn() throws IOException{
frame.setUndecorated(true);
frame.setName("Ballerz");
frame.setIconImage(window.getImage());
frame.setContentPane(startMenu);
frame.validate();
startMenu.setLayout(bord);
startMenu.setPreferredSize(new Dimension(1366, 768));
//top menu design
startMenu.add(topMenu);
topMenu.setPreferredSize(new Dimension(1366, 40));
topMenu.setBackground(Color.BLACK);
topMenu.setForeground(Color.WHITE);
topMenu.setAlignmentX(topMenu.RIGHT_ALIGNMENT);
topMenu.setLayout(bord);
setScene.add(topMenu);
topMenu.setPreferredSize(new Dimension(1366, 40));
topMenu.setBackground(Color.BLACK);
topMenu.setForeground(Color.WHITE);
topMenu.setAlignmentX(topMenu.RIGHT_ALIGNMENT);
topMenu.setLayout(bord);
topMenu.add(X, bord.EAST);
X.setLabel("X");
X.setFont(new Font(title.getName(), Font.ITALIC, 20));
X.setBackground(Color.BLACK);
X.setForeground(Color.WHITE);
X.setSize(new Dimension(50,40));
X.setFocusPainted(false);
X.setBorderPainted(false);
X.doLayout();
startMenu.add(menu, bord.EAST);
ballerz.setIcon(gif);
ballerz.setPreferredSize(new Dimension(768,768));
startMenu.add(ballerz, bord.WEST);
//menu Design
menu.setPreferredSize(new Dimension(598, 700));
menu.setBackground((Color.BLACK));
menu.setLayout(grid);
menu.setAlignmentY(menu.BOTTOM_ALIGNMENT);
grid.setVgap(30);
menu.add(title);
title.setForeground(Color.WHITE);
title.setPreferredSize(new Dimension(598, 150));
title.setFont(new Font(title.getName(), Font.ITALIC, 70));
menu.add(start);
start.setBackground(Color.BLACK);
start.setForeground(Color.WHITE);
start.setLabel("New Game");
start.setFocusPainted(false);
start.setFont(new Font(title.getName(), Font.ITALIC, 25));
start.setBorderPainted(false);
start.setSize(598,50);
start.doLayout();
menu.add(settings);
settings.setBackground(Color.BLACK);
settings.setForeground(Color.WHITE);
settings.setLabel("Settings");
settings.setFocusPainted(false);
settings.setFont(new Font(title.getName(), Font.ITALIC, 25));
settings.setBorderPainted(false);
settings.setSize(598,50);
settings.doLayout();
menu.add(help);
help.setBackground(Color.BLACK);
help.setForeground(Color.WHITE);
help.setLabel("How to Play");
help.setFocusPainted(false);
help.setFont(new Font(title.getName(), Font.ITALIC, 25));
help.setBorderPainted(false);
help.setSize(598,50);
help.doLayout();
menu.add(exit);
exit.setBackground(Color.BLACK);
exit.setForeground(Color.WHITE);
exit.setLabel("Exit");
exit.setFocusPainted(false);
exit.setFont(new Font(title.getName(), Font.ITALIC, 25));
exit.setBorderPainted(false);
exit.setSize(598,50);
exit.doLayout();
menu.add(source);
source.setFont(new Font(title.getName(), Font.ITALIC, 12));
//help design
helpScene.setPreferredSize(new Dimension(1366, 768));
helpScene.setBackground(Color.BLACK);
helpScene.add(topMenu);
ActionListener clic = new ActionListener(){ public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(help)){
frame.setContentPane(helpScene);
frame.revalidate();
frame.repaint();
helpScene.requestFocus();
helpScene.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
helpScene.requestFocus();
System.out.println("pressed " + e.getKeyCode());
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
frame.setContentPane(startMenu);
frame.repaint();
}
}});
frame.repaint();
}
if(e.getSource().equals(start)){
frame.setContentPane(game);
frame.invalidate();
frame.revalidate();
game.requestFocus();
frame.repaint();
}
if(e.getSource().equals(settings)){
frame.setContentPane(setScene);
setScene.setBackground(Color.BLACK);
setScene.requestFocus();
setScene.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
setScene.requestFocus();
System.out.println("pressed " + e.getKeyCode());
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
frame.setContentPane(startMenu);
frame.repaint();
}
}});
frame.repaint();
}
if(e.getSource().equals(X)) {
frame.setContentPane(startMenu);
frame.revalidate();
frame.repaint();
}
if(e.getSource().equals(exit)){
System.exit(0);
}
}};
exit.addActionListener(clic);
X.addActionListener(clic);
start.addActionListener(clic);
help.addActionListener(clic);
settings.addActionListener(clic);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
frame.setBackground(Color.black);
startMenu.setVisible(true);
}
}
game section:
package Ballerz;
import java.util.*;
import java.awt.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.*;
import java.lang.*;
public class Game extends JPanel {
public int x;
public int y;
public int x2;
public int y2;
public double dis1;
public double dis2;
public JLayeredPane game = new JLayeredPane();
public JPanel players = new JPanel();
JFrame frame = new JFrame();
JLabel ballerz = new JLabel();
public JPanel startMenu = new JPanel();
JPanel helpScene = new JPanel();
JPanel setScene = new JPanel();
JLabel title = new JLabel("Ballerz", JLabel.CENTER);
JLabel source = new JLabel("Gif by ShotoPop: https://media.giphy.com/media/3DrHrnC0JMotPiopno/giphy.gif", JLabel.CENTER);
JPanel menu = new JPanel();
JButton help = new JButton();
JButton start = new JButton();
JButton settings = new JButton();
JButton exit = new JButton("Exit");
JTextArea space1 = new JTextArea();
JPanel topMenu = new JPanel();
JButton X = new JButton();
JLabel space = new JLabel();
JLabel p2 = new JLabel();
public Image player1 = ImageIO.read(new File("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\tempdude.png"));
ImageIcon window = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\basketball dude.PNG");
ImageIcon gif = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\Ballerz.gif");
ImageIcon court = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\court.png");
ImageIcon player1s = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\tempdude.png");
public FlowLayout flow = new FlowLayout();
public BorderLayout bord = new BorderLayout();
public GridLayout grid = new GridLayout(6, 1);
JLabel ply1 = new JLabel();
JLabel ply2 = new JLabel();
public Game() throws IOException {
game.setLayout(bord);
game.setPreferredSize(new Dimension(1366, 768));
JLabel cort = new JLabel();
cort.setSize(new Dimension(1366, 768));
cort.setIcon(court);
players.setOpaque(false);
players.setLayout(bord);
players.setBackground(Color.pink);
ply1.setIcon(player1s);
ply1.setSize(new Dimension(200, 200));
ply1.setVisible(true);
ply1.setBackground(Color.black);
ply2.setIcon(player1s);
ply2.setSize(new Dimension(200, 200));
ply2.setVisible(true);
ply2.setBackground(Color.black);
players.add(ply1);
players.add(ply2);
players.setSize(new Dimension(1340, 820));
players.repaint();
players.setLayout(null);
ply2.setLocation(15, 410);
ply1.setLocation(1230, 410);
players.repaint();
players.setVisible(true);
players.setAlignmentX(CENTER_ALIGNMENT);
game.add(cort, bord.CENTER,5);
game.add(players,0);
players.setLocation(0, -50);
game.repaint();
}
public static void main(String[] arg) throws Exception {
GraphicsPn g = new GraphicsPn();
Game game = new Game();
keys li = new keys();
}
}
key binds:
package Ballerz;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.*;
public class keys extends Game{
public keys() throws IOException {
AbstractAction wAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("BOI");
if (ply2.getLocation().getY() <= 650 && ply2.getLocation().getY() >= 10) {
ply2.setLocation((int) ply2.getLocation().getX(), (int) ply2.getLocation().getY() + 10);
System.out.println(ply2.getLocation());
}
if (ply2.getLocation().getY() > 650)
ply2.setLocation((int) ply2.getLocation().getX(), 650);
players.repaint();
if (ply2.getLocation().getY() < 10) {
ply2.setLocation((int) ply2.getLocation().getX(), 10);
players.repaint();
}
players.repaint();
}
};
players.getInputMap().put(KeyStroke.getKeyStroke('w'), "wAction");
players.getActionMap().put("wAction", wAction );
}
}
You claim that your key bindings aren't working which implies that the only relevant part of the huge amount of code that you posted in your question, are the last two lines, namely
players.getInputMap().put(KeyStroke.getKeyStroke('w'), "wAction");
players.getActionMap().put("wAction", wAction );
where players is a JPanel.
So basically your question boils down to:
Key bindings for JPanel not working
This question has been asked and answered many times on stackoverflow
Try searching the Internet with Google for the terms
jpanel key bindings site:stackoverflow.com
The first result (of more than 2000) was JPanel doesn't react to KeyBindings
Basically you need to
Make sure that players is focusable because, by default, a JPanel is not.
Make sure to use the correct input map
I'm creating an about JFrame for my program. I have an icon which I used for the program and I have that show up as the first thing on the about JFrame, but I'm having issues trying to center the image. If I do some kind of centering it screws up the whole alignment of everything else.
I'm trying to have all the JLabels, other than the icon, to be left aligned. Then have the icon aligned to the center.
I had to remove some personal information, whatever I did remove I put them between "[]".
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class About extends JFrame {
public About() {
super("About [PROGRAM]");
setIconImage([PROGRAM].getInstance().setIcon());
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
main.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JLabel icon = new JLabel("", new ImageIcon(getClass().getResource(Constants.ICON_FULL)), JLabel.CENTER);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0,0,10,0));
main.add(icon);
main.add(Box.createRigidArea(new Dimension(0, 10)));
main.add(name);
main.add(expandedName);
main.add(copyright);
main.add(credits);
add(main);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
Consider using some layouts to help you out. Ones that come to mind include BorderLayout with the icon in the BorderLayout.CENTER position. You can stack stuff on one side using a BoxLayout using JPanel that is added to the main BorderLayout-using JPanel.
e.g.,
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class About extends JDialog {
public static final String IMAGE_PATH = "http://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/3/39/European_Common_Frog_Rana_temporaria.jpg/"
+ "800px-European_Common_Frog_Rana_temporaria.jpg";
public About(JFrame frame) {
super(frame, "About [PROGRAM]", true);
ImageIcon myIcon = null;
try {
URL imgUrl = new URL(IMAGE_PATH);
BufferedImage img = ImageIO.read(imgUrl);
myIcon = new ImageIcon(img);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JPanel main = new JPanel(new BorderLayout());
main.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JLabel centerLabel = new JLabel(myIcon);
JLabel name = new JLabel("[PROGRAM]");
JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");
JLabel copyright = new JLabel("[COPYRIGHT JUNK]");
JLabel credits = new JLabel("[CREDITS]");
name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));
copyright.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
int eb = 20;
centerLabel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
leftPanel.add(name);
leftPanel.add(Box.createVerticalGlue());
leftPanel.add(expandedName);
leftPanel.add(copyright);
leftPanel.add(credits);
leftPanel.add(Box.createVerticalGlue());
main.add(centerLabel, BorderLayout.CENTER);
main.add(leftPanel, BorderLayout.LINE_START);
add(main);
pack();
}
public static void main(String[] args) {
final JFrame frame = new JFrame("GUI");
JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("About") {
#Override
public void actionPerformed(ActionEvent e) {
About about = new About(frame);
about.setLocationRelativeTo(frame);
about.setVisible(true);
}
}));
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I've build a small GUI game in java and at some point I'm using a glassPane to temporarily block all mouseinput. I've used the glassPane before without any problems but this time it won't block the mouseinput. So I can still press a button that resides on the contentPane while the glassPane is enabled, I'm sure it's enabled because I can see the stuff I paint on it.
Here is a short piece of runnable code that's shows the problem:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GuiGame {
private JPanel contentPane;
private JButton button;
private JFrame frame;
private JPanel glassPane;
private Dimension screenSize;
public static void main(String[] args) {
GuiGame gui = new GuiGame();
gui.createGUI();
}
public void createGUI()
{
frame = new JFrame("BadGuiGame!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(400, 400));
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
frame.setContentPane(contentPane);
frame.pack();
glassPane = new JPanel();
glassPane.setOpaque(false);
glassPane.setLayout(null);
JLabel glassLabel = new JLabel("Glass Enabled");
glassLabel.setBounds(160, 50, 80, 20);
glassPane.add(glassLabel);
frame.setGlassPane(glassPane);
int buttonWidth = frame.getWidth()/2;
int buttonHeight = frame.getHeight()/4;
int xButton = (frame.getWidth() - buttonWidth)/2;
int yButton = frame.getHeight()/2;
button = new JButton("NEXT LEVEL!");
button.setFocusable(false);
button.setEnabled(true);
button.setBounds(xButton, yButton, buttonWidth, buttonHeight);
contentPane.add(button);
int x = (screenSize.width - frame.getWidth())/2;
int y = (screenSize.height - frame.getHeight())/2;
frame.setLocation(x, y);
frame.setVisible(true);
glassPane.setVisible(true);
}
}
i'd try adding a MouseListener to your glasspane, and on all MouseEvents consume the event, such as
public void mouseClicked(MouseEvent e) {
e.consume();
}