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

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().

Related

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.

Java EventHandler not working, why does it create new Frame?

I am trying to create an address book for a uni project and I am trying to get the GUI to be able to save the details that are input to the form to a file. Every time I click save on the GUI it creates a new Frame rather than executing the code that I have put in the even Handler. I am still fairly new to Java and I just can't see what is wrong with it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AddressBook {
static AddressBookGui addressBookGui = new AddressBookGui();
static int writeCount;
File detailsFile = new File("customerDetails.txt");
public static void saveDetails() throws IOException {
String title = addressBookGui.txtTitle.getText();
FileWriter fw = new FileWriter("customerDetails.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.println(title);
out.close();
writeCount++;
}
}
Above is the Handler class, below is the GUI.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class AddressBookGui {
private JLabel lblTitle;
public JTextField txtTitle;
private JButton btnSaveDetails;
private JPanel panel;
private JFrame frame;
public static void main(String[] args) {
new AddressBookGui();
}
public AddressBookGui() {
createPanel();
addLabels();
addTextFields();
addButtons();
frame.add(panel);
frame.setVisible(true);
}
public void createPanel() {
frame = new JFrame();
frame.setTitle("Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,950);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(null);
}
public void addLabels() {
lblTitle = new JLabel("Title");
lblTitle.setBounds(90,210,140,30);
panel.add(lblTitle);
}
public void addTextFields() {
txtTitle = new JTextField("");
txtTitle.setBounds(190,210,150,30);
panel.add(txtTitle);
}
public void addButtons() {
btnSaveDetails = new JButton("Save");
btnSaveDetails.setBounds(200,600,80,30);
btnSaveDetails.addActionListener(new SaveDetailsButton());
panel.add(btnSaveDetails);
}
public class SaveDetailsButton implements ActionListener {
public void actionPerformed(ActionEvent event) {
try {
AddressBook.saveDetails();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File did not write correctly.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
Thanks in advance.

why BufferedImage does not show full image in JLabel?

I am getting files from JFileChooser and showing them by reading with BufferedImage and putting in JLabels but there is a problem that my images are not completely shown in JLabels. Here is my code
public class ImagePreview
{
JPanel PicHolder= new JPanel();
public ImagePreview()
{
JButton GetImages = new JButton("Browse Images");
GetImages.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
CreatePreviews();
};
});
PicHolder.add(GetImages);
JFrame MainFrame = new JFrame("Image Preview");
MainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MainFrame.getContentPane().add(PicHolder);
MainFrame.pack();
MainFrame.setVisible(true);
}
public void CreatePreviews()
{
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
File[] selectedCarImages = chooser.getSelectedFiles();
for(int a=0; a<selectedImages.length; a++)
{
try
{
BufferedImage myPicture = ImageIO.read(new File(selectedImages[a].getAbsolutePath()));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
PicHolder.add(picLabel);
}
}
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(() -> {
new ImagePreview();
});
}
}
When I run this code, it shows user selected images but they are kind of automatically croped and not showing completely in JLabels.
What's wrong here? Why JLabels do not show full images?
You're adding all the components and images to a single panel having the default FlowLayout. Instead, use GridLayout for the picture labels and add the browse button to the frame's default BorderLayout, as shown below.
As tested:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ImagePreview {
JFrame mainFrame = new JFrame("Image Preview");
JPanel picHolder = new JPanel(new GridLayout(0, 1));
public ImagePreview() {
JButton getImages = new JButton("Browse Images");
getImages.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
CreatePreviews();
}
});
mainFrame.add(getImages, BorderLayout.NORTH);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new JScrollPane(picHolder));
mainFrame.pack();
mainFrame.setLocationByPlatform(true);
mainFrame.setVisible(true);
}
public void CreatePreviews() {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(mainFrame);
File[] selectedImages = chooser.getSelectedFiles();
for (int a = 0; a < selectedImages.length; a++) {
try {
BufferedImage myPicture = ImageIO.read(new File(selectedImages[a].getAbsolutePath()));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
picHolder.add(picLabel);
mainFrame.pack();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(() -> {
new ImagePreview();
});
}
}

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...

JLayeredPane formatting issue

I have a problem with my JLayeredPane, I am probably doing something incredibly simple but I cannot wrap my head around it. The problem i have is that all the components are merged together and have not order. Could you please rectify this as I have no idea. The order I am trying to do is have a layout like this
output
label1 (behind)
input (in Front)
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class window extends JFrame implements KeyListener {
/**
*
*/
private static final long serialVersionUID = 7092006413113558324L;
private static int NewSize;
public static String MainInput;
public static JLabel label1 = new JLabel();
public static JTextField input = new JTextField(10);
public static JTextArea output = new JTextArea(main.Winx, NewSize);
public window() {
super("Satine. /InDev-01/");
JLabel label1;
NewSize = main.Winy - 20;
setLayout(new BorderLayout());
output.setToolTipText("");
add(input, BorderLayout.PAGE_END);
add(output, BorderLayout.CENTER);
input.addKeyListener(this);
input.requestFocus();
ImageIcon icon = new ImageIcon("C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Roaming\\.Satine\\img\\textbox.png", "This is the desc");
label1 = new JLabel(icon);
add(label1, BorderLayout.PAGE_END);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
try {
MainMenu.start();
} catch (IOException e1) {
System.out.print(e1.getCause());
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
And the main class.
import java.awt.Container;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
public class main {
public static int Winx, Winy;
private static JLayeredPane lpane = new JLayeredPane();
public static void main(String[] args) throws IOException{
Winx = window.WIDTH;
Winy = window.HEIGHT;
window Mth= new window();
Mth.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Mth.setSize(1280,720);
Mth.setVisible(true);
lpane.add(window.label1);
lpane.add(window.input);
lpane.add(window.output);
lpane.setLayer(window.label1, 2, -1);
lpane.setLayer(window.input, 1, 0);
lpane.setLayer(window.output, 3, 0);
Mth.pack();
}
}
Thank you for your time and I don't expect the code to be written for me, all I want is tips on where I am going wrong.
I recommend that you not use JLayeredPane as the overall layout of your GUI. Use BoxLayout or BorderLayout, and then use the JLayeredPane only where you need layering. Also, when adding components to the JLayeredPane, use the add method that takes a Component and an Integer. Don't call add(...) and then setLayer(...).
Edit: it's ok to use setLayer(...) as you're doing. I've never used this before, but per the API, it's one way to set the layer.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class LayeredPaneFun extends JPanel {
public static final String IMAGE_PATH = "http://duke.kenai.com/" +
"misc/Bullfight.jpg";
public LayeredPaneFun() {
try {
BufferedImage img = ImageIO.read(new URL(IMAGE_PATH));
ImageIcon icon = new ImageIcon(img);
JLabel backgrndLabel = new JLabel(icon);
backgrndLabel.setSize(backgrndLabel.getPreferredSize());
JPanel forgroundPanel = new JPanel(new GridBagLayout());
forgroundPanel.setOpaque(false);
JLabel fooLabel = new JLabel("Foo");
fooLabel.setFont(fooLabel.getFont().deriveFont(Font.BOLD, 32));
fooLabel.setForeground(Color.cyan);
forgroundPanel.add(fooLabel);
forgroundPanel.add(Box.createRigidArea(new Dimension(50, 50)));
forgroundPanel.add(new JButton("bar"));
forgroundPanel.add(Box.createRigidArea(new Dimension(50, 50)));
forgroundPanel.add(new JTextField(10));
forgroundPanel.setSize(backgrndLabel.getPreferredSize());
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(backgrndLabel.getPreferredSize());
layeredPane.add(backgrndLabel, JLayeredPane.DEFAULT_LAYER);
layeredPane.add(forgroundPanel, JLayeredPane.PALETTE_LAYER);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(new JScrollPane(new JTextArea("Output", 10, 40)));
add(layeredPane);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("LayeredPaneFun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new LayeredPaneFun());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories