So we randomly choose a number between 1 to 6 and whatever is rolled will have an image uploaded of a die face that corresponds to the number. It's compiling, but I get an exception thread I don't understand.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Random;
import java.awt.FlowLayout;
public class Butttin {
private static JLabel label;
public static void main(String[] args) {
JFrame frame = new JFrame("Rolling Dice Game");
JPanel panel = new JPanel();
JButton buttonRoll = new JButton("Roll!");
buttonRoll.addActionListener(new buttonRoll());
panel.setLayout(new GridLayout(5, 2, 5, 5));
panel.add(label);
frame.setVisible(true);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
}
private static class buttonRoll implements ActionListener {
private java.util.Random random = new java.util.Random();
public void actionPerformed(ActionEvent event) {
int max = 6;
int min = 1;
ImageIcon img;
int rolledNumber = random.nextInt(max - min + 1) + min;
String command = event.getActionCommand();
if (command == "Roll!") {
if ("Roll!".equals(command)) {
ImageIcon imageIcon = new ImageIcon("die 1.jpg");
label = new JLabel(imageIcon);
} else if (rolledNumber == 2){
ImageIcon imageIcon = new ImageIcon("die 2.jpg");
label = new JLabel(imageIcon);
} else if (rolledNumber == 3){
ImageIcon imageIcon = new ImageIcon("die 3.jpg");
label = new JLabel(imageIcon);
} else if (rolledNumber == 4){
ImageIcon imageIcon = new ImageIcon("die 4.jpg");
label = new JLabel(imageIcon);
} else if (rolledNumber == 5){
ImageIcon imageIcon = new ImageIcon("die 5.jpg");
label = new JLabel(imageIcon);
} else if (rolledNumber == 6){
ImageIcon imageIcon = new ImageIcon("die 6.jpg");
label = new JLabel(imageIcon);
}
}
}
}
}
The problem is that you do not initialize your JLabel before you add it to your JPanel. The easiest thing to do would be to initialize it directly:
private static JLabel label = new JLabel();
And in your actionPerformed method, instead of creating a new JLabel every time and replacing the old one, just use its setIcon method.
label.setIcon(imageIcon);
On another note, when working with Swing components (creating components, adding components, etc), it should be run on the Event Dispatch Thread:
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//...
}
});
Related
My friend has given me a practice problem regarding prime number. Numbers 1 to n needs to be displayed in a new window. I also can't figure out on how I can use the input I got from panel1 to panel2. I'm very new to GUI since I haven't gone there when I studied Java a few years back. Hope you can help!
I haven't done much with the GUI since I don't really know where to start, but I've watched youtube videos and have gone through many sites on how to start with a GUI. Here's what I have done:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sieve
{
private JPanel contentPane;
private MyPanel input;
private MyPanel2 sieve;
private void displayGUI()
{
JFrame frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
input = new MyPanel(contentPane);
sieve = new MyPanel2();
contentPane.add(input, "Input");
contentPane.add(sieve, "Sieve of Erasthoneses");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JTextField text;
private JLabel label1;
private JButton OK;
private JButton cancel;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
label1 = new JLabel ("Enter a number from 1 to n:");
text = new JTextField(1000);
OK = new JButton ("OK");
cancel = new JButton ("Cancel");
setPreferredSize (new Dimension (500, 250));
setLayout (null);
text.setBounds (145, 50, 60, 25);
OK.setBounds (450, 30, 150, 50);
cancel.setBounds (250, 30, 150, 50);
OK.setSize(315, 25);
OK.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add (text);
add (label1);
add (OK);
add (cancel);
}
}
class MyPanel2 extends JPanel {
private JFrame frame;
private JLabel label;
JLabel label1;
public MyPanel2()
{
frame = new JFrame("Sieve of Eratosthenes");
label = new JLabel("The Prime numbers from 2 to " + num + " are");
num1 = num;
boolean[] bool = new boolean[num1];
for (int i = 0; i < bool.length; i++)
{
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num1); i++)
{
if(bool[i] == true)
{
for(int j = (i*i); j < num1; j = j+i)
{
bool[j] = false;
}
}
}
for (int i = 2; i< bool.length; i++)
{
if(bool[i]==true)
{
label1 = new JLabel(" " + label[i]);
}
}
}
}
Thanks for your help!
Your code had many compilation errors.
Oracle has a helpful tutorial, Creating a GUI With JFC/Swing. Skip the Netbeans section. Review all the other sections.
I reworked your two JPanels. When creating a Swing application, you first create the GUI. After the GUI is created, you fill in the values to be displayed.
I created the following GUI. Here's the input JPanel.
Here's the Sieve JPanel.
I used Swing layout managers to create the two JPanels. Using null layouts and absolute positioning leads to many problems.
I created the sieve JPanel, then populated it with values. You can see how I did it in the source code.
Here's the complete runnable code. I made the classes inner classes.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Eratosthenes {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Eratosthenes().displayGUI();
}
});
}
private CardLayout cardLayout;
private JFrame frame;
private JPanel contentPane;
private InputPanel inputPanel;
private SievePanel sievePanel;
private void displayGUI() {
frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
cardLayout = new CardLayout();
contentPane.setLayout(cardLayout);
inputPanel = new InputPanel();
sievePanel = new SievePanel();
contentPane.add(inputPanel.getPanel(), "Input");
contentPane.add(sievePanel.getPanel(), "Sieve");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void cancelAction() {
frame.dispose();
System.exit(0);
}
public class InputPanel {
private JPanel panel;
private JTextField textField;
public InputPanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JPanel entryPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label = new JLabel("Enter a number from 1 to n:");
entryPanel.add(label);
textField = new JTextField(10);
entryPanel.add(textField);
panel.add(entryPanel, BorderLayout.BEFORE_FIRST_LINE);
JPanel buttonPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton okButton = new JButton("OK");
buttonPanel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int inputNumber = valueOf(textField.getText().trim());
if (inputNumber < 2) {
return;
}
sievePanel.updatePrimeLabel(inputNumber);
sievePanel.updatePrimeNumbers(inputNumber);
cardLayout.show(contentPane, "Sieve");
}
private int valueOf(String number) {
try {
return Integer.valueOf(number);
} catch (NumberFormatException e) {
return -1;
}
}
});
JButton cancelButton = new JButton("Cancel");
buttonPanel.add(cancelButton);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelAction();
}
});
okButton.setPreferredSize(cancelButton.getPreferredSize());
panel.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
return panel;
}
public JPanel getPanel() {
return panel;
}
}
public class SievePanel {
private JLabel primeLabel;
private JList<Integer> primeNumbersList;
private JPanel panel;
public SievePanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Font titlefont = panel.getFont().deriveFont(Font.BOLD, 24f);
JPanel textPanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Sieve of Eratosthenes");
titleLabel.setFont(titlefont);
titleLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(titleLabel, BorderLayout.BEFORE_FIRST_LINE);
primeLabel = new JLabel(" ");
primeLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(primeLabel, BorderLayout.AFTER_LAST_LINE);
panel.add(textPanel, BorderLayout.BEFORE_FIRST_LINE);
primeNumbersList = new JList<>();
JScrollPane scrollPane = new JScrollPane(primeNumbersList);
panel.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Return");
panel.add(button, BorderLayout.AFTER_LAST_LINE);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cardLayout.show(contentPane, "Input");
}
});
return panel;
}
public void updatePrimeLabel(int inputNumber) {
primeLabel.setText("The prime numbers from 2 to " +
inputNumber + " are:");
}
public void updatePrimeNumbers(int inputNumber) {
DefaultListModel<Integer> primeNumbers =
new DefaultListModel<>();
boolean[] bool = new boolean[inputNumber];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(inputNumber); i++) {
if (bool[i] == true) {
for (int j = (i * i); j < inputNumber; j = j + i) {
bool[j] = false;
}
}
}
for (int i = 2; i < bool.length; i++) {
if (bool[i] == true) {
primeNumbers.addElement(i);
}
}
primeNumbersList.setModel(primeNumbers);
}
public JPanel getPanel() {
return panel;
}
}
}
How can I change between the pictures with help of clicking the button.
I made a x variable because then I could make different if-statements but that didn't work for me, probably because I did something wrong... Here is my code so far:
public class Main extends JFrame{
private JButton changePic;
private JPanel panel;
private JLabel pic1;
private JLabel pic2;
private JLabel pic3;
private JLabel picture;
private int x = 0;
public Main(){
panel = new JPanel();
add(panel);
changePic = new JButton("Change Button");
panel.add(changePic);
pic1 = new JLabel(new ImageIcon("pic1.png"));
pic2 = new JLabel(new ImageIcon("pic.png"));
pic3 = new JLabel(new ImageIcon("pic3.png"));
panel.add(pic1);
panel.add(pic2);
panel.add(pic3);
changePic.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource() == changePic){
}
}
});
getContentPane().setBackground(Color.white);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
Main fr = new Main();
}
}
public class Main extends JFrame{
private JButton changePic;
private JPanel panel;
private JLabel pic1;
private int x = 0;
public Main(){
panel = new JPanel();
add(panel);
changePic = new JButton("Change Button");
panel.add(changePic);
pic1 = new JLabel();
panel.add(pic1);
ImageIcon icon1 = new ImageIcon("pic1.gif");
ImageIcon icon2 = new ImageIcon("pic2.gif");
ImageIcon icon3 = new ImageIcon("pic3.gif");
changePic.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource() == changePic){
if(x == 0){
pic1.setIcon(icon1);
}else if(x == 1){
pic1.setIcon(icon2);
}else if(x == 2){
pic1.setIcon(icon3);
}
Main.this.pack();
x++;
if(x > 2) x = 0;
}
}
});
getContentPane().setBackground(Color.white);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
Main fr = new Main();
}
}
you don't need multiple JLabels, use 3 ImageIcons instead.
you need to call JFrame's pack() every time you had UI Changes (in
this case, changing image)
I am trying to make a desktop application in Java Swing. I am trying to create image slider in frame and I got it. Now problem in that I want to set the specific area for imagelabel in that frame. How can I do this? I want to set imagelabel in left side. I am posting my snapshot which I am getting after running my program.
Here is my code
public class ImageSlider extends JPanel implements ActionListener {
private static final int MAX = 20;
private static final Font sans = new Font("SansSerif", Font.PLAIN, 16);
private static final Border border =
BorderFactory.createMatteBorder(4, 16, 4, 16, Color.BLUE);
private List<String> list = new ArrayList<String>(MAX);
private List<ImageIcon> cache = new ArrayList<ImageIcon>(MAX);
private JLabel imageLabel = new JLabel();
//label = new JLabel( image, SwingConstants.CENTER);
private JButton prevButton = new JButton();
private JButton nextButton = new JButton();
private JComboBox favorites;
public ImageSlider() {
this.setLayout(new BorderLayout());
list.add("c.jpg");
list.add("a0.png");
list.add("yellow.png");
list.add("a0.png");
list.add("c.jpg");
for (int i = 0; i < list.size(); i++) cache.add(i, null);
ImageIcon image = new ImageIcon("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\a0.png");
JLabel titleLabel = new JLabel(image, SwingConstants.CENTER);
// titleLabel.setText("ImageSlider");
titleLabel.setHorizontalAlignment(JLabel.CENTER);
titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 24));
titleLabel.setBorder(border);
this.add(titleLabel, BorderLayout.NORTH);
imageLabel.setIcon(getImage(0));
imageLabel.setAlignmentX(LEFT_ALIGNMENT);
imageLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabel.setBorder(border);
this.add(imageLabel, BorderLayout.CENTER);
favorites = new JComboBox(
list.toArray(new String[list.size()]));
favorites.setActionCommand("favs");
favorites.addActionListener(this);
prevButton.setText("\u22b2Prev");
prevButton.setFont(sans);
prevButton.setActionCommand("prev");
prevButton.addActionListener(this);
nextButton.setText("Next\u22b3");
nextButton.setFont(sans);
nextButton.setActionCommand("next");
nextButton.addActionListener(this);
JPanel controlPanel = new JPanel();
controlPanel.add(prevButton);
controlPanel.add(favorites);
controlPanel.add(nextButton);
controlPanel.setBorder(border);
this.add(controlPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String cmd = ae.getActionCommand();
if ("favs".equals(cmd)) {
int index = favorites.getSelectedIndex();
ImageIcon image = getImage(index);
imageLabel.setIcon(image);
if (image != null) imageLabel.setText("");
else imageLabel.setText("Image not available.");
}
if ("prev".equals(cmd)) {
int index = favorites.getSelectedIndex() - 1;
if (index < 0) index = list.size() - 1;
favorites.setSelectedIndex(index);
}
if ("next".equals(cmd)) {
int index = favorites.getSelectedIndex() + 1;
if (index > list.size() - 1) index = 0;
favorites.setSelectedIndex(index);
}
}
public JButton getDefault() { return nextButton; }
// Return the (possibly cached) image having the given index.
private ImageIcon getImage(int index) {
ImageIcon image = cache.get(index);
if (image != null) return image;
String name = "/images/" + list.get(index);
URL url = ImageSlider.class.getResource(name);
if (url != null) {
image = new ImageIcon(url);
}
cache.set(index, image);
return image;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageSlider go = new ImageSlider();
frame.add(go);
frame.setTitle("ImageSlider");
// frame.setSize(400, 300);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setVisible(true);
go.getDefault().requestFocusInWindow();
}
});
}
}
How can I achieve my goal?
The easiest way to achieve this is to put the imageLabel into a JPanel with a FlowLayout. Then add that panel to the bigger BorderLayout.
So change:
this.add(imageLabel, BorderLayout.CENTER);
To something like:
JPanel imageConstrain = new JPanel(new FlowLayout(SwingConstants.LEFT));
imageConstrain.add(imageLabel);
this.add(imageConstrain, BorderLayout.CENTER);
Hey I could use help debugging this program. The code is not mine, it is from an answer to a question and I wanted to try it but I get a NullPointerException and can't figure out where the problem is. I think the problem may be image paths but I am not sure so I could use help.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class CircleImages {
private int score = 0;
private JTextField scoreField = new JTextField(10);
public CircleImages() {
scoreField.setEditable(false);
final ImageIcon[] icons = createImageIcons();
final JPanel iconPanel = createPanel(icons, 8);
JPanel bottomLeftPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomLeftPanel.add(new JLabel("Score: "));
bottomLeftPanel.add(scoreField);
JPanel bottomRightPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JButton newGame = new JButton("New Game");
bottomRightPanel.add(newGame);
JButton quit = new JButton("Quit");
bottomRightPanel.add(quit);
JPanel bottomPanel = new JPanel(new GridLayout(1, 2));
bottomPanel.add(bottomLeftPanel);
bottomPanel.add(bottomRightPanel);
newGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
reset(iconPanel, icons);
score = 0;
scoreField.setText(String.valueOf(score));
}
});
JFrame frame = new JFrame();
frame.add(iconPanel);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void reset(JPanel panel, ImageIcon[] icons) {
Component[] comps = panel.getComponents();
Random random = new Random();
for(Component c : comps) {
if (c instanceof JLabel) {
JLabel button = (JLabel)c;
int index = random.nextInt(icons.length);
button.setIcon(icons[index]);
}
}
}
private JPanel createPanel(ImageIcon[] icons, int gridSize) {
Random random = new Random();
JPanel panel = new JPanel(new GridLayout(gridSize, gridSize));
for (int i = 0; i < gridSize * gridSize; i++) {
int index = random.nextInt(icons.length);
JLabel label = new JLabel(icons[index]);
label.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
score += 1;
scoreField.setText(String.valueOf(score));
}
});
label.setBorder(new LineBorder(Color.GRAY, 2));
panel.add(label);
}
return panel;
}
private ImageIcon[] createImageIcons() {
String[] files = {"DarkGrayButton.png",
"BlueButton.png",
"GreenButton.png",
"LightGrayButton.png",
"OrangeButton.png",
"RedButton.png",
"YellowButton.png"
};
ImageIcon[] icons = new ImageIcon[files.length];
for (int i = 0; i < files.length; i++) {
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
}
return icons;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleImages();
}
});
}
}
Your problem is here:
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
You don't have the required images in your project, so getClass().getResource() will return null and you will have a NullPointerException in the constructor of ImageIcon.
What you have to do is put the following files in your project:
/circleimages/DarkGrayButton.png
/circleimages/BlueButton.png
/circleimages/GreenButton.png
/circleimages/LightGrayButton.png
/circleimages/OrangeButton.png
/circleimages/RedButton.png
/circleimages/YellowButton.png
I'm stuck using Button and JButton
expected result.. ( all information working )
http://i.stack.imgur.com/3qX7v.png
and what I have
http://i.stack.imgur.com/a4gao.png
I want to replace this:
Button butRock = new Button("Rock");
butRock.addActionListener(this);
ButtPan.add(butRock);
To This:
BufferedImage buttonIcon = ImageIO.read(new File("rock.jpg"));
JButton butRock = new JButton(new ImageIcon(buttonIcon));
butRock.addActionListener(this);
ButtPan.add(butRock);
I'm stuck because when I replace Button to JButton the program doesn't work properly...when I use this JButton
Question: How to replace the button with picture and that program still work properly...
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class gui extends JFrame implements ActionListener
{
public JLabel JWoL,JWoLPlayer,JWoLPC,JNumWin,JNumLose,JNumTie, logo;
public JLabel JWinT,JLoseT,JTieT, rpsP, rpsC, result;
JPanel LabelsPan;
static final int WINS = 0, LOSSES = 1, DRAWS = 2;
int[] counts = new int[3];
String[] strings = {"| You Win", "| You Lose", "| Draw"};
JLabel[] labels = {JNumWin, JNumLose, JNumTie};
#SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
gui theWindow = new gui();
theWindow.show();
}
private void record(int type)
{
JWoL.setText(strings[type]);
counts[type]++;
labels[type].setText(""+counts[type]);
}
public gui() throws IOException
{
JPanel logo = new JPanel();
logo.setLayout(new GridLayout(1,1));
BufferedImage myPicture = ImageIO.read(new File("logo.jpg"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
add(picLabel);
JPanel ButtPan=new JPanel();
ButtPan.setLayout(new GridLayout(1,3));
BufferedImage buttonIcon = ImageIO.read(new File("rock.jpg"));
JButton butRock = new JButton(new ImageIcon(buttonIcon));
butRock.addActionListener(this);
ButtPan.add(butRock);
Button butPaper = new Button("Paper");
butPaper.addActionListener(this);
ButtPan.add(butPaper);
Button butScissors = new Button("Scissors");
butScissors.addActionListener(this);
ButtPan.add(butScissors);
JWoLPlayer = new JLabel();
JWoLPC = new JLabel();
JWoL= new JLabel();
JLabel rpsPlayer= new JLabel("| Your Choice: ");
JLabel rpsComputer= new JLabel("| Computers Choice: ");
setTitle("| RoPaS GAME |");
LabelsPan=new JPanel();
LabelsPan.setLayout(new GridLayout(3,2));
rpsP = new JLabel();
LabelsPan.add(rpsPlayer);
LabelsPan.add(JWoLPlayer);
rpsC = new JLabel();
LabelsPan.add(rpsComputer);
LabelsPan.add(JWoLPC);
result =new JLabel();
LabelsPan.add(JWoL,"Center");
JPanel WLPan = new JPanel();
WLPan.setLayout(new GridLayout(3, 2));
JWinT = new JLabel("Wins: ");
JLoseT = new JLabel("Losses: ");
JTieT = new JLabel("Ties: ");
WLPan.add(JWinT);
JNumWin = new JLabel();
WLPan.add(JNumWin);
WLPan.add(JLoseT);
JNumLose = new JLabel();
WLPan.add(JNumLose);
WLPan.add(JTieT);
JNumTie = new JLabel();
WLPan.add(JNumTie);
JLabel[] labels1 = {JNumWin, JNumLose, JNumTie};
labels = labels1;
JPanel TwoPanesN1=new JPanel();
TwoPanesN1.setLayout(new BorderLayout());
TwoPanesN1.add(logo,"North");
TwoPanesN1.add(LabelsPan,"West");
TwoPanesN1.add(WLPan,"East");
getContentPane().setLayout(new GridLayout(3,2));
getContentPane().add(ButtPan);
getContentPane().add(TwoPanesN1);
Font fontDisplay = new Font("Arial", Font.BOLD, 16);
JWoL.setFont(fontDisplay);
LabelsPan.setFont(fontDisplay);
setSize(400,250);
setVisible(true);
setResizable(false);
addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent ev){System.exit(0);}});
}
public void Play(String PlayerChoice)
{
String PCchoice=PCansw();
JWoLPC.setText(PCchoice);
if(PlayerChoice.equals(PCchoice))
record(DRAWS);
else if(PlayerChoice.equals("Rock"))
if(PCchoice.equals("Paper"))
record(LOSSES);
else
record(WINS);
else if(PlayerChoice.equals("Paper"))
if(PCchoice.equals("Scissors"))
record(LOSSES);
else
record(WINS);
else if(PlayerChoice.equals("Scissors"))
if(PCchoice.equals("Rock"))
record(LOSSES);
else
record(WINS);
}
public String PCansw()
{
String rpsPC2="";
int rpsPC=(int)(Math.random( )*3)+1;
if(rpsPC==1)
rpsPC2= "Rock";
else if(rpsPC==2)
rpsPC2= "Paper";
else if(rpsPC==3)
rpsPC2= "Scissors";
return rpsPC2;
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Exit"))
System.exit(0);
else
{
JWoLPlayer.setText(e.getActionCommand());
Play(e.getActionCommand());
}
}
}
The problem is that you are using getActionCommand to determine which JButton was clicked but this property is not set by default in Swing. You would have to call
butRock.setActionCommand("Rock");
java.awt.Button automatically uses the label property as the ActionCommand if it not explicitly set. From the docs
If the command name is null (default) then this method returns the label of the button.
Some asides:
Better to avoid mixing heavy & lightweight components and use lightweight components throughout the application.
As your Rock, Paper, Scissors buttons have identical functionality, consider using an Action.
A direct instance JFrame is typically used rather than extending the class
Use Initial Threads
Window#show is deprecated. Use Window#setVisible.
Don't use System.exit - See more here