ive recently just got back into programming Swing and java in general and am quite rusty. My program im trying to finish is seeming to compile going by eclipse, but it wont run, its telling me it doesn't have a main type. And its not giving me an error notifications so im kind of stuck here at the moment.
I've never seen this error before so not sure what it is, or cant remember what it is if I have. Any ideas what im doing wrong or should fix to get this to run, thanks:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.Timer;
import javax.swing.Timer.*;
import javax.swing.event.*;
public class FamousLocations extends JFrame implements ChangeListener, ActionListener, Runnable
{
private static final long serialVersionUID = 0;
JMenuBar p = new JMenuBar();
int Selected = 0;
ImageIcon a = new ImageIcon("america.jpg");
ImageIcon j = new ImageIcon("Japan.jpg");
ImageIcon c = new ImageIcon("china.jpg");
ImageIcon i = new ImageIcon("ireland.jpg");
ImageIcon t = new ImageIcon("thailand.jpg");
ImageIcon ca = new ImageIcon("Niagra-Falls.jpg");
Icon[] pics = {a,j,c,i,t,ca};
private JLabel ImageLabel = new JLabel(pics[Selected]);
String america = ("Grand Canyon, America");
String japan = ("Kinkaku-ji (The Golden Pavilion) Kyoto, Japan");
String china = ("Mount Huangshan, China");
String ireland = ("Newgrange, Ireland");
String thailand = ("Bangkok ,Thailand");
String canada = ("Niagra Falls , Canada");
String[] Box = {america, japan, china, ireland, thailand, canada};
JTextArea lo = new JTextArea(Box[Selected]);
String InfoGrand = new String ("desciption");
String InfoHiro = new String ("desciption");
String InfoMount = new String ("desciption");
String InfoNew = new String ("desciption");
String InfoBang = new String ("desciption");
String InfoNiag = new String ("desciption");
String[] Info = {InfoGrand, InfoHiro, InfoMount, InfoNew, InfoBang, InfoNiag};
JTextArea ta = new JTextArea(Info[Selected]);
private JTabbedPane tp = new JTabbedPane();
public JSlider slider = new JSlider();
private JPanel dropd = new JPanel();
private JPanel checkb = new JPanel();
private JPanel ImagePan = new JPanel();
private JPanel InfoPan = new JPanel();
private JCheckBox slider1 = new JCheckBox ("Show Slider" , true);
private JCheckBox slideshow1 = new JCheckBox ("Slideshow", false);
JComboBox com1 = new JComboBox(Box);
public FamousLocations(){
setTitle("My Bucket List");
getContentPane().setLayout(new BorderLayout());
getContentPane().setBackground(Color.white);
getContentPane().setSize(1000,1000);
getContentPane().add(dropd);
getContentPane().add(slider,BorderLayout.SOUTH);
getContentPane().add(slider1);
getContentPane().add(slideshow1);
getContentPane().add(tp);
slider.setValue(0);
slider.addChangeListener(this);
slider.setOrientation(JSlider.HORIZONTAL);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setMajorTickSpacing(1);
slider.setMaximum(5);
slider.setSnapToTicks(true);
ImagePan.add(ImageLabel);
checkb.add(com1);
checkb.add(slider1);
checkb.add(slideshow1);
tp.addTab("Photo", ImagePan);
tp.addTab("Description of Area", InfoPan);
tp.addTab("Index and Options", checkb);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setEditable(false);
ta.setVisible(true);
ta.setSize(400,400);
slider1.setVisible(true);
slider1.addActionListener(this);
slideshow1.setVisible(true);
slideshow1.addActionListener(this);
com1.addActionListener(this);
com1.addActionListener(this);
JMenu help = new JMenu("HELP");
JMenuItem AL1 = help.add("how to use");
JMenuItem AL2 = help.add("EXIT");
p.add(help);
this.setJMenuBar(p);
AL1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null,"error");
}
});
AL2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
setSize(250,250);
setVisible(true);
}
public void change(){
JTextArea ta=new JTextArea(Box[Selected]);
ImagePan.removeAll();
ImagePan.add(ImageLabel=new JLabel(pics[Selected]));
InfoPan.removeAll();
InfoPan.add(ImageLabel=new JLabel(Info[Selected]));
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setEditable(false);
ta.setVisible(true);
ta.setSize(400,400);
ImagePan.repaint();
validateTree();
}
public void run(){
for(int y = 0;y==y+1; y++){
slider.setValue(y);
try{
Thread.sleep (1000);
}
catch (Exception e) {}
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==slider1) {slider.setVisible(slider1.isSelected());}
else if(e.getSource()==com1)
{Selected=com1.getSelectedIndex(); change();}
else if(e.getSource()==slideshow1)
{new Thread(this).start(); }
}
public void stateChanged(ChangeEvent e) {
if(e.getSource()==slider){Selected=slider.getValue();change();}
}
}
Related
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
public class DiceFrame extends JFrame{
ImageIcon[] dice_im = new ImageIcon[7];
String score="start";
JPanel mainPanel= new JPanel();
JPanel scorePanel=new JPanel();
JPanel buttonPanel =new JPanel();
JLabel picLabel = new JLabel();
JTextArea scorefield = new JTextArea();
JButton roll= new JButton("roll the dice");
JButton save = new JButton("save");
ActionListener action;
ActionListener output;
public DiceFrame(){
super();
setSize(600, 600);
setTitle("Dice Program");
loadImage();
getContentPane().add(mainPanel, BorderLayout.CENTER);
getContentPane().add(scorePanel, BorderLayout.EAST);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.add(save);
buttonPanel.add(roll);
mainPanel.add(picLabel);
picLabel.setIcon(dice_im[0]);
scorePanel.add(scorefield);
scorefield.setText(score);
action = new DiceActionListener();
roll.addActionListener(action);
}
private void loadImage(){
dice_im [0]= new ImageIcon("1.jpg");
dice_im[1] = new ImageIcon("2.jpg");
dice_im[2] = new ImageIcon("3.JPG");
dice_im[3] = new ImageIcon("4.JPG");
dice_im[4] = new ImageIcon("5.JPG");
dice_im[5] = new ImageIcon("6.JPG");
}
public static void main(String args[]){
DiceFrame frame = new DiceFrame();
frame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class DiceActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Random rg = new Random();
int k = rg.nextInt(6) + 1;
picLabel.setIcon(dice_im[k]);
}
}
class SaveActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) { //NEW code
String out_file_name = "dice_score.txt";
try {
File outputfile = new File(out_file_name);
PrintStream out = new PrintStream(
new FileOutputStream(outputfile));
out.println(score);
out.flush();`
out.close();
} catch (IOException y) {
System.out.println("IO problem.");
}
}
}
}
How can i make save button work by writing this code?
Whenever i run it roll button works but the save button doesn't work?
this is a program for the rolling the dice but i need to make the save button work, Can anyone please help with that?
how can i link dice_score.txt file to this program?
Action listener is not added to Save Button.
save.addActionListener(new SaveActionListener());
Add this at the end of DiceFrame():
save.addActionListener(new SaveActionListener());
See
action = new DiceActionListener();
roll.addActionListener(action);
well you have to follow this pattern and do
SaveActionListener action2 = new SaveActionListener ();
save.addActionListener(action2);
Although in reality it is not necessary to create a named instance and you can simply do
save.addActionListener (new SaveActionListener ());
I've created an auto typer because I've always wanted to know how they work. Only problem is when I click the stop button, it doesn't stop and it freezes my system.
I've tried changing the interval time, and it still doesn't stop when the stop button is pushed.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class AutoSpammer{
private static int interval;
private static Timer timerMain;
private static JTextField txtSpam;
private static JTextField txtInterval;
private static JButton btnStart;
private static JButton btnStop;
public static void main(String[]args){
ActionListener taskSpam = new ActionListener(){
public void actionPerformed(ActionEvent evt) {
sendkeys(txtSpam.getText());
}
};
ActionListener taskStartTimer = new ActionListener(){
public void actionPerformed(ActionEvent evt){
timerMain.setDelay(Integer.parseInt(txtInterval.getText()));
timerMain.start();
btnStart.setEnabled(false);
btnStop.setEnabled(true);
txtInterval.setEnabled(false);
}
};
ActionListener taskStopTimer = new ActionListener(){
public void actionPerformed(ActionEvent evt){
timerMain.stop();
btnStart.setEnabled(true);
btnStop.setEnabled(false);
txtInterval.setEnabled(true);
}
};
btnStart = new JButton("Start Spam");
btnStop = new JButton("Stop Spam");
JLabel lbl1 = new JLabel("Enter Text:");
JLabel lbl2 = new JLabel("Interval:");
timerMain = new Timer(1,taskSpam);
txtSpam = new JTextField("Enter text:", 13);
txtInterval = new JTextField("3000",3);
btnStart.addActionListener(taskStartTimer);
btnStop.addActionListener(taskStopTimer);
btnStop.setEnabled(false);
JPanel intervalpane = new JPanel();
intervalpane.add(lbl2,BorderLayout.EAST);
intervalpane.add(txtInterval,BorderLayout.WEST);
JPanel bottompane = new JPanel();
bottompane.add(btnStart,BorderLayout.EAST);
bottompane.add(btnStop,BorderLayout.CENTER);
bottompane.add(intervalpane,BorderLayout.WEST);
JPanel toppane = new JPanel();
toppane.add(lbl1,BorderLayout.EAST);
toppane.add(txtSpam,BorderLayout.NORTH);
JPanel pane = new JPanel(new BorderLayout());
pane.add(toppane,BorderLayout.NORTH);
pane.add(bottompane,BorderLayout.SOUTH);
JFrame frame = new JFrame("Spammer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(pane);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
private static void sendkeys(String text) {
try {
Robot robot = new Robot();
text = text.toUpperCase();
for(int i = 0; i < text.length(); i++)
robot.keyPress(text.charAt(i));
robot.keyPress(KeyEvent.VK_ENTER);
}catch(java.awt.AWTException exc) {
System.out.println("error");
}
}
}
program works fine for me. Stop does stop the robot. I added a simple System.out what has been pressed and this stops
I was trying some stuff in Swing (Java), but getting very strange results.
I am getting a String from JTextArea.getText() method and adding "\n" to it. This resultant string I am writing into a file, using BufferedWriter which is chaining through FileOutputStream to a file. But the new line character "\n" is not creating new line in the .txt file.
How can I fix this issue?
My Code is here:
package quizCardGame;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
public class QuizCardBuilder extends JFrame {
private static final long serialVersionUID = 1L;
private JTextArea question;
private JTextArea answer;
private Font font;
private ArrayList<QuizCard> deck;
private int countOfDeck;
private JLabel countLable;
public QuizCardBuilder() {
super();
deck = new ArrayList<QuizCard>();
buildGUI();
}
public static void main(String[] args) {
QuizCardBuilder app = new QuizCardBuilder();
}
public void buildGUI() {
font = new Font(Font.SERIF, Font.BOLD, 12);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
this.getContentPane().add(BorderLayout.CENTER, panel);
JPanel stats = new JPanel();
countLable = new JLabel("Count: " + countOfDeck);
stats.add(countLable);
this.getContentPane().add(BorderLayout.SOUTH, stats);
JLabel qLable = new JLabel("Question");
panel.add(qLable);
question = new JTextArea(5, 30);
question.setLineWrap(true);
question.setWrapStyleWord(true);
question.setFont(font);
JScrollPane qScroller = new JScrollPane(question);
qScroller
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(qScroller);
JLabel aLable = new JLabel("Answer");
panel.add(aLable);
answer = new JTextArea(5, 30);
answer.setLineWrap(true);
answer.setWrapStyleWord(true);
answer.setFont(font);
JScrollPane aScroller = new JScrollPane(answer);
aScroller
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
aScroller
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(aScroller);
JButton nextButton = new JButton("Next");
nextButton.addActionListener(new NextCardListener());
panel.add(nextButton);
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem newMenuItem = new JMenuItem("New");
JMenuItem saveMenuItem = new JMenuItem("Save");
fileMenu.add(newMenuItem);
fileMenu.add(saveMenuItem);
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
newMenuItem.addActionListener(new NewMenuListener());
saveMenuItem.addActionListener(new SaveMenuListener());
this.setSize(350, 350);
this.setVisible(true);
}
public class SaveMenuListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
deck.add(new QuizCard(question.getText(), answer.getText()));
JFileChooser fileSave = new JFileChooser();
fileSave.showSaveDialog(null);
saveFile(fileSave.getSelectedFile());
}
}
public void saveFile(File file) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for (QuizCard card : deck) {
bw.write(card.getQuestion() + "/");
bw.write(card.getAnswer() + "\n");
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class NewMenuListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
deck.clear();
countOfDeck = deck.size();
countLable.setText("Count: " + countOfDeck);
clearText();
}
}
public class NextCardListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
deck.add(new QuizCard(question.getText(), answer.getText()));
countOfDeck = deck.size();
countLable.setText("Count: " + countOfDeck);
clearText();
}
}
private void clearText() {
question.setText("");
answer.setText("");
}
}
Use instead BufferedWriter.newLine() which:
Writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline ('\n') character.
This is my FileIOManagement class that I want to handle all of the reading from text files etc that grabs data to display in the GUI.
This is the code for my current FileIOManagement class:
package swinging;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
public class FileIOManagement {
private ArrayList<String> nameList = new ArrayList<String>();
private ArrayList<String> courseList = new ArrayList<String>();
private ArrayList<String> semesterList = new ArrayList<String>();
private ArrayList<String> moderatorList = new ArrayList<String>();
private ArrayList<String> programList = new ArrayList<String>();
private ArrayList<String> majorList = new ArrayList<String>();
public FileIOManagement(){
readTextFile();
}
private void readTextFile(){
try{
Scanner scan = new Scanner(new File("Course.txt"));
while(scan.hasNextLine()){
String line = scan.nextLine();
String[] tokens = line.split("~");
String course = tokens[0].trim();
String examiner = tokens[1].trim();
String moderator = tokens[2].trim();
String semester = tokens[3].trim();
String program = tokens[4].trim();
String major = tokens[5].trim();
courseList.add(course);
semesterList.add(semester);
nameList.add(examiner);
moderatorList.add(moderator);
programList.add(program);
majorList.add(major);
HashSet hs = new HashSet();
hs.addAll(nameList);
nameList.clear();
nameList.addAll(hs);
Collections.sort(nameList);
}
scan.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
This is the class I need the ArrayList data passed to. As you can see I am attempting to populate comboBox1 and comboBox2 with data I am attempting to get via ArrayList:
package swinging;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.border.EmptyBorder;
public class ReportGUI extends JFrame{
//Fields
private JButton viewAllReports = new JButton("View All Program Details");
private JButton viewPrograms = new JButton("View Programs and Majors Associated with this course");
private JButton viewTaughtCourses = new JButton("View Courses this Examiner Teaches");
private JLabel courseLabel = new JLabel("Select a Course: ");
private JLabel examinerLabel = new JLabel("Select an Examiner: ");
private JPanel panel = new JPanel(new GridLayout(6,2,4,4));
FileIOManagement fileName;
ArrayList<String> names = new ArrayList<String>(fileName.getNameList());
ArrayList<String> courses = new ArrayList<String>(fileName.getCourseList());
public ReportGUI(){
reportInterface();
allReportsBtn();
// fileRead();
comboBoxes();
}
private void reportInterface(){
setTitle("Choose Report Specifications");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
add(panel, BorderLayout.CENTER);
setSize(650,200);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private void allReportsBtn(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(70, 50, 70, 25));
panel.add(viewAllReports);
viewAllReports.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
new AllDataGUI();
}
});
add(panel, BorderLayout.LINE_END);
}
private void comboBoxes(){
panel.setBorder(new EmptyBorder(0, 5, 5, 10));
String[] comboBox1Array = names.toArray (new String[names.size()]);
JComboBox comboBox1 = new JComboBox(comboBox1Array);
panel.add(examinerLabel);
panel.add(comboBox1);
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new ViewCourseGUI();
}
});
String[] comboBox2Array = courses.toArray(new String[courses.size()]);
JComboBox comboBox2 = new JComboBox(comboBox2Array);
panel.add(courseLabel);
panel.add(comboBox2);
panel.add(viewPrograms);
viewPrograms.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new ViewProgramGUI();
}
});
add(panel, BorderLayout.LINE_START);
}
}
However when I attempt to compile, I get a NullPointerException as in the below image:
What am I doing wrong here?
What you did is that you are trying to get the fileName.getNameList() where fileName was never instantiated as a result it will return null.
problem:
FileIOManagement fileName; //was not instantiated
ArrayList<String> names = new ArrayList<String>(fileName.getNameList()); //fileName.getNameList() is null
ArrayList<String> courses = new ArrayList<String>(fileName.getCourseList()); //fileName.getCourseList() is null
solution:
Instantiate your FileIOManagement fileName before getting the List of it.
Figured it out.
public class ReportGUI extends JFrame{
//Fields
private JButton viewAllReports = new JButton("View All Program Details");
private JButton viewPrograms = new JButton("View Programs and Majors Associated with this course");
private JButton viewTaughtCourses = new JButton("View Courses this Examiner Teaches");
private JLabel courseLabel = new JLabel("Select a Course: ");
private JLabel examinerLabel = new JLabel("Select an Examiner: ");
private JPanel panel = new JPanel(new GridLayout(6,2,4,4));
private FileIOManagement fileManage = new FileIOManagement();
private ArrayList<String> nameList = new ArrayList();
private ArrayList<String> courseList = new ArrayList();
// filename = fileManage.nameList();
//FileIOManagement fileName = new FileIOManagement(fileName.getNameList());
public void getData(){
nameList = fileManage.getNameList();
courseList = fileManage.getCourseList();
}
public ReportGUI(){
getData();
reportInterface();
allReportsBtn();
comboBoxes();
}
private void reportInterface(){
setTitle("Choose Report Specifications");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
add(panel, BorderLayout.CENTER);
setSize(650,200);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private void allReportsBtn(){
JPanel panel = new JPanel(new GridLayout(1,1));
panel.setBorder(new EmptyBorder(70, 50, 70, 25));
panel.add(viewAllReports);
viewAllReports.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
new AllDataGUI();
}
});
add(panel, BorderLayout.LINE_END);
}
private void comboBoxes(){
panel.setBorder(new EmptyBorder(0, 5, 5, 10));
String[] comboBox1Array = nameList.toArray (new String[nameList.size()]);
JComboBox comboBox1 = new JComboBox(comboBox1Array);
panel.add(examinerLabel);
panel.add(comboBox1);
panel.add(viewTaughtCourses);
viewTaughtCourses.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new ViewCourseGUI();
}
});
String[] comboBox2Array = courseList.toArray(new String[courseList.size()]);
JComboBox comboBox2 = new JComboBox(comboBox2Array);
panel.add(courseLabel);
panel.add(comboBox2);
panel.add(viewPrograms);
viewPrograms.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new ViewProgramGUI();
}
});
add(panel, BorderLayout.LINE_START);
}
}
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