How to center buttons in my java game menu - java

So, basically, I've never really worked with windows in java, and I need help centering things. I tried a bunch of things, but no matter what, I can't center my buttons on my java menu.
Here's my main class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
public class window extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage canvas;
public window(int width, int height) {
canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
public Dimension getPreferredSize() {
return new Dimension(canvas.getWidth(), canvas.getHeight());
}
public void paint(Graphics g){
// double CanvasTileHeight = (canvas.getHeight()/16)+1;
// double CanvasTileWidth = (canvas.getWidth()/16)+1;
//
// OpenSimplexNoise noise = new OpenSimplexNoise();
//
// for(int j=0;j<CanvasTileWidth;j++) {
// double NoiseForCurrentLoopPos;
// if (((noise.eval(j,2)+1)*2)+16 < CanvasTileHeight) {
// NoiseForCurrentLoopPos = ((noise.eval(j,2)+1)*2)+16;
// } else {
// NoiseForCurrentLoopPos = CanvasTileHeight;
// }
// for(int i=(int) CanvasTileHeight;i>NoiseForCurrentLoopPos;i--) {
// Image sand = Toolkit.getDefaultToolkit().getImage("src/images/misc/sand.png");
// g.drawImage(sand, j*16, i*16, this);
// }
// }
//
// Image image = Toolkit.getDefaultToolkit().getImage("src/images/misc/Player_Placeholder1.png");
//
// ImageObserver paintingChild = null;
// g.drawImage(image, canvas.getWidth()/2-image.getWidth(paintingChild)/2, canvas.getHeight()/2-image.getHeight(paintingChild)/2, this);
//
}
public static void main(String[] args) throws ClassNotFoundException, IOException {
int width = 640;
int height = 480;
JFrame frame = new JFrame("Example Frame");
window panel = new window(width, height);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
JPanel buttons = new JPanel();
BoxLayout boxlayout = new BoxLayout(buttons, BoxLayout.Y_AXIS);
buttons.setLayout(boxlayout);
buttons.setBorder(new EmptyBorder(new Insets(150, 200, 150, 200)));
JLabel bottomLabel = new JLabel("GAME NAME HERE", SwingConstants.CENTER);
buttons.add(bottomLabel);
JButton jb1 = new JButton("Button 1");
JButton jb2 = new JButton("Button 2");
JButton jb3 = new JButton("Button 3");
jb1.setAlignmentX(SwingConstants.CENTER);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb1);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb2);
buttons.add(Box.createRigidArea(new Dimension(0, 10)));
buttons.add(jb3);
frame.add(buttons);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// loadtest();
// System.out.println(Arrays.toString(((String) test1).split(",")));
//
// savetest();
dirtest();
}
public static void savetest() {
String TestArray[] = {"hi87er629087029648276540982", "hi2", "hi3", "hi4", "Not gonna keep going on like this lol"};
String Test = TestArray[0];
String world = "testworld101022";
for (int k = 0; k < TestArray.length-1; k++) {
Test = Test + "," + TestArray[k+1];
}
new File("src\\saves\\" + world).mkdir();
try(FileOutputStream f = new FileOutputStream("src\\saves\\" + world + "\\chunk1savetest1.txt");
ObjectOutput s = new ObjectOutputStream(f)) {
s.writeObject(Test);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
static Object test1 = null;
public static void loadtest() {
String world = "testworld101022";
try(FileInputStream in = new FileInputStream("src\\saves\\" + world + "\\chunk1savetest1.txt");
ObjectInputStream s = new ObjectInputStream(in)) {
test1 = s.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void dirtest() {
File dir = new File("src\\saves");
File[] files = dir.listFiles();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
System.out.println(files.length);
if (files.length == 0) {
System.out.println("No saves yet!");
} else {
for (int i = 0; i< files.length; i++) {
File filename = files[i];
System.out.println(filename.toString());
}
}
}
}
My problem is when I run it, this is what happens:
So, the buttons and/or test are not centered. I don't understand why.
My problem is, the buttons should be about where the red line on the image is, but no matter what I do, I can't get it to work.
I tried centering it with SwingConstants.CENTER, but that diden't work, so I also tried Component.CENTER_ALIGNMENT, but that did the exact same thing. I found that doing multiple different things like changing the code to
jb1.setAlignmentX(Component.CENTER_ALIGNMENT);
jb2.setAlignmentX(SwingConstants.CENTER);
jb3.setAlignmentX(SwingConstants.CENTER);
makes it like this:
so basically it makes it so the 2 that are different from the one I changed are correctly centered, but the one I changed it not. All the images and stuff are probably unnecessary, but I hope I got across what I need help with! thanks =)

You can use BoxLayout to do that, take a look at the following code:
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.util.Arrays;
public class Main
{
public static void main(final String[] args)
{
final JLabel label = new JLabel("GAME NAME HERE");
final JButton button1 = new JButton("Button 1");
final JButton button2 = new JButton("Button 2");
final JButton button3 = new JButton("Button 3");
final JPanel centerPanel = createCenterVerticalPanel(5, label, button1, button2, button3);
final JFrame frame = new JFrame();
frame.add(centerPanel);
frame.setVisible(true);
frame.pack();
}
private static JPanel createCenterVerticalPanel(final int spaceBetweenComponents, final JComponent... components)
{
final JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Arrays.stream(components).forEach(component -> {
component.setAlignmentX(JPanel.CENTER_ALIGNMENT);
panel.add(component);
panel.add(Box.createRigidArea(new Dimension(0, spaceBetweenComponents)));
});
return panel;
}
}
If you also want to center a panel vertically in a frame, just use frame.setLayout(new GridBagLayout()). Cheers!

Related

Java selectable JLabel

I have made a GUI with a gallery panel which shows images held in JLabels. I need to make JLabel highlightable and then remove it if the user clicks remove. Is there a way or should I change my approach?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class GalleryPanel extends JPanel
{
private static final long serialVersionUID = 1L;
private int currentImage;
private JLabel[] images;
private final int MAX_IMAGES = 12;
private JScrollPane scrollPane;
private JList<JLabel> imageGallery;
private DefaultListModel<JLabel> listModel;
private JPanel imageHolder;
public void init()
{
setLayout(new BorderLayout());
imageHolder = new JPanel();
imageHolder.setLayout(new BoxLayout(imageHolder, BoxLayout.PAGE_AXIS));
imageHolder.setSize(getWidth(), getHeight());
images = new JLabel[MAX_IMAGES];
listModel = new DefaultListModel<JLabel>();
listModel.addElement(new JLabel(new ImageIcon("Untitled.png")));
imageGallery = new JList<JLabel>(listModel);
imageGallery.setBackground(Color.GRAY);
imageGallery.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
imageGallery.setLayoutOrientation(JList.VERTICAL);
imageGallery.setFixedCellHeight(50);
imageGallery.setFixedCellWidth(100);
scrollPane = new JScrollPane(imageHolder);
scrollPane.setBackground(Color.RED);
add(scrollPane, BorderLayout.CENTER);
}
public void addImageToGallery(File file)
{
if ( currentImage <= images.length - 1)
{
BufferedImage bufImage = null;
try
{
bufImage = ImageIO.read(file); //tries to load the image
}
catch (Exception e)
{
System.out.println("Unable to load file " + file.toString());
}
Image resizedImage = bufImage.getScaledInstance(bufImage.getWidth()/5, bufImage.getHeight()/5, Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(resizedImage);
images[currentImage] = new JLabel(icon, JLabel.CENTER);
//images[currentImage].setSize(resized);
//images[currentImage
images[currentImage].setBorder(new TitledBorder(new LineBorder(Color.GRAY,5), file.toString()));
imageHolder.add(images[currentImage]);
revalidate();
repaint();
currentImage++;
}
else
{
throw new ArrayIndexOutOfBoundsException("The gallery is full");
}
}
public final int getMaxImages()
{
return MAX_IMAGES;
}
public Dimension getPreferredSize()
{
return new Dimension(300, 700);
}
}
So you first of call should be the tutorals
How to use Lists
Selecting items in a list
Adding items to and removing items from a list
Which will give you the basic information you need to proceeded.
Based on your available code, you should not be adding a JLabel to the ListModel, you should never add components to data models, as more often than not, Swing components have there own concept of how they will render them.
In your case, you're actually lucky, as the default ListCellRenderer is based on a JLabel and will render Icon's automatically, for example
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
DefaultListModel model = new DefaultListModel();
model.addElement(new ImageIcon("mt01.jpg"));
model.addElement(new ImageIcon("mt02.jpg"));
model.addElement(new ImageIcon("mt03.jpg"));
JList list = new JList(model);
list.setVisibleRowCount(3);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
System.out.println(list.getSelectedIndex());
}
}
});
JFrame frame = new JFrame("Test");
frame.add(new JScrollPane(list));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Swing splash screen not working, Unexpected result

