Why is the reset button for my game not working? - java

I have made a reset button which doesn't take away the focus of the KeyListener so that the game could still be playable after the clicking of the button. The rest of the button is all about resetting locations, emptying arraylists and arrays and so on. But it seems like whenever I click the restart button, the player object does go to its starting point, x = 2 y = 0. But after that whenever I make a move I see the man object/picture move to the position in was in before so the restart button isn't working at all. The player object is actually still at the location in which it stood when the restart button was clicked. I have read that there might be a second panel added beneath and thus the real panel not changing? I'm not sure and require your help.
My question specific: Why does the reset button not suffice for the changing of the player/man objects location, why is it failing?
package riddle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameFrame extends JFrame {
private JPanel p2;
private JButton reset;
private GameDraw component;
private Man m;
public GameFrame() {
this.setTitle("Riddle Man");
this.setSize(719, 850);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
component = new GameDraw();
m = new Man(component);
component.addKeyListener(m);
component.requestFocus();
createButton();
createPanel();
}
private void createButton() {
reset = new JButton("Restart");
ActionListener listener = new ClickListener();
reset.addActionListener(listener);
}
private void createPanel() {
p2 = new JPanel();
p2.setLayout(null);
component.setBounds(0, 0, 800, 800);
reset.setBounds(0, 725, 100, 50);
p2.add(component);
p2.add(reset);
add(p2);
}
class ClickListener implements ActionListener {
public ClickListener(){
}
#Override
public void actionPerformed(ActionEvent e) {
reset.setFocusable(false);
component.resetGame();
}
}
}
package riddle;
import org.apache.commons.lang3.StringUtils;
import java.awt.Color;
import static java.awt.Frame.NORMAL;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class GameField {
public String[][] field;
private String grass, wall, note, end, theRiddle, theAnswer;
private ArrayList<Integer> arrayG;
private ArrayList<Integer> arrayW;
private ArrayList<Integer> arrayN;
private ArrayList<Integer> arrayE;
private Riddle riddle;
private int instantRight, count, wrongs, retries;
private boolean ok = false;
public GameField() {
field = new String[10][10];
grass = "Grass";
wall = "Wall";
note = "Note";
end = "End";
theRiddle = "";
theAnswer = "";
instantRight = 0;
count = 0;
wrongs = 0;
retries = 0;
arrayG = new ArrayList<Integer>(Arrays.asList(0, 9, 10, 19, 20, 29, 30, 39, 40, 49, 50, 59, 60, 69, 70, 79, 80, 89, 90, 99));
arrayW = new ArrayList<Integer>(Arrays.asList(1, 3, 4, 5, 6, 7, 8, 11, 18, 21, 22, 23, 24, 25, 26, 28, 31, 38, 41, 43, 44, 45, 46, 47, 48, 51, 58, 61, 62, 63, 64, 65, 66, 68, 71, 78, 81, 83, 84, 85, 86, 87, 88, 91, 98));
arrayN = new ArrayList<Integer>(Arrays.asList(17, 35, 32, 54, 57, 76, 72, 94));
arrayE = new ArrayList<Integer>(Arrays.asList(97));
riddle = new Riddle();
fillField();
}
public String checkField(int x, int y) {
String result = "";
if (field[y][x] == "Wall") {
result = wall;
} else if (field[y][x] == "Note") {
result = note;
} else if (field[y][x] == "End") {
result = end;
endGame();
}
return result;
}
private void fillField() {
int k = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (arrayG.contains(k)) {
field[i][j] = grass;
} else if (arrayW.contains(k)) {
field[i][j] = wall;
} else if (arrayN.contains(k)) {
field[i][j] = note;
} else if (arrayE.contains(k)) {
field[i][j] = end;
}
k++;
}
}
}
public void setField(int x, int y) {
field[x][y] = null;
}
public boolean riddleTime() {
boolean check = false;
theRiddle = riddle.generateRiddle();
theAnswer = riddle.getAnswer();
while (!check) {
check = checkReply(theRiddle, theAnswer);
}
return check;
}
public boolean checkReply(String question, String answer) {
ImageIcon image = new ImageIcon(this.getClass().getResource("/resources/bad.png"));
ImageIcon image2 = new ImageIcon(this.getClass().getResource("/resources/good.png"));
String[] option = {"Yes", "Quit"};
String reply = JOptionPane.showInputDialog(question);
if (reply.contains(answer.toLowerCase()) || reply.contains(StringUtils.capitalize(answer)) || reply.contains(answer.toUpperCase())) {
JOptionPane.showMessageDialog(null, riddle.getResponseC(), "", NORMAL, image2);
ok = true;
if (count == 0) {
instantRight++;
} else {
count = 0;
}
} else {
wrongs++;
int selectedValue = JOptionPane.showOptionDialog(null, riddle.getResponseW(), "", JOptionPane.YES_NO_OPTION, JOptionPane.YES_NO_OPTION, image, option, NORMAL);
if (selectedValue == JOptionPane.YES_OPTION) {
checkReply(question, answer);
retries++;
}
if (selectedValue == JOptionPane.NO_OPTION) {
System.exit(0);
}
count++;
}
return ok;
}
private void endGame() {
ImageIcon bad = new ImageIcon(this.getClass().getResource("/resources/endingbad.png"));
ImageIcon good = new ImageIcon(this.getClass().getResource("/resources/endinggood.png"));
ImageIcon info = new ImageIcon(this.getClass().getResource("/resources/info.png"));
if (instantRight >= 6) {
JOptionPane.showMessageDialog(null, "", "", NORMAL, good);
JOptionPane.showMessageDialog(null, "<html><center><br><br>Instant Rights: " + instantRight + "\n" + "\n" + "Wrongs: " + wrongs + "\n" + "\n" + "Retries: " + retries + "\n" + "\n" + " Wisdom Level: " + indicate(instantRight, wrongs, retries), " Statistics", NORMAL, info);
} else {
JOptionPane.showMessageDialog(null, "", "", NORMAL, bad);
JOptionPane.showMessageDialog(null, "\n" + "Instant Rights: " + instantRight + "\n" + "\n" + "Wrongs: " + wrongs + "\n" + "\n" + "Retries: " + retries + "\n" + "\n" + " Wisdom Level: " + indicate(instantRight, wrongs, retries), " Statistics", NORMAL, info);
}
}
public String indicate(int instantRight, int wrongs, int retries) {
String level = "";
if (instantRight >= 6 && wrongs <= 4 && retries <= 4) {
level = "HIGH";
} else if (instantRight <= 3 && wrongs > 6 && retries > 6) {
level = "LOW";
} else {
level = "AVERAGE";
}
return level;
}
public void resetGame(){
fillField();
riddle.resetGame();
instantRight = 0;
wrongs = 0;
retries = 0;
count = 0;
}
}
package riddle;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
public class GameDraw extends JComponent {
private int rows;
private int columns;
private int RWIDTH;
private int RHEIGHT;
private int manX;
private int manY;
private BufferedImage man, grass, wall, note, end;
private Man m;
private GameField f;
public GameDraw() {
//Integer variables
rows = 9;
columns = 9;
RWIDTH = 70;
RHEIGHT = 70;
manX = 2;
manY = 0;
f = new GameField();
m = new Man(this);
this.setFocusable(true);
URL resourceMan = this.getClass().getResource("/resources/man.png");
try {
man = ImageIO.read(resourceMan);
} catch (IOException e) {
System.out.println("Er ging iets mis met het laden van de afbeelding van de speler");
}
}
#Override
public void paintComponent(Graphics g) {
drawField(g);
drawMan(g);
drawObjects(g);
}
private void drawField(Graphics g) {
int x = 0;
int y = 0;
Color lightgray = new Color(192, 192, 192);
for (int i = 0; i < rows + 1; i++) {
for (int j = 0; j < columns; j++) {
g.setColor(lightgray);
g.fillRect(x, y, RWIDTH, RHEIGHT);
x += RWIDTH;
}
g.setColor(lightgray);
g.fillRect(x, y, RWIDTH, RHEIGHT);
x = 0;
y += RHEIGHT;
}
}
private void drawMan(Graphics g) {
g.drawImage(man, manX * RWIDTH, manY * RHEIGHT, RWIDTH, RHEIGHT, this);
}
public void moveMan(int x, int y) {
manX = x;
manY = y;
repaint();
System.out.println(manX + " " + manY);
}
private void drawObjects(Graphics g) {
URL resourceGrass = this.getClass().getResource("/resources/Grassy.png");
URL resourceWall = this.getClass().getResource("/resources/wall.png");
URL resourceNote = this.getClass().getResource("/resources/note.png");
URL resourceEnd = this.getClass().getResource("/resources/chest.png");
//Grass object
try {
grass = ImageIO.read(resourceGrass);
wall = ImageIO.read(resourceWall);
note = ImageIO.read(resourceNote);
end = ImageIO.read(resourceEnd);
} catch (IOException e) {
System.out.println("Er ging iets mis met het laden van de afbeelding van de speler");
}
for (int j = 0; j < rows + 1; j++) {
for (int i = 0; i < columns + 1; i++) {
if (f.field[i][j] == "Grass") {
g.drawImage(grass, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
if (f.field[i][j] == "Wall") {
g.drawImage(wall, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
if (f.field[i][j] == "Note") {
g.drawImage(note, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
if (f.field[i][j] == "End") {
g.drawImage(end, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
}
}
}
public void repaintField(int x, int y) {
f.field[x][y] = null;
repaint();
}
public void resetGame(){
f.resetGame();
m.resetGame();
System.out.println(manX + " " + manY);
}
}
package riddle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Man implements KeyListener {
private int locationX;
private int locationY;
private GameDraw draw;
private GameField field;
public Man(GameDraw draw) {
locationX = 2;
locationY = 0;
this.draw = draw;
field = new GameField();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
String check;
boolean pass;
switch (key) {
case KeyEvent.VK_UP:
locationY--;
if (locationY < 0) {
locationY++;
}
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
} else if (check.equals("Wall") || check.equals("End")) {
locationY++;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationY++;
}
}
break;
case KeyEvent.VK_DOWN:
locationY++;
if (locationY > 9) {
locationY--;
}
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
}
if (check.equals("Wall") || check.equals("End")) {
locationY--;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationY--;
}
}
break;
case KeyEvent.VK_LEFT:
locationX--;
;
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
}
if (check.equals("Wall") || check.equals("End")) {
locationX++;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationX++;
}
}
break;
case KeyEvent.VK_RIGHT:
System.out.println(locationX + " " + locationY);
locationX++;
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
}
if (check.equals("Wall") || check.equals("End")) {
locationX--;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationX--;
}
}
break;
default:
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
public void clearNote(int x, int y) {
field.setField(y, x);
draw.repaintField(y, x);
}
public void resetGame(){
locationX = 2;
locationY = 0;
draw.moveMan(locationX, locationY);
System.out.println(locationX + " " + locationY);
}
}
package riddle;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Riddle {
private ArrayList<String> riddles;
private ArrayList<String> answers;
private ArrayList<String> correct;
private ArrayList<String> wrong;
private ArrayList<Integer> used;
private ArrayList<Integer> used2;
private Random ran;
private int indexAnswer;
public Riddle() {
riddles = new ArrayList<String>();
answers = new ArrayList<String>();
correct = new ArrayList<String>();
wrong = new ArrayList<String>();
used = new ArrayList<Integer>();
used2 = new ArrayList<Integer>();
ran = new Random();
fillRiddles();
fillAnswers();
fillCorrect();
fillWrong();
}
private void fillRiddles() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\riddles.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
riddles.add(s);
}
}
}
private void fillAnswers() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\answers.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
answers.add(s);
}
}
}
private void fillCorrect() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\correct.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
correct.add(s);
}
}
}
private void fillWrong() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\wrong.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
wrong.add(s);
}
}
}
public String generateRiddle() {
String theRiddle = "";
int index = ran.nextInt(riddles.size());
if (!used.contains(index)) {
theRiddle = riddles.get(index);
indexAnswer = index;
used.add(index);
} else {
theRiddle = generateRiddle();
}
return theRiddle;
}
public String getAnswer() {
String theAnswer = answers.get(indexAnswer);
return theAnswer;
}
public String getResponseC() {
String response = "";
int index = ran.nextInt(correct.size());
if (!used2.contains(index)) {
response = correct.get(index);
used2.add(index);
} else {
response = getResponseC();
}
return response;
}
public String getResponseW() {
String response = "";
int index = ran.nextInt(wrong.size());
response = wrong.get(index);
return response;
}
public void resetGame(){
riddles.clear();
answers.clear();
wrong.clear();
correct.clear();
used.clear();
used2.clear();
fillRiddles();
fillAnswers();
fillCorrect();
fillWrong();
indexAnswer = 0;
}
}

