I'm getting there step by step but have come across yet another hurdle.
The title is pretty self-explanatory, what I'm wondering is how would I be able to use the JButton "logout" with ActionListener to be able to swap the card in my main LoginScreen.class?
I've had a few whacks but to no avail. Also any tips on improving my coding and format are welcome. Thanks in advance.
Here's my code:
LoginScreen.class
/*Login Screen class for allowing
multiple levels of access and security*/
//Imports library files
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;
//Creates a LoginScreen class that extends the JFrame library class
class LoginScreen extends JFrame {
//Creates a swing components and CardLayout for organising JPanels
JPanel cardScreen;
JPanel screen = new JPanel();
Image ProgramIcon = Toolkit.getDefaultToolkit().getImage("imageIco.png");
ImageIcon logo = new ImageIcon ("Logo.png");
JLabel icon = new JLabel(logo);
JLabel username = new JLabel("Username");
JLabel password = new JLabel("Password");
JTextField user = new JTextField(18);
JPasswordField pass = new JPasswordField(18);
JButton login = new JButton("Login");
JLabel errorInfo = new JLabel("");
int WIDTH = 800;
int HEIGHT = 500;
int currentPanel = 1;
public static void main(String[] args){
//Sets the GUI (Look and Feel) to the NimROD theme
try {UIManager.setLookAndFeel("com.nilo.plaf.nimrod.NimRODLookAndFeel");}
catch (UnsupportedLookAndFeelException e){ JOptionPane.showMessageDialog(null, "GUI Load Error: Unsupported");}
catch (ClassNotFoundException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: NimROD Missing");}
catch (InstantiationException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: Instantiation Missing");}
catch (IllegalAccessException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: Illegal Access"); }
//Creates a new LoginScreen via the LoginScreen method
LoginScreen LS = new LoginScreen();
}
public LoginScreen(){
//Adds the JPanel to the JFrame and set the JFrame's properties
//Sets the main JPanel to CardLayout platform and adds other JPanels it
final CardLayout cardL = new CardLayout();
cardScreen = new JPanel();
cardScreen.setLayout(cardL);
cardScreen.add(screen, "1");;
BaseScreen base = new BaseScreen();
cardScreen.add(base, "2");
this.setIconImage(ProgramIcon);
this.setTitle("Login");
this.setSize(WIDTH,HEIGHT);
this.setResizable(false);
this.add(cardScreen);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
//Place the components on the JPanel and set their absolute posistions
screen.setLayout(null);
screen.add(username);
screen.add(password);
screen.add(user);
screen.add(pass);
screen.add(login);
screen.add(icon);
Dimension iconSize = icon.getPreferredSize();
Dimension usernameSize = username.getPreferredSize();
Dimension passwordSize = password.getPreferredSize();
Dimension loginSize = login.getPreferredSize();
Dimension userSize = user.getPreferredSize();
Dimension passSize = pass.getPreferredSize();
username.setBounds(252,170,usernameSize.width,usernameSize.height);
password.setBounds(495,170,passwordSize.width,passwordSize.height);
user.setBounds(180,200,userSize.width,userSize.height);
pass.setBounds(420,200,passSize.width,passSize.height);
login.setBounds(375,250,loginSize.width,loginSize.height);
icon.setBounds(250,50,iconSize.width,iconSize.height);
this.setVisible(true);
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
//Checks if both the user and pass text fields are empty
if((user.getText().equals("")) && (pass.getText().equals(""))){
//Displays an error in the form of a label and adds it to the JPanel
errorInfo.setText("Please enter username and password");
screen.add(errorInfo);
errorInfo.setForeground(Color.RED);
Dimension errorInfoSize = errorInfo.getPreferredSize();
errorInfo.setBounds(300,300,errorInfoSize.width,errorInfoSize.height);
}
if((user.getText().equals("admin"))&&(pass.getText().equals("password"))){
cardL.show(cardScreen,"2");
}
}
});
}
}
BaseScreen.class
//Basescreen class
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class BaseScreen extends JPanel{
JPanel screen = this;
JButton logout = new JButton("Logout");
ImageIcon title = new ImageIcon("title.png");
JLabel header = new JLabel(title);
public BaseScreen(){
screen.setLayout(null);
screen.add(logout);
screen.add(header);
Dimension headerSize = header.getPreferredSize();
Dimension logoutSize = logout.getPreferredSize();
logout.setBounds(720,440,logoutSize.width,logoutSize.height);
header.setBounds(0,0,headerSize.width,headerSize.height);
screen.setVisible(true);
}
}
If your'e wondering why I've gone through all the effort to separate out the JPanel into another class, this is because I want to use my BaseScreen class to be inherited by many other JPanel classes and add each one as a card so being able to use a JButton in one of the classes is vital for the structure of the program to work. Hopefully I haven't gone about this the complete wrong way and won't need an etire rewrite of the program.
-Zalx
Related
public class Main {
public static class GUI extends JFrame {
public GUI() {
//Title
super("Draw Card");
//panel
Panel buttonsPanel = new Panel();
Panel imagePanel = new Panel();
//App layout
setSize(600,480);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
//gc value
gc.gridy=0;gc.gridx=0;gc.gridwidth=1;gc.gridheight=1;gc.weightx=0.5;gc.weighty=0;gc.fill = GridBagConstraints.HORIZONTAL;
//layout in layout
GridLayout buttonsLayout = new GridLayout(1,2);
GridLayout imageLayout = new GridLayout(4,13);
buttonsPanel.setLayout(buttonsLayout);
imagePanel.setLayout(imageLayout);
//add
add(buttonsPanel,gc);
//change gc value
gc.gridy=1;gc.weighty=1;gc.gridheight=9;gc.fill = GridBagConstraints.BOTH;
//add
add(imagePanel,gc);
//button
JButton btn = new JButton("Draw card");
buttonsPanel.add(btn);
buttonsPanel.add(new JButton("Remove cards."));
//event
btn.addActionListener(e ->{
//just image from link
Image image = null;
try {
URL url = new URL("https://www.improvemagic.com/wp-content/uploads/2020/11/kj.png");
image = ImageIO.read(url);
} catch (IOException ee) {
ee.printStackTrace();
}
//add to label then add label to panel
JLabel label = new JLabel(new ImageIcon(image));
imagePanel.add(label);
revalidate();
});
//set visible
setVisible(true);
}
}
public static void main(String[] args){
GUI test = new GUI();
}
}
EDITED: I dont think i can make it shorter without destroying everything, only one image and it's online, got the same problem that i have.
I've tryed a couple a thing on the pannel and the layout to give the image size for each cell but didnt worked.
Hello ! I have some trouble to keep the full image, i didn't find a single way of getting them fully, did I miss something about those layout ?
I'm still not used to post here ask me if i need to add things ! Thank you !
I have a baglayout that contain 2 gridlayout (one for button and another one where I want to add random card by clicking on one button)
Introduction
I reworked your code to create the following GUI.
Here's the same GUI after drawing a few cards.
The JFrame worked out to be 822 x 420 pixels. In Swing, you work from the inside out. You create Swing components, put the Swing components in JPanels, put the JPanels in a JFrame, and see what the size of the JFrame turns out to be.
Explanation
Whenever I create a Swing GUI, I use the model/view/controller (MVC) pattern. This pattern implies that you create the model first, then the view, then the controller. For complex projects, the process is more iterative than waterfall.
The MVC pattern in Swing development means:
The view reads information from the model.
The view does not modify the model.
The controller modifies the model and updates the view.
There's usually not one controller class "to rule them all". Each Action or ActionListener class is responsible for its portion of the model and the view.
Model
I assumed you eventually wanted to read more than one card image, so I created a Card class. This class holds the card Image and whatever information you want about a playing card, including descriptive text, suit, int value, and int suit value.
I created a SomeCardGameModel class to hold a blank card, a card, and an int cardCount. The cardCount helps ensure that we don't draw more than 52 cards.
Reducing the size of the card image turned out to be a bit of a challenge. I used a search engine to find relevant bits of code and put them together in the SomeCardGameModel class. The main point is that you do all of the model creation before you create the view.
View
I started the Swing application with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components will be created and executed on the Event Dispatch Thread.
I separated the creation of the JFrame and the JPanels into separate methods. This makes the code much easier for people to understand what you're doing.
The JFrame has a default BorderLayout. I used a BorderLayout for the main JPanel and GridLayouts for the button JPanel and the card JPanel. I added some spacing between the Swing components so you can see individual cards.
Controller
After creating a model and a view, your anonymous controller class is simplified. You should be able to create the controller for the "remove Cards" JButton.
Code
Here's the complete runnable code. I made all the additional classes inner classes so I can post this code as one block.
import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SomeCardGame implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new SomeCardGame());
}
private JLabel[] cardLabels;
private final SomeCardGameModel model;
public SomeCardGame() {
this.model = new SomeCardGameModel();
}
#Override
public void run() {
JFrame frame = new JFrame("Draw Card");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
System.out.println(frame.getSize());
}
public JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(createButtonPanel(), BorderLayout.NORTH);
panel.add(createCardPanel(), BorderLayout.CENTER);
return panel;
}
public JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridLayout(0, 2, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton drawButton = new JButton("Draw card");
panel.add(drawButton);
drawButton.addActionListener(e -> {
int count = model.getCardCount();
if (count < 52) {
cardLabels[model.getCardCount()].setIcon(
new ImageIcon(model.getCard().getCardImage()));
model.incrementCardCount(1);
}
});
JButton removeButton = new JButton("Remove cards");
panel.add(removeButton);
return panel;
}
public JPanel createCardPanel() {
JPanel panel = new JPanel(new GridLayout(0, 13, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
this.cardLabels = new JLabel[52];
for (int index = 0; index < cardLabels.length; index++) {
cardLabels[index] = new JLabel(new ImageIcon(
model.getBlankCard().getCardImage()));
panel.add(cardLabels[index]);
}
return panel;
}
public class SomeCardGameModel {
private int cardCount;
private final Card blankCard;
private final Card card;
public SomeCardGameModel() {
this.blankCard = new Card(createBlankCard());
BufferedImage image = readCard();
Image reducedImage = image.getScaledInstance(
56, 78, Image.SCALE_SMOOTH);
this.card = new Card(toBufferedImage(reducedImage));
this.cardCount = 0;
}
private BufferedImage createBlankCard() {
BufferedImage image = new BufferedImage(56, 78,
BufferedImage.TYPE_INT_RGB);
return image;
}
private BufferedImage readCard() {
try {
URL url = new URL("https://www.improvemagic.com/"
+ "wp-content/uploads/2020/11/kj.png");
return ImageIO.read(url);
} catch (IOException ee) {
ee.printStackTrace();
return null;
}
}
private BufferedImage toBufferedImage(Image img) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
BufferedImage bimage = new BufferedImage(
img.getWidth(null), img.getHeight(null),
BufferedImage.TYPE_INT_RGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
public Card getBlankCard() {
return blankCard;
}
public Card getCard() {
return card;
}
public int getCardCount() {
return cardCount;
}
public void incrementCardCount(int increment) {
this.cardCount += increment;
}
}
public class Card {
private final BufferedImage cardImage;
public Card(BufferedImage cardImage) {
this.cardImage = cardImage;
}
public BufferedImage getCardImage() {
return cardImage;
}
}
}
I am trying to create a Blackjack app with swing and I am having difficulty adding new cards when a player clicks hit button. I feel like it has something to do with the JLabel not being validated but I have no idea what that really means or how to fix the issues. Please help...
I am really new to Java swing so it might seem very intuitive problems but I hope someone can explain kindly...
Below is the code that I currently have and it deals two cards each for both dealer and player without duplication of cards but is unable to display newly dealt cards even though the card is chosen as I can see them on console...
import javax.swing.*;
import java.awt.*;
#SuppressWarnings("serial")
public class PlayerHand extends JPanel {
//declaring private vars
private JLabel cardPonTable[] = new JLabel[11];
private int cardP[] = new int[11];
private Image cardPImage[] = new Image[11];
private int cardOnTableCount = 0; //counter for number of cards on the table
public PlayerHand(boolean firstDeal){
setLayout(null);
/**
* Deals the first two cards for the player
*/
if (firstDeal == true) { //run this code if true
//playerHand config
setBackground(new Color(238, 238, 238));
setLayout(null);
JLabel playersHandLabel = new JLabel("Player's Hand"); //creates a label indicating the bottom half of the screen is the player's hand
//player's hand label config
playersHandLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 25));
playersHandLabel.setHorizontalAlignment(SwingConstants.CENTER);
playersHandLabel.setBounds(192, 314, 200, 80);
add(playersHandLabel); //add player's hand label to the container
//creates JLabel for two of the player's card, set the positions, and add to the container
cardPonTable[0] = new JLabel("");
cardPonTable[0].setBounds(80, 6, 220, 320);
add(cardPonTable[0]);
cardPonTable[1] = new JLabel("");
cardPonTable[1].setBounds(340, 6, 220, 320);
add(cardPonTable[1]);
System.out.println("Player's cards"); //indicate that the following is the player's dealt card on the console
CardDeal.createDeck(); //create a deck
//deal two card for the player
cardP[0] = CardDeal.cardDeal();
cardP[1] = CardDeal.cardDeal();
//get the image from the src folder
cardPImage[0] = new ImageIcon (this.getClass().getResource(cardP[0]+".png")).getImage();
cardPImage[1] = new ImageIcon (this.getClass().getResource(cardP[1]+".png")).getImage();
cardPonTable[0].setIcon(new ImageIcon (cardPImage[0])); //set the JLabel of the card to the image chosen above
cardOnTableCount++; //increase the counter by one
cardPonTable[1].setIcon(new ImageIcon (cardPImage[1])); //set the JLabel of the card to the image chosen above
cardOnTableCount++; //increase the counter by one
}
/**
* Do not deal the first two cards (instance made)
*/
}
public void cardAdded() throws Exception {
//cardP1onTable.setBounds(cardP1onTable.getX()-50, cardP1onTable.getY(), (int)(WIDTH*0.7), (int)(HEIGHT*0.7));
//cardP2onTable.setBounds(cardP2onTable.getX()-50, cardP2onTable.getY(), (int)(WIDTH*0.7), (int)(HEIGHT*0.7));
PlayerHand newDealt = new PlayerHand(false); //creates an instance of playerHand method (send false as a parameter so that the method won't deal two cards again)
System.out.println("Player's card dealt");
newDealt.setLayout(null);
cardPonTable[cardOnTableCount] = new JLabel("");
cardPonTable[cardOnTableCount].setBounds(192, 6, 220, 320);
newDealt.add(cardPonTable[cardOnTableCount]);
cardP[cardOnTableCount] = CardDeal.cardDeal();
cardPImage[cardOnTableCount] = new ImageIcon (newDealt.getClass().getResource(cardP[cardOnTableCount]+".png")).getImage();
cardPonTable[cardOnTableCount].setIcon(new ImageIcon (cardPImage[cardOnTableCount]));
cardOnTableCount++;
}
}
This code below is the JPanel that lets the player choose hit or stay
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
#SuppressWarnings("serial")
public class ChoiseBar extends JPanel{
private JButton hitButton;
private JButton stayButton;
public ChoiseBar() {
Dimension dim = getPreferredSize();
dim.height = 100;
setPreferredSize(new Dimension(1200, 100));
hitButton = new JButton("HIT");
hitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
PlayerHand.cardAdded();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
stayButton = new JButton("STAY");
setLayout(new GridLayout(0, 2, 0, 0));
add(hitButton);
add(stayButton);
}
}
This is the MainFrame class where PlayerHand, DealerHand, and ChoiceBar is added.
import javax.swing.JFrame;
import java.awt.Color;
#SuppressWarnings("serial")
public class MainFrame extends JFrame{
//declaring private vars
private DealerHand dealerHand;
private PlayerHand playerHand;
private ChoiseBar choiseBar;
public MainFrame() {
super("TABLE"); //calling the "TABLE" method in BJ_APP
playerHand = new PlayerHand(true); //creates an instance of playerHand (firstDeal is true as it is the first deal)
//playerHand config
playerHand.setForeground(new Color(0, 0, 0));
playerHand.setBackground(new Color(238, 238, 238));
playerHand.setLocation(300, 625);
playerHand.setSize(600, 400);
dealerHand = new DealerHand(); //creates an instance of dealerHand
//playerHand config
dealerHand.setLocation(300, 31);
dealerHand.setSize(600, 429);
choiseBar = new ChoiseBar(); //creates an instance of choiseBar
//choiseBar config
choiseBar.setSize(800, 120);
choiseBar.setLocation(214, 472);
getContentPane().setLayout(null); //mainFrame uses absolute layout
//add these three containers to mainFrame
getContentPane().add(choiseBar);
getContentPane().add(playerHand);
getContentPane().add(dealerHand);
setSize(1200,1080); //set the size of mainFrame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //the program will terminated when mainFrame is closed
this.setVisible(true); //set mainFrame visible
}
}
What exactly does "keeping a reference" mean?
You do it all the time:
hitButton = new JButton("HIT");
Above you create an instance of a JButton a keep a reference to it.
Then in your code you change a property of the button by using:
hitButton.addActionListener(new ActionListener() ...
Your custom panels are no different. You create a custom class with methods that you want to execute.
So somewhere in your code you need logic like:
PlayHand playHandPanel = new PlayHand();
ChoiceBar choiceBarPanel = new ChoiceBar( playHandPanel );
frame.add( playHandPanel );
frame.add( choiceBar );
Then in the constructor of your ChoiceBar you save the reference to the "playHandPanel" as an instance variable in your class. And then in the ActionListener for the button you can now invoke the cardAdded() method.
I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?
A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!
Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.
Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).
Currently working on a school project in which I am making a wheel of fortune replica in Java. I have a panel of JButtons within a class called buttonPanel, and a separate class, wheelGUI, which acts as the class that the program runs through. What I want to happen is when the JButton spin is pressed on the GUI, it assigns a random value from String[] wheelStuff to a String, spinValue,using the method spinWheel which acts as the parameter for the JTextField results, and then displays that random value on the Cyan box in the GUI. In non-technical terms, when the button spin is pressed, display a random value in the Cyan box which acts as the current players' spin value. Here is the code for the class buttonPanel
package wheelOfFortune;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class buttonPanels extends JPanel
implements ActionListener
{
private JButton spin, solve, buyVowel, guess, reset, end, cont;
Color yungMoney = new Color(0, 180, 100);
private static String[] wheelStuff = new String[]{"Bankrupt", "Lose a Turn", "$5000", "$600", "$500", "$300", "$800", "$550", "$400", "$900", "$350", "$450", "$700"};
public buttonPanels()
{
setBackground(yungMoney);
spin = new JButton("Spin!");
spin.addActionListener(this);
solve = new JButton("Solve the Puzzle");
solve.addActionListener(this);
buyVowel = new JButton("Buy a Vowel");
buyVowel.addActionListener(this);
guess = new JButton("Guess a Letter");
guess.addActionListener(this);
reset = new JButton("Reset");
reset.addActionListener(this);
cont = new JButton("Continue");
cont.addActionListener(this);
JPanel buttonPanel = new JPanel(new GridLayout(3, 1, 5, 5));
buttonPanel.setPreferredSize(new Dimension(300,380));
buttonPanel.setBackground(yungMoney);
buttonPanel.add(spin);
buttonPanel.add(guess);
buttonPanel.add(buyVowel);
buttonPanel.add(solve);
buttonPanel.add(cont);
buttonPanel.add(reset);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
JButton b = (JButton)e.getSource();
b.addActionListener(this);
if(b==spin)
{
wheelGUI.spinWheel(wheelStuff);
}
repaint();
}
}
And here is the code for the main class, wheelGUI
package wheelOfFortune;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Random;
import javax.swing.*;
public class wheelGUI extends JFrame implements ActionListener {
private playerPlate player1, player2, player3;
Color yungMoney = new Color(0, 180, 100);
private String fileName = "M:/wheelOfFortune/src/wheelOfFortune/img/wheel1.png";
private String cat;
private static String spinValue = "";
private static String[] wheelStuff = new String[]{"Bankrupt", "Lose a Turn", "$5000", "$600", "$500", "$300", "$800", "$550", "$400", "$900", "$350", "$450", "$700"};
private static JTextField results;
public wheelGUI() {
super("Butt Stuff!");
ImageIcon i = new ImageIcon(fileName);
JLabel picture = new JLabel(i);
player1 = new playerPlate("Garrett", Color.RED);
player2 = new playerPlate("Jonny", Color.YELLOW);
player3 = new playerPlate("Robert", Color.BLUE);
buttonPanels buttons = new buttonPanels();
letterBoard letters = new letterBoard();
catBox category = new catBox(cat);
inputField input = new inputField();
Box wall = Box.createHorizontalBox();
wall.add(player1);
wall.add(Box.createHorizontalStrut(5));
wall.add(player2);
wall.add(Box.createHorizontalStrut(5));
wall.add(player3);
JPanel result = new JPanel();
result.setBackground(yungMoney);
JTextField results = new JTextField(spinValue);
results.setBackground(Color.CYAN);
results.setHorizontalAlignment(JTextField.CENTER);
results.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
results.setPreferredSize(new Dimension(150,100));
results.setFont(new Font("Impact", Font.PLAIN, 28));
results.setEditable(false);
result.add(results);
Box catInput = Box.createVerticalBox();
catInput.add(category);
catInput.add(Box.createVerticalStrut(50));
catInput.add(result);
catInput.add(Box.createVerticalStrut(100));
catInput.add(input);
Container c = getContentPane();
c.setBackground(yungMoney);
c.add(buttons, BorderLayout.EAST);
c.add(wall, BorderLayout.SOUTH);
c.add(letters, BorderLayout.NORTH);
c.add(picture, BorderLayout.WEST);
c.add(catInput, BorderLayout.CENTER);
}
public static String spinWheel(String[] wheelStuff)
{
Random rnd = new Random();
wheelStuff[rnd.nextInt(wheelStuff.length)] = spinValue;
return spinValue;
}
public static void main(String[] args) {
wheelGUI window = new wheelGUI();
window.setBounds(50, 50, 1024, 768);
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setResizable(false);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
// logic for any additional panels. other logics should be in individual
// classes.
}
}
Thanks for your help! Note: all of the code in wheelGUI that isn't related to something previously stated can be ignored, it's from various other classes.
The use of static fields in this manner is not recommended.
Instead, the buttonsPanel should be taking a reference of the wheelGUI. This will allow the buttonsPanel to call the required methods on the wheelGUI when it needs to.
A better solution would be to use a model which can sit between the two UIs and model the logic, firing events as parts of the model change
Your primary problem is your shadowing the results textfield. That is, you've declared and class level, static field and then redeclared it within your constructor
Change the following line in your wheelGUI constructor
JTextField results = new JTextField(spinValue);
To
results = new JTextField(spinValue);
This will mean when you set the text on the results field, you will be setting the value of the correct instance of the field.
I've been in a bit of a pickle here. I've been ripping my hair out over how to accomplish such a task. For my International Bacc I have to fill out certain criteria for my Program dossier and one of them is using inheritance and passing parameters etc. I'm in the stage of making my prototype and wanted to achieve the effect of using multiple JPanels within the same JFrame. I've achieved this rather crudely with setVisivble() and adding both panels to the JFrame. I understand that I can use the CardLayout for this and will probably implement it as soon as possible.
All in all what I'm trying to achieve is that I have a login button the loads the other jpanel, is there a way of doing this in separate classes? Because when I seem to use the myframe.add(new mypanelClass()) it creates an entirely new JFrame! Essentially the miniclass I have in this file I want to separate out into another class. Also how can I make a logout button on the other panel bring me back to the login screen from another class? Thanks in advance for any help.
Here's my code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;
class Menu extends JFrame
{
JFrame container = new JFrame();
JPanel screen = new JPanel();
JPanel screenBase = new JPanel();
Image ProgramIcon = Toolkit.getDefaultToolkit().getImage("imageIco.png");
ImageIcon logo = new ImageIcon ("Logo.png");
JLabel icon = new JLabel(logo);
JLabel username = new JLabel("Username");
JLabel password = new JLabel("Password");
JTextField user = new JTextField(18);
JPasswordField pass = new JPasswordField(18);
JButton login = new JButton("Login");
JLabel errorInfo = new JLabel("");
int WIDTH = 800;
int HEIGHT = 500;
JPanel screen2 = new JPanel();
JButton logout = new JButton("Logout");
ImageIcon title = new ImageIcon("title.png");
JLabel header = new JLabel(title);
public static void main(String[] args)
{
try {UIManager.setLookAndFeel("com.nilo.plaf.nimrod.NimRODLookAndFeel");}
catch (UnsupportedLookAndFeelException e){ JOptionPane.showMessageDialog(null, "GUI Load Error: Unsupported");}
catch (ClassNotFoundException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: NimROD Missing");}
catch (InstantiationException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: Instantiation Missing");}
catch (IllegalAccessException e) { JOptionPane.showMessageDialog(null, "GUI Load Error: Illegal Access"); }
Menu admin = new Menu();
}
public Menu()
{
container.setIconImage(ProgramIcon);
container.setTitle("Login");
container.setSize(WIDTH,HEIGHT);
container.setResizable(false);
container.setVisible(true);
container.add(screen);
container.setDefaultCloseOperation(EXIT_ON_CLOSE);
screen.add(username);
screen.add(password);
screen.add(user);
screen.add(pass);
screen.add(login);
screen.add(icon);
screen.setLayout(null);
Dimension iconSize = icon.getPreferredSize();
Dimension usernameSize = username.getPreferredSize();
Dimension passwordSize = password.getPreferredSize();
Dimension loginSize = login.getPreferredSize();
Dimension userSize = user.getPreferredSize();
Dimension passSize = pass.getPreferredSize();
username.setBounds(252,170,usernameSize.width,usernameSize.height);
password.setBounds(495,170,passwordSize.width,passwordSize.height);
user.setBounds(180,200,userSize.width,userSize.height);
pass.setBounds(420,200,passSize.width,passSize.height);
login.setBounds(375,250,loginSize.width,loginSize.height);
icon.setBounds(250,50,iconSize.width,iconSize.height);
ButtonHandler handle = new ButtonHandler();
login.addActionListener(handle);
new BaseScreen();
}
public class BaseScreen
{
public BaseScreen()
{
container.add(screen2);
screen2.setLayout(null);
screen2.add(logout);
screen2.add(header);
screen2.setVisible(false);
Dimension headerSize = header.getPreferredSize();
Dimension logoutSize = logout.getPreferredSize();
logout.setBounds(720,440,logoutSize.width,logoutSize.height);
header.setBounds(0,0,headerSize.width,headerSize.height);
setDefaultCloseOperation(EXIT_ON_CLOSE);
ButtonHandler handle = new ButtonHandler();
logout.addActionListener(handle);
}
}
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == login)
{
if((user.getText().equals("")) && (pass.getText().equals("")))
{
errorInfo.setText("Please enter username and password");
screen.add(errorInfo);
errorInfo.setForeground(Color.RED);
Dimension errorInfoSize = errorInfo.getPreferredSize();
errorInfo.setBounds(300,300,errorInfoSize.width,errorInfoSize.height);
}
if((user.getText().equals("admin"))&&(pass.getText().equals("password")))
{
screen.setVisible(false);
screen2.setVisible(true);
container.setTitle("Menu");
user.setText("");
pass.setText("");
}
}
if (event.getSource() == logout)
{
screen2.setVisible(false);
screen.setVisible(true);
container.setTitle("Login");
}
}
}
}
You'll need to stop instantiating a JFrame within that class that extends JFrame, that's 2 JFrames right there. Write JFrame container = this; then use your IDE's inline feature to inline the container field.
If BaseScreen needs access to the JFrame 'this' you can pass that value into BaseScreen's constructor and BaseScreen can store that value as a field. There's no magic 'linking the classes together', you tell one object about another one by passing values around. If what I'm saying is unfamiliar you'll need to visit the constructors section of the Java tutorial - http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html