Downloaded some code to display Splash Screen from O'Reilly, but When I do some modified some text to display as per need.
I did some investigation, and debug the program but found nothing.
Is that any windows platform issue?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
public class SplashScreen extends JWindow {
private int duration;
byte[] msg = new byte[]{65,112,114,105,108,32,70, 111, 111,108};
String text = "";
public SplashScreen(int d) {
duration = d;
}
// A simple little method to show a title screen in the center
// of the screen for the amount of time given in the constructor
public void showSplash() throws Exception {
JPanel content = (JPanel)getContentPane();
content.setBackground(Color.white);
// Set the window's bounds, centering the window
int width = 450;
int height =300;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screen.width-width)/2;
int y = (screen.height-height)/2;
setBounds(x,y,width,height);
JLabel txt = new JLabel
(new String(msg), JLabel.CENTER);
txt.setFont(new Font("Sans-Serif", Font.BOLD, 32));
// Build the splash screen
JLabel label = new JLabel(new ImageIcon("oreilly.gif"));
JLabel copyrt = new JLabel
(new String(msg), JLabel.CENTER);
URL url = new URL("http://findicons.com/files/icons/360/emoticons/128/satisfied.png");
BufferedImage img = ImageIO.read(url);
ImageIcon icon = new ImageIcon(img);
JLabel iconL = new JLabel(icon);
copyrt.setFont(new Font("Sans-Serif", Font.BOLD, 12));
content.add(label, BorderLayout.CENTER);
content.add(txt, BorderLayout.CENTER);
content.add(iconL, BorderLayout.CENTER);
content.add(copyrt, BorderLayout.SOUTH);
Color oraRed = new Color(156, 20, 20, 255);
content.setBorder(BorderFactory.createLineBorder(oraRed, 10));
// Display it
setVisible(true);
// Wait a little while, maybe while loading resources
try { Thread.sleep(duration); } catch (Exception e) {}
setVisible(false);
}
public void showSplashAndExit() {
try {
showSplash();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
public static void main(String[] args) {
// Throw a nice little title page up on the screen first
SplashScreen splash = new SplashScreen(10000);
// Normally, we'd call splash.showSplash() and get on with the program.
// But, since this is only a test...
splash.showSplashAndExit();
}
}

Problems with Graphics drawImage

I've been hunting through past StackOverflow posts and trying to figure out why my image won't display.
I know that the ImageIO is fine since I can run getWidth() on my BufferedImage and it returns the correct width.
Here is my Graphic class, followed by my main class.
(I'm sorry for trashy code, I'm new to this.)
Code in Graphic class:
package blackjack;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Graphic extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public JFrame frame = new JFrame("Game Window");
public JPanel layout = new JPanel(new BorderLayout());
public JPanel menu = new JPanel();
public JPanel playing = new JPanel(new BorderLayout());
public JPanel game = new JPanel();
public BufferedImage cardArray[] = new BufferedImage[52];
public void begin() {
//starting menu
}
public void playersTurn() {
menu.add(playing);
Font font = new Font("",Font.PLAIN, 24);
JPanel btnHolder = new JPanel();
JLabel play = new JLabel("Playing:");
JLabel or = new JLabel(" or ");
JLabel question = new JLabel(" ? ");
question.setFont(font);
or.setFont(font);
play.setFont(font);
JButton hit = new JButton("Hit");
JButton stand = new JButton("Stand");
hit.addActionListener(this);
stand.addActionListener(this);
playing.add(play, BorderLayout.WEST);
playing.add(btnHolder, BorderLayout.CENTER);
btnHolder.add(hit);
btnHolder.add(or);
btnHolder.add(stand);
btnHolder.add(question);
}
public void gui() {
//main gui
Dimension imageD = new Dimension(71,96);
Dimension menuD = new Dimension(900,120);
menu.setBorder(BorderFactory.createLineBorder(Color.black));
menu.setPreferredSize(menuD);
JPanel titlePanel = new JPanel();
JLabel title = new JLabel("BlackJack");
title.setFont(new Font("", Font.PLAIN, 14));
titlePanel.add(title);
Graphic gr = new Graphic();
gr.setPreferredSize(imageD);
//adding
frame.add(layout);
layout.add(menu, BorderLayout.SOUTH);
layout.add(titlePanel, BorderLayout.NORTH);
layout.add(gr, BorderLayout.CENTER);
//frame settings
frame.setSize(900, 650);
frame.setResizable(false);
frame.setVisible(true);
}
public void buildPathArray() {
for(int i = 1; i<=52; i++){
BufferedImage im = null;
try {
im = ImageIO.read(new File(Blackjack.getInstallDir() + Blackjack.s + "src" + Blackjack.s + "cardpngs"+ Blackjack.s + (100+i)+".png"));
} catch (IOException e) {
e.printStackTrace();
}
cardArray[i-1]= im;
//System.out.println(Blackjack.getInstallDir() + "\\src\\cardpngs\\" + (100+i)+".png");
}
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Hit")) {
} else if(e.getActionCommand().equals("Stand")) {
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//g.setColor(Color.GREEN);
//g.fillOval(20, 20, 20, 20);
g.drawImage(cardArray[0], 0, 0, this);
}
}
Code in my main class:
package blackjack;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Blackjack {
public static String installDir = "";
public static String s = "";
public static void main(String[] args) {
Path currentRelativePath = Paths.get("");
installDir = currentRelativePath.toAbsolutePath().toString();
s = System.getProperty("file.separator");
Graphic gr = new Graphic();
gr.buildPathArray();
gr.gui();
//System.out.println(installDir);
//g.playersTurn();
}
public static String getInstallDir() {
return installDir;
}
}
The output is this:
You're creating one instance of Graphic in your Blackjack class...
public class Blackjack {
public static String installDir = "";
public static String s = "";
public static void main(String[] args) {
//...
Graphic gr = new Graphic();
gr.buildPathArray();
gr.gui();
}
And another in your Graphic class
public void gui() {
//...
Graphic gr = new Graphic();
gr.setPreferredSize(imageD);
//adding
//...
layout.add(gr, BorderLayout.CENTER);
//...
}
But you only initialise the images, using buildPathArray of the instance in you BlackBelt class, which is not what is actually displayed on the screen...
As a general rule of thumb, you shouldn't be creating an instance of JFrame from within another component with the express purpose of display that component. Your Graphic component is also trying to do too much. Instead, I would have a Game class, maybe, which pulled the title, menu and Graphic components together and then put that onto an instance of JFrame
The main reason for this is, is your Graphic class is trying to do too much. It should be solely responsible for display the cards and managing them. The Game class should manage the other UI elements and be responsible for ensuring that the UI meets the current state of the game "model", taking in user input (and listening to events from the other UI elements) and updating the model and responding to events that the model creates, a little more like...
BlackJack...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BlackJack {
public static void main(String[] args) {
new BlackJack();
}
public BlackJack() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Game());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Game extends JPanel {
private JPanel menu;
private Graphic graphic;
public Game() {
menu = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(900, 120);
}
};
menu.setBorder(BorderFactory.createLineBorder(Color.black));
JPanel titlePanel = new JPanel();
JLabel title = new JLabel("BlackJack");
title.setFont(new Font("", Font.PLAIN, 14));
titlePanel.add(title);
Graphic gr = new Graphic();
gr.buildPathArray();
setLayout(new BorderLayout());
add(menu, BorderLayout.SOUTH);
add(titlePanel, BorderLayout.NORTH);
add(gr, BorderLayout.CENTER);
}
}
}
Graphic...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Graphic extends JPanel {
private static final long serialVersionUID = 1L;
public BufferedImage cardArray[] = new BufferedImage[52];
public void begin() {
//starting menu
}
public void playersTurn() {
// All of this belongs in Game
}
#Override
public Dimension getPreferredSize() {
return new Dimension(71,96);
}
public void buildPathArray() {
for (int i = 1; i <= 52; i++) {
BufferedImage im = null;
try {
im = ImageIO.read(new File(Blackjack.getInstallDir() + Blackjack.s + "src" + Blackjack.s + "cardpngs" + Blackjack.s + (100 + i) + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
cardArray[i - 1] = im;
//System.out.println(Blackjack.getInstallDir() + "\\src\\cardpngs\\" + (100+i)+".png");
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
//g.setColor(Color.GREEN);
//g.fillOval(20, 20, 20, 20);
g.drawImage(cardArray[0], 0, 0, this);
}
}
You might also want to have a look at Model-View-Controller.

Why won't the JButtons, JLabels and JTextFields be displayed?

This code enables an employee to log in to the coffee shop system. I admit I have a lot of unneeded code. My problem is that when I run the program just the image is displayed above and no JButtons, JLabels or JTextFields.
Thanks in advance.
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.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
public class login extends JFrame {
public void CreateFrame() {
JFrame frame = new JFrame("Welcome");
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setLayout(new BorderLayout(1000,1000));
panel.setLayout(new FlowLayout());
getContentPane().add(panel);
ImagePanel imagePanel = new ImagePanel();
imagePanel.show();
panel.add(imagePanel, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.add(panel);
}
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();
}
new login().CreateFrame();
}
});
}
}
class GUI extends JFrame{
private JButton buttonLogin;
private JButton buttonNewUser;
private JLabel iUsername;
private JLabel iPassword;
private JTextField userField;
private JPasswordField passField;
public void createGUI(){
setLayout(new GridBagLayout());
JPanel loginPanel = new JPanel();
loginPanel.setOpaque(false);
loginPanel.setLayout(new GridLayout(3,3,3,3));
iUsername = new JLabel("Username ");
iUsername.setForeground(Color.BLACK);
userField = new JTextField(10);
iPassword = new JLabel("Password ");
iPassword.setForeground(Color.BLACK);
passField = new JPasswordField(10);
buttonLogin = new JButton("Login");
buttonNewUser = new JButton("New User");
loginPanel.add(iUsername);
loginPanel.add(iPassword);
loginPanel.add(userField);
loginPanel.add(passField);
loginPanel.add(buttonLogin);
loginPanel.add(buttonNewUser);
add(loginPanel);
pack();
Writer writer = null;
File check = new File("userPass.txt");
if(check.exists()){
//Checks if the file exists. will not add anything if the file does exist.
}else{
try{
File texting = new File("userPass.txt");
writer = new BufferedWriter(new FileWriter(texting));
writer.write("message");
}catch(IOException e){
e.printStackTrace();
}
}
buttonLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File("userPass.txt");
Scanner scan = new Scanner(file);;
String line = null;
FileWriter filewrite = new FileWriter(file, true);
String usertxt = " ";
String passtxt = " ";
String puname = userField.getText();
String ppaswd = passField.getText();
while (scan.hasNext()) {
usertxt = scan.nextLine();
passtxt = scan.nextLine();
}
if(puname.equals(usertxt) && ppaswd.equals(passtxt)) {
MainMenu menu = new MainMenu();
dispose();
}
else if(puname.equals("") && ppaswd.equals("")){
JOptionPane.showMessageDialog(null,"Please insert Username and Password");
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username / Password");
userField.setText("");
passField.setText("");
userField.requestFocus();
}
} catch (IOException d) {
d.printStackTrace();
}
}
});
buttonNewUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewUser user = new NewUser();
dispose();
}
});
}
}
class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel(){
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.BLACK,5));
try
{
image = ImageIO.read(new URL("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ8F5S_KK7uelpM5qdQXuaL1r09SS484R3-gLYArOp7Bom-LTYTT8Kjaiw"));
}
catch(Exception e)
{
e.printStackTrace();
}
GUI show = new GUI();
show.createGUI();
}
#Override
public Dimension getPreferredSize(){
return (new Dimension(430, 300));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
}
Seems to me like you have a class login (which is a JFrame, but never used as one). This login class creates a new generic "Welcome" JFrame with the ImagePanel in it. The ImagePanel calls GUI.createGUI() (which creates another JFrame, but doesn't show it) and then does absolutely nothing with it, thus it is immediately lost.
There are way to many JFrames in your code. One should be enough, perhaps two. But you got three: login, gui, and a simple new JFrame().

mouseListener lost after panel is repainted

My program will allow the user to log in first and if he is logged in,
he will click on labelone first and labeltwo next.
the program will print ("last two cards detected. starting new game..") and allow the user to click on the two labels again.
the problem I am facing is after my panel has been repainted. I cannot click on the labels
anymore.
I know that my codes provided it too lengthy but I have already attempted to tried to cut down my codes from my actual program.
I think the main focus is this block of codes in my controller class.
labelPanel.removeAll();
Dealer dealer = new Dealer();
labelPanel.add(new LabelPanel(dealer));
labelPanel.revalidate();
labelPanel.repaint();
new Controller(labelPanel,dealer);
I am not sure what happened to my mouselistener. please help
This is are the class. feel free to run it if you guys couldn't understand.
login as username-> john password -> abc
click on label one first, after that click on label two. the console will display
"last 2 cards detected, starting new game.."
after that try clicking the labels again(by right it should be clickable but it's not)
LoginPanel.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
#SuppressWarnings("serial")
public class LoginPanel extends JPanel {
private JPanel northPanel = new JPanel(new BorderLayout());
private JPanel southPanel = new JPanel(new BorderLayout());
private JPanel subSouthPanel = new JPanel(new GridBagLayout());
private JPanel subSouthPanelTwo = new JPanel(new FlowLayout());
private GridBagConstraints gbc2 = new GridBagConstraints();
private JTextField playerUsernameTF = new JTextField(15);
private JPasswordField playerPasswordTF = new JPasswordField(15);
private JButton playerLoginBtn = new JButton("Login");
public LoginPanel() {
setLayout(new BorderLayout());
gbc2.gridx = 0;
gbc2.gridy = 0;
subSouthPanel.add(new JLabel("Username"),gbc2);
gbc2.gridx = 1;
gbc2.gridy = 0;
subSouthPanel.add(playerUsernameTF,gbc2);
gbc2.gridx = 0;
gbc2.gridy = 1;
subSouthPanel.add(new JLabel("Password"),gbc2);
gbc2.gridx = 1;
gbc2.gridy = 1;
subSouthPanel.add(playerPasswordTF,gbc2);
southPanel.add(subSouthPanel,BorderLayout.CENTER);
subSouthPanelTwo.add(playerLoginBtn);
southPanel.add(subSouthPanelTwo,BorderLayout.SOUTH);
add(northPanel,BorderLayout.NORTH);
add(southPanel,BorderLayout.SOUTH);
}
public JTextField getPlayerUsernameTF() {
return playerUsernameTF;
}
public JPasswordField getPlayerPasswordTF() {
return playerPasswordTF;
}
void addListenerForPlayerLoginBtn(ActionListener actionListener) {
playerLoginBtn.addActionListener(actionListener);
}
}
LabelPanel.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class LabelPanel extends JPanel {
private JPanel panel = new JPanel(new FlowLayout());
private JLabel labelOne;
private JLabel labelTwo;
public LabelPanel(Dealer dealer) {
setLayout(new BorderLayout());
labelOne = new JLabel(new ImageIcon(dealer.hideCard()));
labelTwo = new JLabel(new ImageIcon(dealer.hideCard()));
panel.add(labelOne);
panel.add(labelTwo);
add(panel);
}
public JLabel getJLabelOne() {
return labelOne;
}
public JLabel getJLabelTwo() {
return labelTwo;
}
void listenerForJLabelOne(MouseListener listenForMouseClick) {
labelOne.addMouseListener(listenForMouseClick);
}
void listenerForJLabelTwo(MouseListener listenForMouseClick) {
labelTwo.addMouseListener(listenForMouseClick);
}
}
Dealer.java
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class Dealer {
public Dealer() {
}
public Image hideCard() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/images/blank.png"));
} catch (Exception e) {
}
return img;
}
public Image displayFirsCard() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/images/ClubsAce.png"));
} catch (Exception e) {
}
return img;
}
public Image displaySecondCard() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/images/ClubsAce.png"));
} catch (Exception e) {
}
return img;
}
}
Controller.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.Timer;
public class Controller {
private LabelPanel labelPanel;
private Dealer dealer;
private int countdown = 1;
private Timer timer = new Timer(1000,null);
private MouseHandler mouseHandler = new MouseHandler();
private int clicked = 0;
public Controller(LabelPanel labelPanel,Dealer dealer) {
clicked = 0;
this.labelPanel = labelPanel;
this.dealer = dealer;
this.labelPanel.listenerForJLabelOne(mouseHandler);
this.labelPanel.listenerForJLabelTwo(mouseHandler);
this.labelPanel.getJLabelOne().setText("Ace");
this.labelPanel.getJLabelTwo().setText("Ace");
}
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent e) {
JLabel label = (JLabel) e.getSource();
clicked++;
if(clicked == 1) {
labelPanel.getJLabelOne().setIcon((new ImageIcon(dealer.displayFirsCard())));
}
if(clicked == 2) {
labelPanel.getJLabelTwo().setIcon((new ImageIcon(dealer.displaySecondCard())));;
if(label.getText().equals(label.getText())) {
System.out.println("last 2 cards detected, starting new game..");
timer = new Timer(1000,new newGameTimer());
timer.start();
}
}
}
}
private class newGameTimer implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(countdown == 0) {
timer.stop();
clicked = 0;
labelPanel.removeAll();
Dealer dealer = new Dealer();
labelPanel.add(new LabelPanel(dealer));
labelPanel.revalidate();
labelPanel.repaint();
new Controller(labelPanel,dealer);
}
else {
countdown--;
}
}
}
}
MainFrame.java
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame {
private CardLayout cardLayout = new CardLayout();
private Dealer dealer = new Dealer();
private JPanel cardLayoutPanel = new JPanel();
private LoginPanel loginPanel = new LoginPanel();
private JFrame frame = new JFrame("Mouse CLick Test");
private JPanel dialogPanel = new JPanel();
private LabelPanel labelPanel = new LabelPanel(dealer);
public MainFrame() {
cardLayoutPanel.setLayout(cardLayout);
cardLayoutPanel.add(loginPanel,"1");
cardLayout.show(cardLayoutPanel,"1");
cardLayoutPanel.add(labelPanel,"2");
frame.add(cardLayoutPanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setSize(1024,768);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
loginPanel.addListenerForPlayerLoginBtn(new PlayerLoginBtnActionPerformed());
}
public class PlayerLoginBtnActionPerformed implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String playerUsername = loginPanel.getPlayerUsernameTF().getText();
String playerPassword = new String(loginPanel.getPlayerPasswordTF().getPassword());
if(playerUsername.equals("john") && playerPassword.equals("abc")) {
JOptionPane.showMessageDialog(dialogPanel,
"Login Successfully!"
,"Player Login",JOptionPane.PLAIN_MESSAGE);
cardLayout.show(cardLayoutPanel,"2");
new Controller(labelPanel,dealer);
}
else {
JOptionPane.showMessageDialog(dialogPanel,
"Wrong Password or Username!"
,"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[]args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
The problem is, you are adding a LabelPanel to a LabelPanel
labelPanel.add(new LabelPanel(dealer));
But you are passing the outer panel to the controller
new Controller(labelPanel, dealer);
The outer panel no longer actually contains any labels, but only contains the new LabelPanel...
A better solution would be to provide the LabelPanel with a "reset" option of some kind instead...

Categories