Related

How to write a action to a particular button to select a particular rows of jlabels i have created here in java swing

I am new to java please help me i have a doubt.
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import static javax.swing.SwingConstants.CENTER;
import javax.swing.SwingUtilities;
/**
*
* #author lenovo
*/
public class New1 extends javax.swing.JFrame {
JLabel a = new JLabel();
JLabel b = new JLabel();
/**
* Creates new form New1
*/
private ImageIcon abc = new ImageIcon("E:\\img1.png");
private ImageIcon ab = new ImageIcon("E:\\img3.png");
private ImageIcon abcd = new ImageIcon("E:\\img2.png");
private ImageIcon abe = new ImageIcon("E:\\img4.png");
private ImageIcon right = new ImageIcon("E:\\right.png");
private ImageIcon down = new ImageIcon("E:\\down.png");
public New1() {
initComponents();
insert();
it();
it1();
this.getContentPane().setBackground(Color.red);
}
public void insert() {
int x = 10;
int y = 10;
for (int i = 0; i < 100; i++) {
JLabel b = new JLabel(" " + i);
JLabel a = new JLabel(" " + i);
x = 10 + i % 10 * 40;
if (i % 10 == 0) {
y = y + 40;
}
if (i % 2 == 0) {
a.setText("0" + i);
b.setText("0" + i);
if (i >= 10) {
a.setText("" + i);
b.setText("" + i);
}
a.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
b.setIcon(abc);
b.addMouseListener((new MouseAdapter() {
int clicked = 1;
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
String r = b.getText();
String m = String.valueOf(clicked++);
b.setText(r);
b.setHorizontalTextPosition(CENTER);
b.setFont(new Font("Arial", Font.BOLD, 12));
a.setText(m);
b.setIcon(ab);
// a.setVerticalTextPosition(CENTER);
// a.setHorizontalTextPosition(CENTER);
// a.setVerticalTextPosition(BOTTOM);
// a.setVerticalTextPosition(BOTTOM);
a.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
a.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
a.setVisible(true);
a.setFont(new Font("Arial", Font.BOLD, 10));
javax.swing.border.Border border = BorderFactory.createLineBorder(new Color(51, 51, 255), 1);
a.setBorder(border);
}
if (SwingUtilities.isRightMouseButton(e)) {
String m = ("");
a.setText(m);
clicked = 1;
}
}
}));
javax.swing.border.Border border
= BorderFactory.createLineBorder(new Color(51, 51, 255), 1);
a.setBorder(border);
} else {
a.setText("0" + i);
b.setText("0" + i);
if (i >= 10) {
a.setText("" + i);
b.setText("" + i);
}
a.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
b.setIcon(abcd);
b.addMouseListener((new MouseAdapter() {
int clicked = 1;
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
String m = String.valueOf(clicked++);
String w = b.getText();
b.setText(w);
b.setFont(new Font("Arial", Font.BOLD, 12));
b.setHorizontalTextPosition(CENTER);
a.setText(m);
b.setIcon(abe);
a.setFont(new Font("Arial", Font.BOLD, 10));
a.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
a.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
a.setVisible(true);
// javax.swing.border.Border border =
BorderFactory.createLineBorder(new Color(51, 51, 255), 1);
//a.setBorder(border);
}
if (SwingUtilities.isRightMouseButton(e)) {
String m = ("");
a.setText(m);
clicked = 1;
}
}
}));
//a.setIcon(abcd);
javax.swing.border.Border border
= BorderFactory.createLineBorder(new Color(51, 51, 255), 1);
a.setBorder(border);
}
a.setFont(new Font("Arial", Font.BOLD, 12));
b.setBounds(x, y, 40, 40);
a.setBounds(x, y, 40, 40);
add(a);
add(b);
}
}
public void it() {
int x = 410;
int y = 10;
for (int j = 0; j < 10; j++) {
JButton c = new JButton("");
// x=410+i%410*40;
y = 10 + j % 10 * 40;
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String ss = a.getText();
int nn = Integer.parseInt(ss);
if (nn < 1) {
a.setIcon(down);
b.setIcon(down);
}
}
});
if (j % 1 == 0) {
x = 410;
y = y + 40;
}
c.setBounds(x, y, 40, 40);
c.setIcon(right);
add(c);
}
}
public void it1() {
int x = 10;
int y = 450;
for (int i = 0; i <= 10; i++) {
JButton sr = new JButton("");
x = 10 + i % 10 * 40;
y = 450;
sr.setBounds(x, y, 40, 40);
sr.setIcon(down);
add(sr);
}
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(New1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(New1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(New1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(New1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new New1().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}

Painting canvas and System.out.println() not working

I have JFrame with a start button, which triggers the calculation of a Julia Set.
The code that is executed when the start button is clicked is as follows:
public void actionPerformed(ActionEvent aActionEvent)
{
String strCmd = aActionEvent.getActionCommand();
if (strCmd.equals("Start"))
{
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
this.handleCalculation();
}
else if (aActionEvent.getSource() == m_cTReal)
Which used to work fine, except that the application could not be closed anymore. So I tried to use m_bRunning in a separate method so that actionPerformed() isn't blocked all the time to see if that would help, and then set m_bRunning = false in the method stop() which is called when the window is closed:
public void run()
{
if(m_bRunning)
{
this.handleCalculation();
}
}
The method run() is called from the main class in a while(true) loop.
Yet unfortunately, neither did that solve the problem, nor do I now have any output to the canvas or any debug traces with System.out.println(). Could anyone point me in the right direction on this?
EDIT:
Here are the whole files:
// cMain.java
package juliaSet;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.Dimension;
public class cMain {
public static void main(String[] args)
{
int windowWidth = 1000;//(int)screenSize.getWidth() - 200;
int windowHeight = 800;//(int)screenSize.getHeight() - 50;
int plotWidth = 400;//(int)screenSize.getWidth() - 600;
int plotHeight = 400;//(int)screenSize.getHeight() - 150;
JuliaSet cJuliaSet = new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
cJuliaSet.setVisible(true);
while(true)
{
cJuliaSet.run();
}
}
}
// JuliaSet.java
package juliaSet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import java.util.Random;
import java.io.*;
import java.lang.ref.*;
public class JuliaSet extends JFrame implements ActionListener
{
private JButton m_cBStart;
private JTextField m_cTReal;
private JTextField m_cTImag;
private JTextField m_cTDivergThresh;
private JLabel m_cLReal;
private JLabel m_cLImag;
private JLabel m_cLDivergThresh;
private int m_iDivergThresh = 10;
private String m_cMsgDivThresh = "Divergence threshold = " + m_iDivergThresh;
private JuliaCanvas m_cCanvas;
private int m_iPlotWidth; // number of cells
private int m_iPlotHeight; // number of cells
private Boolean m_bRunning = false;
private double m_dReal = 0.3;
private double m_dImag = -0.5;
private String m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
private String m_cMsgIter = "x = 0, y = 0";
private Complex m_cCoordPlane[][];
private double m_dAbsSqValues[][];
private int m_iIterations[][];
private Complex m_cSummand;
private BufferedImage m_cBackGroundImage = null;
private FileWriter m_cFileWriter;
private BufferedWriter m_cBufferedWriter;
private String m_sFileName = "log.txt";
private Boolean m_bWriteLog = false;
private static final double PLOTMAX = 2.0; // we'll have symmetric axes
// ((0,0) at the centre of the
// plot
private static final int MAXITER = 0xff;
JuliaSet(String aTitle, int aFrameWidth, int aFrameHeight, int aPlotWidth, int aPlotHeight)
{
super(aTitle);
this.setSize(aFrameWidth, aFrameHeight);
m_iPlotWidth = aPlotWidth;
m_iPlotHeight = aPlotHeight;
m_cSummand = new Complex(m_dReal, m_dImag);
m_cBackGroundImage = new BufferedImage(aFrameWidth, aFrameHeight, BufferedImage.TYPE_INT_RGB);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
stop();
super.windowClosing(e);
System.exit(0);
}
});
GridBagLayout cLayout = new GridBagLayout();
GridBagConstraints cConstraints = new GridBagConstraints();
this.setLayout(cLayout);
m_cCanvas = new JuliaCanvas(m_iPlotWidth, m_iPlotHeight);
m_cCanvas.setSize(m_iPlotWidth, m_iPlotHeight);
m_cBStart = new JButton("Start");
m_cBStart.addActionListener(this);
m_cTReal = new JTextField(5);
m_cTReal.addActionListener(this);
m_cTImag = new JTextField(5);
m_cTImag.addActionListener(this);
m_cTDivergThresh = new JTextField(5);
m_cTDivergThresh.addActionListener(this);
m_cLReal = new JLabel("Re(c):");
m_cLImag = new JLabel("Im(c):");
m_cLDivergThresh = new JLabel("Divergence Threshold:");
cConstraints.insets.top = 3;
cConstraints.insets.bottom = 3;
cConstraints.insets.right = 3;
cConstraints.insets.left = 3;
// cCanvas
cConstraints.gridx = 0;
cConstraints.gridy = 0;
cLayout.setConstraints(m_cCanvas, cConstraints);
this.add(m_cCanvas);
// m_cLReal
cConstraints.gridx = 0;
cConstraints.gridy = 1;
cLayout.setConstraints(m_cLReal, cConstraints);
this.add(m_cLReal);
// m_cTReal
cConstraints.gridx = 1;
cConstraints.gridy = 1;
cLayout.setConstraints(m_cTReal, cConstraints);
this.add(m_cTReal);
// m_cLImag
cConstraints.gridx = 0;
cConstraints.gridy = 2;
cLayout.setConstraints(m_cLImag, cConstraints);
this.add(m_cLImag);
// m_cTImag
cConstraints.gridx = 1;
cConstraints.gridy = 2;
cLayout.setConstraints(m_cTImag, cConstraints);
this.add(m_cTImag);
// m_cLDivergThresh
cConstraints.gridx = 0;
cConstraints.gridy = 3;
cLayout.setConstraints(m_cLDivergThresh, cConstraints);
this.add(m_cLDivergThresh);
// m_cTDivergThresh
cConstraints.gridx = 1;
cConstraints.gridy = 3;
cLayout.setConstraints(m_cTDivergThresh, cConstraints);
this.add(m_cTDivergThresh);
// m_cBStart
cConstraints.gridx = 0;
cConstraints.gridy = 4;
cLayout.setConstraints(m_cBStart, cConstraints);
this.add(m_cBStart);
if (m_bWriteLog)
{
try
{
m_cFileWriter = new FileWriter(m_sFileName, false);
m_cBufferedWriter = new BufferedWriter(m_cFileWriter);
} catch (IOException ex) {
System.out.println("Error opening file '" + m_sFileName + "'");
}
}
this.repaint();
this.transformCoordinates();
}
public synchronized void stop()
{
if (m_bRunning)
{
m_bRunning = false;
boolean bRetry = true;
}
if (m_bWriteLog)
{
try {
m_cBufferedWriter.close();
m_cFileWriter.close();
} catch (IOException ex) {
System.out.println("Error closing file '" + m_sFileName + "'");
}
}
}
public void collectGarbage()
{
Object cObj = new Object();
WeakReference ref = new WeakReference<Object>(cObj);
cObj = null;
while(ref.get() != null) {
System.gc();
}
}
public void setSummand(Complex aSummand)
{
m_cSummand.setIm(aSummand.getIm());
m_dImag = aSummand.getIm();
m_cSummand.setRe(aSummand.getRe());
m_dReal = aSummand.getRe();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
}
public void paint(Graphics aGraphics)
{
Graphics cScreenGraphics = aGraphics;
// render on background image
aGraphics = m_cBackGroundImage.getGraphics();
this.paintComponents(aGraphics);
// drawString() calls are debug code only....
aGraphics.setColor(Color.BLACK);
aGraphics.drawString(m_cSMsg, 10, 450);
aGraphics.drawString(m_cMsgIter, 10, 465);
aGraphics.drawString(m_cMsgDivThresh, 10, 480);
// rendering is done, draw background image to on screen graphics
cScreenGraphics.drawImage(m_cBackGroundImage, 0, 0, null);
}
public void actionPerformed(ActionEvent aActionEvent)
{
String strCmd = aActionEvent.getActionCommand();
if (strCmd.equals("Start"))
{
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
}
else if (aActionEvent.getSource() == m_cTReal)
{
m_dReal = Double.parseDouble(m_cTReal.getText());
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_cSummand.setRe(m_dReal);
}
else if (aActionEvent.getSource() == m_cTImag)
{
m_dImag = Double.parseDouble(m_cTImag.getText());
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_cSummand.setIm(m_dImag);
}
else if (aActionEvent.getSource() == m_cTDivergThresh)
{
m_iDivergThresh = Integer.parseInt(m_cTDivergThresh.getText());
m_cMsgDivThresh = "Divergence threshold = " + m_iDivergThresh;
}
this.update(this.getGraphics());
}
public void transformCoordinates()
{
double dCanvasHeight = (double) m_cCanvas.getHeight();
double dCanvasWidth = (double) m_cCanvas.getWidth();
// init matrix with same amount of elements as pixels in canvas
m_cCoordPlane = new Complex[(int) dCanvasHeight][(int) dCanvasWidth];
double iPlotRange = 2 * PLOTMAX;
for (int i = 0; i < dCanvasHeight; i++)
{
for (int j = 0; j < dCanvasWidth; j++)
{
m_cCoordPlane[i][j] = new Complex((i - (dCanvasWidth / 2)) * iPlotRange / dCanvasWidth,
(j - (dCanvasHeight / 2)) * iPlotRange / dCanvasHeight);
}
}
}
public void calcAbsSqValues()
{
int iCanvasHeight = m_cCanvas.getHeight();
int iCanvasWidth = m_cCanvas.getWidth();
// init matrix with same amount of elements as pixels in canvas
m_dAbsSqValues = new double[iCanvasHeight][iCanvasWidth];
m_iIterations = new int[iCanvasHeight][iCanvasWidth];
Complex cSum = new Complex();
if (m_bWriteLog) {
try
{
m_cBufferedWriter.write("m_iIterations[][] =");
m_cBufferedWriter.newLine();
}
catch (IOException ex)
{
System.out.println("Error opening file '" + m_sFileName + "'");
}
}
for (int i = 0; i < iCanvasHeight; i++)
{
for (int j = 0; j < iCanvasWidth; j++)
{
cSum.setRe(m_cCoordPlane[i][j].getRe());
cSum.setIm(m_cCoordPlane[i][j].getIm());
m_iIterations[i][j] = 0;
do
{
m_iIterations[i][j]++;
cSum.square();
cSum.add(m_cSummand);
m_dAbsSqValues[i][j] = cSum.getAbsSq();
} while ((m_iIterations[i][j] < MAXITER) && (m_dAbsSqValues[i][j] < m_iDivergThresh));
this.calcColour(i, j, m_iIterations[i][j]);
m_cMsgIter = "x = " + i + " , y = " + j;
if(m_bWriteLog)
{
System.out.println(m_cMsgIter);
System.out.flush();
}
if (m_bWriteLog) {
try
{
m_cBufferedWriter.write(Integer.toString(m_iIterations[i][j]));
m_cBufferedWriter.write(" ");
}
catch (IOException ex) {
System.out.println("Error writing to file '" + m_sFileName + "'");
}
}
}
if (m_bWriteLog) {
try
{
m_cBufferedWriter.newLine();
}
catch (IOException ex) {
System.out.println("Error writing to file '" + m_sFileName + "'");
}
}
}
m_dAbsSqValues = null;
m_iIterations = null;
cSum = null;
}
private void calcColour(int i, int j, int aIterations)
{
Color cColour = Color.getHSBColor((int) Math.pow(aIterations, 4), 0xff,
0xff * ((aIterations < MAXITER) ? 1 : 0));
m_cCanvas.setPixelColour(i, j, cColour);
cColour = null;
}
private void handleCalculation()
{
Complex cSummand = new Complex();
for(int i = -800; i <= 800; i++)
{
for(int j = -800; j <= 800; j++)
{
cSummand.setRe(((double)i)/1000.0);
cSummand.setIm(((double)j)/1000.0);
this.setSummand(cSummand);
this.calcAbsSqValues();
this.getCanvas().paint(m_cCanvas.getGraphics());
this.paint(this.getGraphics());
}
}
cSummand = null;
this.collectGarbage();
System.gc();
System.runFinalization();
}
public boolean isRunning()
{
return m_bRunning;
}
public void setRunning(boolean aRunning)
{
m_bRunning = aRunning;
}
public Canvas getCanvas()
{
return m_cCanvas;
}
public void run()
{
if(m_bRunning)
{
this.handleCalculation();
}
}
}
class JuliaCanvas extends Canvas
{
private int m_iWidth;
private int m_iHeight;
private Random m_cRnd;
private BufferedImage m_cBackGroundImage = null;
private int m_iRed[][];
private int m_iGreen[][];
private int m_iBlue[][];
JuliaCanvas(int aWidth, int aHeight)
{
m_iWidth = aWidth;
m_iHeight = aHeight;
m_cRnd = new Random();
m_cRnd.setSeed(m_cRnd.nextLong());
m_cBackGroundImage = new BufferedImage(m_iWidth, m_iHeight, BufferedImage.TYPE_INT_RGB);
m_iRed = new int[m_iHeight][m_iWidth];
m_iGreen = new int[m_iHeight][m_iWidth];
m_iBlue = new int[m_iHeight][m_iWidth];
}
public void init() {
}
public void setPixelColour(int i, int j, Color aColour)
{
m_iRed[i][j] = aColour.getRed();
m_iGreen[i][j] = aColour.getGreen();
m_iBlue[i][j] = aColour.getBlue();
}
private int getRandomInt(double aProbability)
{
return (m_cRnd.nextDouble() < aProbability) ? 1 : 0;
}
#Override
public void paint(Graphics aGraphics)
{
// store on screen graphics
Graphics cScreenGraphics = aGraphics;
// render on background image
aGraphics = m_cBackGroundImage.getGraphics();
for (int i = 0; i < m_iWidth; i++)
{
for (int j = 0; j < m_iHeight; j++)
{
Color cColor = new Color(m_iRed[i][j], m_iGreen[i][j], m_iBlue[i][j]);
aGraphics.setColor(cColor);
aGraphics.drawRect(i, j, 0, 0);
cColor = null;
}
}
// rendering is done, draw background image to on screen graphics
cScreenGraphics.drawImage(m_cBackGroundImage, 1, 1, null);
}
#Override
public void update(Graphics aGraphics)
{
paint(aGraphics);
}
}
class Complex {
private double m_dRe;
private double m_dIm;
public Complex()
{
m_dRe = 0;
m_dIm = 0;
}
public Complex(double aRe, double aIm)
{
m_dRe = aRe;
m_dIm = aIm;
}
public Complex(Complex aComplex)
{
m_dRe = aComplex.m_dRe;
m_dIm = aComplex.m_dIm;
}
public double getRe() {
return m_dRe;
}
public void setRe(double adRe)
{
m_dRe = adRe;
}
public double getIm() {
return m_dIm;
}
public void setIm(double adIm)
{
m_dIm = adIm;
}
public void add(Complex acComplex)
{
m_dRe += acComplex.getRe();
m_dIm += acComplex.getIm();
}
public void square()
{
double m_dReSave = m_dRe;
m_dRe = (m_dRe * m_dRe) - (m_dIm * m_dIm);
m_dIm = 2 * m_dReSave * m_dIm;
}
public double getAbsSq()
{
return ((m_dRe * m_dRe) + (m_dIm * m_dIm));
}
}
I'm quoting a recent comment from #MadProgrammer (including links)
"Swing is single threaded, nothing you can do to change that, all events are posted to the event queue and processed by the Event Dispatching Thread, see Concurrency in Swing for more details and have a look at Worker Threads and SwingWorker for at least one possible solution"
There is only one thread in your code. That thread is busy doing the calculation and can not respond to events located in the GUI. You have to separate the calculation in another thread that periodically updates the quantities that appears in the window. More info about that in the links, courtesy of #MadProgrammer, I insist.
UPDATED: As pointed by #Yusuf, the proper way of launching the JFrame is
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
}
});
Set the frame visible on construction and start calculation when the start button is pressed.
First;
Endless loop is not a proper way to do this. This part is loops and taking CPU and never give canvas to refresh screen. if you add below code your code will run as expected. but this is not the proper solution.
cMain.java:
while (true) {
cJuliaSet.run();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Second: you could call run method when start button clicked. But you should create a thread in run method to not freeze screen.
public static void main(String[] args) {
int windowWidth = 1000;// (int)screenSize.getWidth() - 200;
int windowHeight = 800;// (int)screenSize.getHeight() - 50;
int plotWidth = 400;// (int)screenSize.getWidth() - 600;
int plotHeight = 400;// (int)screenSize.getHeight() - 150;
JuliaSet cJuliaSet = new JuliaSet("Julia Set", windowWidth, windowHeight, plotWidth, plotHeight);
cJuliaSet.setVisible(true);
//While loop removed
}
actionPerformed:
if (strCmd.equals("Start")) {
m_cCanvas.init();
m_cSMsg = "c = " + Double.toString(m_dReal) + " + " + "j*" + Double.toString(m_dImag);
m_bRunning = true;
this.run(); // added call run method.
} else if (aActionEvent.getSource() == m_cTReal) {
run method:
public void run()
{
if(m_bRunning)
{
new Thread(){ //Thread to release screen
#Override
public void run() {
JuliaSet.this.handleCalculation();
}
}.start(); //also thread must be started
}
}
As said by #RubioRic, SwingUtilities.invokeLater method is also a part of solution. But you need to check whole of your code and you should learn about Threads.

Resetting JFrame

This game is connect four and at the end of the game I give the player an option
to play again. So if they want to play again I try clearing the canvas and resetting the board. I know basically nothing about doing java graphics so I'm
pretty certain the error stems from me not understanding something about the
graphics as opposed to the games logic.
If you look at the update gameState method right after I get input from the user
is when I try to reset everything. And when I say reset I mean remove all images and such from window. Instead of everything being removed it just locks up.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Color;
public class MainFrame extends JFrame
{
public static final String GAME_NAME = "Connect Four!";
private static final int _PLAYER_ONE_TURN = 1;
private static String _title;
private Board _gameBoard;
private ToolBar _buttons;
private boolean _humanVsHuman;
private int _gameIteration;
public MainFrame()
{
super();
final String INITIAL_GAME_MESSAGE = "Human Vs. Human? Default Computer "
+ "Vs. Human.";
final String MENU_TITLE = "Game Setup...";
final String[] MENU_OPTIONS = { "Yes!", "No!" };
_gameBoard = new Board(Game.BOARD_WIDTH, Game.BOARD_HEIGHT);
_buttons = new ToolBar(Game.BOARD_WIDTH);
_humanVsHuman = 0 == JOptionPane.showOptionDialog(this,
INITIAL_GAME_MESSAGE, MENU_TITLE, JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, MENU_OPTIONS, MENU_OPTIONS[1]);
updateTitle();
setLayout(new BorderLayout());
setSize(Game.SCREEN_WIDTH, Game.SCREEN_HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(_buttons, BorderLayout.SOUTH);
setVisible(true);
}
public void paint(Graphics g)
{
GamePiece[][] board = _gameBoard.getBoard();
_buttons.repaint();
for (int x = 0; x < Game.BOARD_WIDTH; x++)
{
for (int y = 0; y < Game.BOARD_HEIGHT; y++)
{
if (board[x][y] != null)
{
g.setColor(
board[x][y].toString().equals(GamePiece.GAME_PIECE_BLUE)
? Color.BLUE : Color.RED);
g.fillOval((int) (x * (GamePiece.SIZE[0] * .92) + ((Game.SCREEN_WIDTH - (GamePiece.SIZE[0] * Game.BOARD_WIDTH)) / Game.BOARD_WIDTH) * x + 30), (int) (y * (GamePiece.SIZE[1] * .9) + ((Game.SCREEN_HEIGHT - (GamePiece.SIZE[1] * Game.BOARD_HEIGHT)) / Game.BOARD_HEIGHT) * y + 30),
GamePiece.SIZE[0], GamePiece.SIZE[1]);
}
}
}
}
public void updateTitle()
{
final String HUMAN = "HUMAN";
final String COMPUTER = "COMPUTER";
final String PLAYER = "PLAYER";
final String TURN = "TURN";
_title = GAME_NAME + " " + Game.VERSION + ": " + PLAYER + " "
+ (getPlayerTurn(_gameIteration) == _PLAYER_ONE_TURN
? _humanVsHuman ? "1" : HUMAN
: _humanVsHuman ? "2" : COMPUTER)
+ " " + TURN;
setTitle(_title);
}
public void updateGameState(boolean aWinner)
{
final String AGAIN = "Play Again?";
final String ROUND_OVER = "ROUND OVER";
final String[] OPTIONS = { "Yes", "No" };
boolean hasWinner = aWinner;
if (hasWinner || _gameBoard.isFull())
{
if (hasWinner)
{
JOptionPane.showMessageDialog(this,
getPlayerTurn(_gameIteration) == _PLAYER_ONE_TURN
? "Blue won!" : "Red won!");
}
if (0 != JOptionPane.showOptionDialog(this, AGAIN, ROUND_OVER,
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
OPTIONS, OPTIONS[1]))
{
setVisible(false);
dispose();
}
else
{
_gameBoard.clearBoard();
removeAll();//or remove(JComponent)
invalidate();
_buttons = new ToolBar(Game.BOARD_WIDTH);
updateMainFrame();
}
}
_gameIteration++;
}
public void updateMainFrame()
{
revalidate();
repaint();
updateTitle();
if (_gameIteration + 1 == Integer.MAX_VALUE)
{
if (getPlayerTurn(_gameIteration) == _PLAYER_ONE_TURN)
{
_gameIteration = 0;
}
else
{
_gameIteration = 1;
}
}
}
private int getPlayerTurn(int iteration)
{
return (iteration % 2) + 1;
}
private class ToolBar extends JPanel
{
public ToolBar(int numberOfButtons)
{
setLayout(new FlowLayout(FlowLayout.CENTER,
(int) (Game.SCREEN_WIDTH / numberOfButtons) / 2, 0));
for (int i = 0; i < numberOfButtons; i++)
{
JButton button = new JButton("" + (i + 1));
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
boolean hasWinner;
if (!_gameBoard
.isRowFull(Integer.parseInt(button.getText()) - 1))
{
hasWinner = _gameBoard.insert(
getPlayerTurn(_gameIteration) == _PLAYER_ONE_TURN
? new BluePiece() : new RedPiece(),
Integer.parseInt(button.getText()) - 1);
updateMainFrame();
updateGameState(hasWinner);
}
}
});
add(button);
}
}
}
}

How to get Note On/Off messages from a MIDI sequence?

I am hoping to get notifications of note on/off events in a playing MIDI sequence to show the notes on a screen based (piano) keyboard.
The code below adds a MetaEventListener and a ControllerEventListener when playing a MIDI file, but only shows a few messages at the start and end of the track.
How can we listen for note on & note off MIDI events?
import java.io.File;
import javax.sound.midi.*;
import javax.swing.JOptionPane;
class PlayMidi {
public static void main(String[] args) throws Exception {
/* This MIDI file can be found at..
https://drive.google.com/open?id=0B5B9wDXIGw9lR2dGX005anJsT2M&authuser=0
*/
File path = new File("I:\\projects\\EverLove.mid");
Sequence sequence = MidiSystem.getSequence(path);
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
MetaEventListener mel = new MetaEventListener() {
#Override
public void meta(MetaMessage meta) {
final int type = meta.getType();
System.out.println("MEL - type: " + type);
}
};
sequencer.addMetaEventListener(mel);
int[] types = new int[128];
for (int ii = 0; ii < 128; ii++) {
types[ii] = ii;
}
ControllerEventListener cel = new ControllerEventListener() {
#Override
public void controlChange(ShortMessage event) {
int command = event.getCommand();
if (command == ShortMessage.NOTE_ON) {
System.out.println("CEL - note on!");
} else if (command == ShortMessage.NOTE_OFF) {
System.out.println("CEL - note off!");
} else {
System.out.println("CEL - unknown: " + command);
}
}
};
int[] listeningTo = sequencer.addControllerEventListener(cel, types);
for (int ii : listeningTo) {
System.out.println("Listening To: " + ii);
}
sequencer.setSequence(sequence);
sequencer.start();
JOptionPane.showMessageDialog(null, "Exit this dialog to end");
sequencer.stop();
sequencer.close();
}
}
Here is an implementation of the first suggestion of the accepted answer. It will present an option pane confirm dialog as to whether or not to add a new track to hold meta events corresponding to the NOTE_ON & NOTE_OFF messages of each of the existing tracks.
If the user chooses to do that, they'll see Meta events throughout the playback of the MIDI sequence.
import java.io.File;
import javax.sound.midi.*;
import javax.swing.JOptionPane;
class PlayMidi {
/** Iterates the MIDI events of the first track and if they are a
* NOTE_ON or NOTE_OFF message, adds them to the second track as a
* Meta event. */
public static final void addNotesToTrack(
Track track,
Track trk) throws InvalidMidiDataException {
for (int ii = 0; ii < track.size(); ii++) {
MidiEvent me = track.get(ii);
MidiMessage mm = me.getMessage();
if (mm instanceof ShortMessage) {
ShortMessage sm = (ShortMessage) mm;
int command = sm.getCommand();
int com = -1;
if (command == ShortMessage.NOTE_ON) {
com = 1;
} else if (command == ShortMessage.NOTE_OFF) {
com = 2;
}
if (com > 0) {
byte[] b = sm.getMessage();
int l = (b == null ? 0 : b.length);
MetaMessage metaMessage = new MetaMessage(com, b, l);
MidiEvent me2 = new MidiEvent(metaMessage, me.getTick());
trk.add(me2);
}
}
}
}
public static void main(String[] args) throws Exception {
/* This MIDI file can be found at..
https://drive.google.com/open?id=0B5B9wDXIGw9lR2dGX005anJsT2M&authuser=0
*/
File path = new File("I:\\projects\\EverLove.mid");
Sequence sequence = MidiSystem.getSequence(path);
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
MetaEventListener mel = new MetaEventListener() {
#Override
public void meta(MetaMessage meta) {
final int type = meta.getType();
System.out.println("MEL - type: " + type);
}
};
sequencer.addMetaEventListener(mel);
int[] types = new int[128];
for (int ii = 0; ii < 128; ii++) {
types[ii] = ii;
}
ControllerEventListener cel = new ControllerEventListener() {
#Override
public void controlChange(ShortMessage event) {
int command = event.getCommand();
if (command == ShortMessage.NOTE_ON) {
System.out.println("CEL - note on!");
} else if (command == ShortMessage.NOTE_OFF) {
System.out.println("CEL - note off!");
} else {
System.out.println("CEL - unknown: " + command);
}
}
};
int[] listeningTo = sequencer.addControllerEventListener(cel, types);
StringBuilder sb = new StringBuilder();
for (int ii = 0; ii < listeningTo.length; ii++) {
sb.append(ii);
sb.append(", ");
}
System.out.println("Listenning to: " + sb.toString());
int mirror = JOptionPane.showConfirmDialog(
null,
"Add note on/off messages to another track as meta messages?",
"Confirm Mirror",
JOptionPane.OK_CANCEL_OPTION);
if (mirror == JOptionPane.OK_OPTION) {
Track[] tracks = sequence.getTracks();
Track trk = sequence.createTrack();
for (Track track : tracks) {
addNotesToTrack(track, trk);
}
}
sequencer.setSequence(sequence);
sequencer.start();
JOptionPane.showMessageDialog(null, "Exit this dialog to end");
sequencer.stop();
sequencer.close();
}
}
Implementation of keyboard
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.sound.midi.*;
import java.util.ArrayList;
import java.io.*;
import java.net.URL;
public class MidiPianola {
private JComponent ui = null;
public static final int OTHER = -1;
public static final int NOTE_ON = 1;
public static final int NOTE_OFF = 2;
private OctaveComponent[] octaves;
Sequencer sequencer;
int startOctave = 0;
int numOctaves = 0;
MidiPianola(int startOctave, int numOctaves)
throws MidiUnavailableException {
this.startOctave = startOctave;
this.numOctaves = numOctaves;
initUI();
}
public void openMidi(URL url)
throws InvalidMidiDataException, IOException {
openMidi(url.openStream());
}
public void openMidi(InputStream is)
throws InvalidMidiDataException, IOException {
Sequence sequence = MidiSystem.getSequence(is);
Track[] tracks = sequence.getTracks();
Track trk = sequence.createTrack();
for (Track track : tracks) {
addNotesToTrack(track, trk);
}
sequencer.setSequence(sequence);
startMidi();
}
public void startMidi() {
sequencer.start();
}
public void stopMidi() {
sequencer.stop();
}
public void closeSequencer() {
sequencer.close();
}
private void handleNote(final int command, int note) {
OctaveComponent octave = getOctaveForNote(note);
PianoKey key = octave.getKeyForNote(note);
if (command == NOTE_ON) {
key.setPressed(true);
} else if (command == NOTE_OFF) {
key.setPressed(false);
}
ui.repaint();
}
private OctaveComponent getOctaveForNote(int note) {
return octaves[(note / 12) - startOctave];
}
public void initUI() throws MidiUnavailableException {
if (ui != null) {
return;
}
sequencer = MidiSystem.getSequencer();
MetaEventListener mel = new MetaEventListener() {
#Override
public void meta(MetaMessage meta) {
final int type = meta.getType();
byte b = meta.getData()[1];
int i = (int) (b & 0xFF);
handleNote(type, i);
}
};
sequencer.addMetaEventListener(mel);
sequencer.open();
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JPanel keyBoard = new JPanel(new GridLayout(1, 0));
ui.add(keyBoard, BorderLayout.CENTER);
int end = startOctave + numOctaves;
octaves = new OctaveComponent[end - startOctave];
for (int i = startOctave; i < end; i++) {
octaves[i - startOctave] = new OctaveComponent(i);
keyBoard.add(octaves[i - startOctave]);
}
JToolBar tools = new JToolBar();
tools.setFloatable(false);
ui.add(tools, BorderLayout.PAGE_START);
tools.setFloatable(false);
Action open = new AbstractAction("Open") {
JFileChooser fileChooser = new JFileChooser();
#Override
public void actionPerformed(ActionEvent e) {
int result = fileChooser.showOpenDialog(ui);
if (result == JFileChooser.APPROVE_OPTION) {
File f = fileChooser.getSelectedFile();
try {
openMidi(f.toURI().toURL());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
};
tools.add(open);
Action rewind = new AbstractAction("Rewind") {
#Override
public void actionPerformed(ActionEvent e) {
sequencer.setTickPosition(0);
}
};
tools.add(rewind);
Action play = new AbstractAction("Play") {
#Override
public void actionPerformed(ActionEvent e) {
startMidi();
}
};
tools.add(play);
Action stop = new AbstractAction("Stop") {
#Override
public void actionPerformed(ActionEvent e) {
stopMidi();
}
};
tools.add(stop);
}
public JComponent getUI() {
return ui;
}
/**
* Iterates the MIDI events of the first track, and if they are a NOTE_ON or
* NOTE_OFF message, adds them to the second track as a Meta event.
*/
public static final void addNotesToTrack(
Track track,
Track trk) throws InvalidMidiDataException {
for (int ii = 0; ii < track.size(); ii++) {
MidiEvent me = track.get(ii);
MidiMessage mm = me.getMessage();
if (mm instanceof ShortMessage) {
ShortMessage sm = (ShortMessage) mm;
int command = sm.getCommand();
int com = OTHER;
if (command == ShortMessage.NOTE_ON) {
com = NOTE_ON;
} else if (command == ShortMessage.NOTE_OFF) {
com = NOTE_OFF;
}
if (com > OTHER) {
byte[] b = sm.getMessage();
int l = (b == null ? 0 : b.length);
MetaMessage metaMessage = new MetaMessage(
com,
b,
l);
MidiEvent me2 = new MidiEvent(metaMessage, me.getTick());
trk.add(me2);
}
}
}
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
SpinnerNumberModel startModel =
new SpinnerNumberModel(2,0,6,1);
JOptionPane.showMessageDialog(
null,
new JSpinner(startModel),
"Start Octave",
JOptionPane.QUESTION_MESSAGE);
SpinnerNumberModel octavesModel =
new SpinnerNumberModel(5,5,11,1);
JOptionPane.showMessageDialog(
null,
new JSpinner(octavesModel),
"Number of Octaves",
JOptionPane.QUESTION_MESSAGE);
final MidiPianola o = new MidiPianola(
startModel.getNumber().intValue(),
octavesModel.getNumber().intValue());
WindowListener closeListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
o.closeSequencer();
}
};
JFrame f = new JFrame("MIDI Pianola");
f.addWindowListener(closeListener);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.setResizable(false);
f.pack();
f.setVisible(true);
} catch (MidiUnavailableException ex) {
ex.printStackTrace();
} catch (InvalidMidiDataException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
};
SwingUtilities.invokeLater(r);
}
}
class OctaveComponent extends JPanel {
int octave;
ArrayList<PianoKey> keys;
PianoKey selectedKey = null;
public OctaveComponent(int octave) {
this.octave = octave;
init();
}
public PianoKey getKeyForNote(int note) {
int number = note % 12;
return keys.get(number);
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
for (PianoKey key : keys) {
key.draw(g2);
}
}
public static final Shape
removeArrayFromShape(Shape shape, Shape[] shapes) {
Area a = new Area(shape);
for (Shape sh : shapes) {
a.subtract(new Area(sh));
}
return a;
}
public final Shape getEntireBounds() {
Area a = new Area();
for (PianoKey key : keys) {
a.add(new Area(key.keyShape));
}
return a;
}
#Override
public Dimension getPreferredSize() {
Shape sh = getEntireBounds();
Rectangle r = sh.getBounds();
Dimension d = new Dimension(r.x + r.width, r.y + r.height + 1);
return d;
}
public void init() {
keys = new ArrayList<PianoKey>();
int w = 30;
int h = 200;
int x = 0;
int y = 0;
int xs = w - (w / 3);
Shape[] sharps = new Shape[5];
int hs = h * 3 / 5;
int ws = w * 2 / 3;
sharps[0] = new Rectangle2D.Double(xs, y, ws, hs);
xs += w;
sharps[1] = new Rectangle2D.Double(xs, y, ws, hs);
xs += 2 * w;
sharps[2] = new Rectangle2D.Double(xs, y, ws, hs);
xs += w;
sharps[3] = new Rectangle2D.Double(xs, y, ws, hs);
xs += w;
sharps[4] = new Rectangle2D.Double(xs, y, ws, hs);
Shape[] standards = new Shape[7];
for (int ii = 0; ii < standards.length; ii++) {
Shape shape = new Rectangle2D.Double(x, y, w, h);
x += w;
standards[ii] = removeArrayFromShape(shape, sharps);
}
int note = 0;
int ist = 0;
int ish = 0;
keys.add(new PianoKey(standards[ist++], (octave * 12) + note++, "C", this));
keys.add(new PianoKey(sharps[ish++], (octave * 12) + note++, "C#", this));
keys.add(new PianoKey(standards[ist++], (octave * 12) + note++, "D", this));
keys.add(new PianoKey(sharps[ish++], (octave * 12) + note++, "D#", this));
keys.add(new PianoKey(standards[ist++], (octave * 12) + note++, "E", this));
keys.add(new PianoKey(standards[ist++], (octave * 12) + note++, "F", this));
keys.add(new PianoKey(sharps[ish++], (octave * 12) + note++, "F#", this));
keys.add(new PianoKey(standards[ist++], (octave * 12) + note++, "G", this));
keys.add(new PianoKey(sharps[ish++], (octave * 12) + note++, "G#", this));
keys.add(new PianoKey(standards[ist++], (octave * 12) + note++, "A", this));
keys.add(new PianoKey(sharps[ish++], (octave * 12) + note++, "A#", this));
keys.add(new PianoKey(standards[ist++], (octave * 12) + note++, "B", this));
}
}
class PianoKey {
Shape keyShape;
int number;
String name;
Component component;
boolean pressed = false;
PianoKey(Shape keyShape, int number, String name, Component component) {
this.keyShape = keyShape;
this.number = number;
this.name = name;
this.component = component;
}
public void draw(Graphics2D g) {
if (name.endsWith("#")) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.WHITE);
}
g.fill(keyShape);
g.setColor(Color.GRAY);
g.draw(keyShape);
if (pressed) {
Rectangle r = keyShape.getBounds();
GradientPaint gp = new GradientPaint(
r.x,
r.y,
new Color(255, 225, 0, 40),
r.x,
r.y + (int) r.getHeight(),
new Color(255, 225, 0, 188));
g.setPaint(gp);
g.fill(keyShape);
g.setColor(Color.GRAY);
g.draw(keyShape);
}
}
public boolean isPressed() {
return pressed;
}
public void setPressed(boolean pressed) {
this.pressed = pressed;
}
}
I'll be watching to see if there is a better answer than either of the two suggestions that I have, which are clearly less than ideal.
edit the midi file to include meta events that match the existing key on/off
write you own event system
I don't do a lot yet with MIDI, myself. I only occasionally import MIDI scores and strip out most of the info, converting it to use with an event-system I wrote for my own audio needs (triggering an FM synthesizer I wrote).
An answer here. Something like:
class MidiPlayer implements Receiver {
private Receiver myReceiver;
void play() {
Sequencer sequencer = MidiSystem.getSequencer();
...
// Save the original receiver
this.myReceiver = sequencer.getReceiver();
// Override the receiver
sequencer.getTransmitter().setReceiver(this);
sequencer.start();
}
#Override
public void send(MidiMessage msg, long tstamp) {
// Send the message to the original receiver
this.myReceiver.send(msg, tstamp);
// Process the message
if (msg instanceof ShortMessage) {
ShortMessage shortMsg = (ShortMessage) msg;
if (shortMsg.getCommand() == ShortMessage.NOTE_ON) {
System.out.printf("NOTE ON\n");
}
}
...
}

Applet does not load on html page

I have this applet and i cant figure out why it doesnt load on html page.I have added full permissions in java.policy file. I use the default html file from NetBeans Applet's output.
/* Hearts Cards Game with AI*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.awt.Graphics;
import java.awt.Image;
import java.security.AccessController;
import javax.swing.ImageIcon;
import javax.swing.*;
import javax.swing.JPanel;
public class Game extends JApplet implements MouseListener, Runnable {
int initNoCards = 13;
int width, height;
boolean endGame = false;
int turn = -1;
int firstCard = 0;
int firstTrick = 0;
String leadingSuit = null;
Cards leadingCard = null;
Cards playCard = null;
String startCard = "c2";
Cards[] trickCards = new Cards[4];
ArrayList<Cards>[] playerCards = new ArrayList[4];
ArrayList<Cards>[] takenCards = new ArrayList[4];
boolean heartsBroken = false;
ArrayList<Cards> cards = new ArrayList<Cards>();
String[] hearts = {"h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "h10", "h12", "h13", "h14", "h15"};
String queen = "s13";
int cardHeight = 76;
int cardWidth = 48;
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
int selectedCard = -1;
//set the background image
Image backImage = new ImageIcon("deck\\back2.png").getImage();
public void GetDataFromXML() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
boolean image = false;
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
if (qName.equalsIgnoreCase("IMAGE")) {
image = true;
}
}
#Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
}
#Override
public void characters(char ch[], int start, int length) throws SAXException {
String s = new String(ch, start, length);
if (name) {
cards.add(new Cards(s));
name = false;
}
if (image) {
image = false;
}
}
};
saxParser.parse("deck\\deck.xml", handler);
} catch (Exception e) {
}
}
//function for comparing cards from same suite
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
//checks if a card is valid to play
public boolean ValidMove(Cards c) {
if (firstCard == 0) {
if (c.getName().equals(startCard)) {
firstCard = 1;
return true;
}
return false;
}
boolean result = playerCards[turn].indexOf(c) >= 0;
if (leadingSuit == null) {
return result;
}
boolean found = false;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) == leadingSuit.charAt(0)) {
found = true;
break;
}
}
if (!found) {
boolean justHearts = true;
for (int i = 0; i < playerCards[turn].size(); i++) {
if (playerCards[turn].get(i).getName().charAt(0) != 'h') {
justHearts = false;
break;
}
}
if (firstTrick == 0) {
if (c.getName().equals(queen)) {
return false;
}
if (!justHearts && c.getName().charAt(0) == 'h') {
return false;
}
} else {
if (c.getName().charAt(0) == 'h' && leadingSuit == null && !heartsBroken && !justHearts) {
return false;
}
}
} else {
if (c.getName().charAt(0) != leadingSuit.charAt(0)) {
return false;
}
}
return result;
}
#Override
public void init() {
GetDataFromXML();
setSize(500, 500);
width = super.getSize().width;
height = super.getSize().height;
setBackground(Color.white);
addMouseListener(this);
for (int i = 0; i < cards.size(); i++) {
System.out.println(cards.get(i).getName());
System.out.println(cards.get(i).getImage());
}
Shuffle();
}
public int GetTrickCount() {
int count = 0;
for (int i = 0; i < trickCards.length; i++) {
if (trickCards[i] != null) {
count++;
}
}
return count;
}
public void ResetTrick() {
for (int i = 0; i < trickCards.length; i++) {
trickCards[i] = null;
}
}
#Override
public void run() {
try {
PlayTurn();
} catch (InterruptedException ex) {
}
}
public void start() {
Thread th = new Thread(this);
th.start();
}
//function for shuffling cards and painting players cards
public void Shuffle() {
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
}
ArrayList<Cards> list = new ArrayList<Cards>();
list.addAll(cards);
Collections.shuffle(list);
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i).getName() + " ");
}
//initializare liste carti
for (int i = 0; i < 4; i++) {
playerCards[i] = new ArrayList<Cards>();
takenCards[i] = new ArrayList<Cards>();
for (int j = 0; j < initNoCards; j++) {
playerCards[i].add((list.get(j + i * initNoCards)));
if (list.get(j + i * initNoCards).getName().equals(startCard)) {
turn = i;
}
}
Collections.sort(playerCards[i], c);
ShowCards(i);
}
for (int i = 0; i < playerCards[0].size() - 1; i++) {
rectangles.add(new Rectangle((141 + 1) + 13 * i - 2, 350 + 1, 13 - 2, cardHeight - 1));
}
rectangles.add(new Rectangle((141 + 1) + 13 * 12 - 2, 350 + 1, cardWidth, cardHeight - 1));
ShowPlayersCards();
}
Comparator<Cards> c = new Comparator<Cards>() {
#Override
public int compare(Cards o1, Cards o2) {
if (o2.getName().charAt(0) != o1.getName().charAt(0)) {
return o2.getName().charAt(0) - o1.getName().charAt(0);
} else {
int a, b;
a = Integer.parseInt(o1.getName().substring(1));
b = Integer.parseInt(o2.getName().substring(1));
return a - b;
}
}
};
public void PlayTurn() throws InterruptedException {
endGame = true;
System.out.println("Its " + turn);
for (int i = 0; i < 4; i++) {
if (!playerCards[i].isEmpty()) {
endGame = false;
}
}
if (endGame) {
System.out.println("Game over!");
GetPlayersScore();
return;
}
if (turn != 0) {
Random r = new Random();
int k = r.nextInt(playerCards[turn].size());
Cards AIcard = playerCards[turn].get(k);
while (!ValidMove(AIcard)) {
k = r.nextInt(playerCards[turn].size());
AIcard = playerCards[turn].get(k);
}
leadingCard = AIcard;
playCard = AIcard;
} else {
System.out.println("\nIt is player's (" + turn + ") turn");
System.out.println("Player (" + turn + ") enter card to play:");
leadingCard = null;
playCard = null;//new Cards(read);
while (true) {
if (playCard != null) {
break;
}
Thread.sleep(50);
}
}
repaint();
Thread.sleep(1000);
repaint();
if (playCard.getName().charAt(0) == 'h') {
heartsBroken = true;
}
playerCards[turn].remove(playCard);
trickCards[turn] = playCard;
if (GetTrickCount() == 1)//setez leading suit doar pentru trickCards[0]
{
leadingSuit = GetSuit(playCard);
}
System.out.println("Leading suit " + leadingSuit);
System.out.println("Player (" + turn + ") chose card " + playCard.getName() + " to play");
ShowTrickCards();
ShowPlayersCards();
if (GetTrickCount() < 4) {
turn = (turn + 1) % 4;
} else {
turn = GetTrickWinner();
leadingSuit = null;
firstTrick = 1;
playCard = null;
repaint();
}
PlayTurn();
}
public void ShowTrickCards() {
System.out.println("Cards in this trick are:");
for (int i = 0; i < 4; i++) {
if (trickCards[i] != null) {
System.out.print(trickCards[i].getName() + " ");
}
}
}
public String GetSuit(Cards c) {
if (c.getName().contains("c")) {
return "c";
}
if (c.getName().contains("s")) {
return "s";
}
if (c.getName().contains("h")) {
return "h";
}
if (c.getName().contains("d")) {
return "d";
}
return null;
}
public String GetValue(Cards c) {
String get = null;
get = c.getName().substring(1);
return get;
}
public int GetTrickWinner() {
int poz = 0;
for (int i = 1; i < 4; i++) {
if (trickCards[poz].getName().charAt(0) == trickCards[i].getName().charAt(0) && lowerThan(trickCards[poz], trickCards[i]) == true) {
poz = i;
}
}
System.out.println("\nPlayer (" + poz + ") won last trick with card " + trickCards[poz].getName());
ResetTrick();
return poz;
}
public void ShowPlayersCards() {
ShowCards(0);
ShowCards(1);
ShowCards(2);
ShowCards(3);
}
public void GetPlayersScore() {
GetScore(0);
GetScore(1);
GetScore(2);
GetScore(3);
}
public void ShowCards(int player) {
System.out.print("\nPlayer (" + player + ") cards: ");
for (int i = 0; i < playerCards[player].size(); i++) {
System.out.print(playerCards[player].get(i).getName() + " ");
}
System.out.println();
}
public int GetScore(int player) {
int score = 0;
for (int i = 0; i < takenCards[player].size(); i++) {
for (int j = 0; j < hearts.length; j++) {
if (takenCards[player].get(i).getName().equals(hearts[j])) {
score++;
break;
}
}
if (takenCards[player].get(i).getName().equals(queen)) {
score += 13;
}
}
return score;
}
#Override
public void paint(Graphics g) {
g.drawImage(backImage, 0, 0, getWidth(), getHeight(), this);
for (int i = 0; i < playerCards[0].size(); i++) {
if (selectedCard == i) {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 340, null);
} else {
g.drawImage(playerCards[0].get(i).getImage(), 141 + i * 13, 350, null);
}
if (trickCards[0] != null) {
g.drawImage(trickCards[0].getImage(), 225, 250, 48, 76, null);
}
if (trickCards[1] != null) {
g.drawImage(trickCards[1].getImage(), 177, 174, 48, 76, null);
}
if (trickCards[2] != null) {
g.drawImage(trickCards[2].getImage(), 225, 98, 48, 76, null);
}
if (trickCards[3] != null) {
g.drawImage(trickCards[3].getImage(), 273, 174, 48, 76, null);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
if (turn != 0) {
return;
}
for (int i = 0; i < rectangles.size(); i++) {
if (rectangles.get(i).contains(e.getPoint())) {
if (i == selectedCard) {
if (ValidMove(playerCards[0].get(i))) {
selectedCard = -1;
rectangles.get(rectangles.size() - 2).width = rectangles.get(rectangles.size() - 1).width;
playCard = playerCards[0].get(i);
leadingCard = playCard;
rectangles.remove(rectangles.size() - 1);
trickCards[0] = playerCards[0].remove(i);
} else {
if (firstCard == 0) {
JOptionPane.showMessageDialog(this, "You have to play 2 of clubs!");
}
}
} else {
selectedCard = i;
rectangles.get(i).y -= 10;
}
repaint();
break;
}
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
class Cards extends JPanel {
private String name;
private String image;
private Image img;
public Cards(String name) {
super();
this.name = name;
this.image = "deck\\" + name + ".png";
this.img = new ImageIcon(image).getImage();
}
public Cards() {
super();
this.name = null;
this.image = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Image getImage() {
return img;
}
public void setImage(String image) {
this.image = image;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Cards)) {
return false;
}
Cards c = (Cards) obj;
return name.equals(c.getName()) && image.equals(c.getImage());
}
#Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 31 * hash + (this.image != null ? this.image.hashCode() : 0);
return hash;
}
#Override
public void paint(Graphics g) {
g.drawImage(img, WIDTH, HEIGHT, this);
}
public boolean lowerThan(Cards c1, Cards c2) {
int a, b;
a = Integer.parseInt(c1.getName().substring(1));
b = Integer.parseInt(c2.getName().substring(1));
return a < b;
}
public int compareTo(Cards c) {
if (c.getName().charAt(0) != name.charAt(0)) {
return c.getName().charAt(0) - name.charAt(0);
} else {
int a, b;
a = Integer.parseInt(name.substring(1));
b = Integer.parseInt(c.getName().substring(1));
return a - b;
}
}
}
HTML
<HTML>
<HEAD>
<TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>
<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>
<P>
<APPLET codebase="classes" code="Game.class" width=350 height=200></APPLET>
</P>
<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
Image backImage = new ImageIcon("deck\\back2.png").getImage();
If I am the user of the applet when it is on the internet, the will cause the JRE to search for a File relative to the current user directory on my PC, either that or the cache of FF. In either case, it will not locate an image by the name of back2.png.
For fear of sounding like a looping Clip:
Resources intended for an applet (icons, BG image, help files etc.) should be accessed by URL.
An applet will not need trust to access those resources, so long as the resources are on the run-time class-path, or on the same server as the code base or document base.
Further
I have added full permissions in java.policy file.
This is pointless. It will not be workable at time of deployment unless you control every machine it is intended to run on. If an applet needs trust in a general environment, it needs to be digitally signed. You might as well sign it while building the app.
cant figure out why it doesnt load on html page.
Something that would assist greatly is to configure the Java Console to open when an applet is loaded. There is a setting in the last tab of the Java Control Panel that configures it.

Categories