Calling 2 classes from Java GUI within Matlab - java

Since Java cannot unload native libraries when once used (in Matlab; see SO question), i am trying to call 2 GUI classes from within Matlab. I am working on grabbing an image from camera and then saving it on disk. I want to use one Java class for communicating with camera while another class (GUI) is still open in Matlab. Is this possible? Here's the code:
1.
public class GUI
{
public static void main(String[] args)
{
// Just open up the window and start things running
MainWindow mWindow = new MainWindow();
}
public static void main2()
{
MainWindow.grabImage(0);
}
}
2.
public class MainWindow
{
static volatile int commandVal;
Thread updateThread;
static CameraImage cImage;
static int fs_c =1;
MainWindow(){
JFrame main_f = new JFrame("M");
main_f.getContentPane().setLayout(new BorderLayout());
main_f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
main_f.getContentPane().add(tabPane1, "Center");
main_f.pack();
main_f.setVisible(true);
kkk = 1;
mySerial = new CameraSerial(cWindow.getPort());
}
}
3.
public static void grabImage(int commandVal){
while (MainWindow.kkk == 1) {
if (MainWindow.fs_c == 1) {
MainWindow.commandVal = 5;
}
if (MainWindow.commandVal == 5 || MainWindow.commandVal == 6){
cImage.sendFrame(0);
JFileChooser save_d = new JFileChooser();
File saveFile = save_d.getSelectedFile();
cImage.writeImage(saveFile + ".jpg");
MainWindow.fs_c = 0;
MainWindow.commandVal = 0;
mySerial.write("\r");
System.out.println("Camera Ready...");
break;
}
else if (commandVal == -1) {
MainWindow.commandVal = 0;
mySerial.write("\r");
status_t.setText("Camera Ready...");
}
else {
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
}
From Matlab I'm calling first Gui.main([]), and then Gui.main2(). It works for the first time. But when I call Gui.main2() again, Matlab does nothing. I think it's a bad code somewhere. Thanks for replying!

Just an assumption without having more information:
This check:
if (MainWindow.fs_c == 1) {
MainWindow.commandVal = 5;
}
And later this (note that commandVal would be 5 after the check succeeded for the first time):
MainWindow.fs_c = 0;
MainWindow.commandVal = 0;
Here's the problem:
In the first run, commandVal is set to 5, assuming MainWindow.fs_c is initially 1.
Thus MainWindow.fs_c = 0; is executed.
In the second run MainWindow.fs_c == 1 is false (MainWindow.fs_c is now 0) and MainWindow.commandVal was also set to 0. Thus the method doesn't do anything, except sleeping for 100 milliseconds.

Related

Why aren't my ArrayList items removing themselves when they disapear?

I am trying to get my Asteroids game in Java to have the ArrayList container be removed once it's off screen. I figured out how to stop having it print when off screen, but can see in my console the array continues to grow. Not sure where to go from here.
I think the way I can get them to be removed when off screen is by either using the remove or set feature with arrayLists. Visually everything is disappearing right, but in the console my ArrayList is still growing. I thought about setting a limit of how long it can be, but not sure if there is a better way than that.
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
public class AsteroidGame extends Frame {
private int FrameWidth = 500;
private int FrameHeight = 400;
static public void main(String[] args) {
AsteroidGame world = new AsteroidGame();
world.show();
world.run();
}
public AsteroidGame() {
setTitle("Asteroid Game0");
setSize(FrameWidth, FrameHeight);
addKeyListener(new keyDown());
addWindowListener(new CloseQuit());
}
public void run() {
while (true) {
movePieces();
repaint();
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
private ArrayList asteroids = new ArrayList();
private ArrayList rockets = new ArrayList();
private Station station = new Station(FrameWidth / 2, FrameHeight - 20);
public void paint(Graphics g) {
station.paint(g);
Iterator astIt = asteroids.iterator();
while (astIt.hasNext()) {
Asteroid rock = (Asteroid) astIt.next();
if (rock.y >= 400 || rock.x >= 500){
rock = null;
} else {
rock.paint(g);
}
}
Iterator rocIt = rockets.iterator();
while (rocIt.hasNext()) {
Rocket rock = (Rocket) rocIt.next();
if (rock.y >= 400 || rock.x >= 500) {
rock = null;
} else {
rock.paint(g);
}
}
}
public void movePieces() {
if (Math.random() < 0.3) {
Asteroid newRock = new Asteroid(FrameWidth * Math.random(), 20, 10 * Math.random() - 5, 3 + 3 * Math.random());
if (newRock.y >= 500 || newRock.x >= 500){
asteroids.remove(0);
} else{
asteroids.add(newRock);
}
System.out.println(asteroids.size());
}
Iterator astIt = asteroids.iterator();
while (astIt.hasNext()) {
Asteroid rock = (Asteroid) astIt.next();
if (rock.y >= 400 || rock.x >= 500) {
rock = null;
} else {
rock.move();
station.checkHit(rock);
}
}
Iterator rocIt = rockets.iterator();
while (rocIt.hasNext()) {
Rocket rock = (Rocket) rocIt.next();
if (rock.y >= 400 || rock.x >= 500) {
rock = null;
} else {
rock.move(asteroids);
}
}
}
private class gameMover extends Thread {
public void run() {
while (true) {
movePieces();
repaint();
try {
sleep(100);
} catch (Exception e) {
}
}
}
}
Change:
rock = null;
to:
astIt.remove();
Assigning null to the variable that has been assigned the value of an element of a List does absolutely nothing to either the List or the element in it; it only affects the value that the variable holds.
As an aside, nice variable name choice of rock - it is appropraite for both types of object - either an abbreviation of "rocket" or a reasonable synonym for an astroid.
Change rock = null; to asteroids.remove(rock); or astIt.remove();
and it should be fine, also no need to set the variable to null as the garbage collector will take care of it for you.
EDIT
Actually asteroids.remove(rock); will throw an exception as said in the comments of this answer, so nevermind it and use the other.
Also I think when in movePieces() you create a new rock and you check if this new rock is outside the screen, I don't think removing the first asteroid in the ArrayList is correct as you will not add the new rock (which may be right if the rock can actually randomly spawn outside the screen) but you will also remove a maybe fine working asteroid from the ArrayList (and thus from the game and the screen).
So, personally I would change that part of code to:
if (Math.random() < 0.3) {
Asteroid newRock = new Asteroid(FrameWidth * Math.random(), 20, 10 * Math.random() - 5, 3 + 3 * Math.random());
if (!(newRock.y >= 500 || newRock.x >= 500)){
asteroids.add(newRock);
}
System.out.println(asteroids.size());
}
But tell me if this works for you.

I'm trying to add a value to an int in one class and then use it in another, Java

So as the title says im struggling to add a value to an integer and then pass it to another class that uses it, then this class will pass it to the next and then that one will pass it over to the main class. Its an integer that changes the stat template of the enemies in my small game im writing.
I have tried to make constructors in two of my classes as I thought that was the problem, Ive tried to see if they work by passing some messages in them.
The problem seems to be that when I save something in the "private int l" It dosnt actually change the value of that int and I cant figure out why that is.
Here is my code, its probably not very pretty so if you have any suggestions to structure changes that I might wanna do please feel free too let me know!
Thanks in advance!
import java.util.Scanner;
public class Stor {
public static void main(String[] args) {
Scanner user_Input = new Scanner(System.in);
Menu user = new Menu();
EnemyValue monster = new EnemyValue();
user.namn();
user.AnvNamn = user_Input.next();
user.introMeny();
user.difficulty();
System.out.println(“Your enemy has " + monster.HP + " HP and " +
monster.DMG + " Damage" );
user_Input.close();
}
}
class Menu {
Scanner user_Input = new Scanner(System.in);
String AnvNamn;
String difficultySvar;
String nivåSvar;
int svar;
private int i; /
private int l;
public int getL() {
return l;
}
boolean difficultyLoop = true;
boolean felLoop = true;
void introMeny() {
System.out.println(“Welcome " + AnvNamn + "!");
}
void namn() {
System.out.print(“Pick a name: “);
}
void difficulty() {
do {
System.out.println("\nWhat level do you want ?\n1 = Easy.\n2 =
Medium.\n3 = Hard.”);
svar = user_Input.nextInt();
if (svar == 1) {
System.out.println(“Your not very brave are you ? Are you sure
this is how you wanna play ?”);
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 1;
} // If ja 1
else if (difficultySvar.equalsIgnoreCase(“Nej”)) {
System.out.println(“Ahh good! I figuerd you would change
your mind.”);
}
else
System.out.println(“I don’t understand….”);
} // if 1
else if (svar == 2) {
System.out.println(“Not to hard or to easy, a good choice! But
maybe you want to go for something harder ? Or maybe easier ?");
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 2;
} // if ja 2
else if (difficultySvar.equalsIgnoreCase(“No”)) {
System.out.println(“I sure hope you don’t pick the easy
way…..”);
}
else
System.out.println("I don’t understand….");
} // Else if 2
else if (svar == 3) {
System.out.println(“Damn! We have a big player here! Are you
sure you can handle this ?");
difficultySvar = user_Input.next();
if (difficultySvar.equalsIgnoreCase(“Yes”)) {
difficultyLoop = false;
l = 3;
} // If ja 3
else if (difficultySvar.equalsIgnoreCase(“No”)) {
System.out.println(“Wuss.”);
}
else
System.out.println(“I don’t understand….”);
} // Else if 3
else {
if (i == 0) {
System.out.println(“Ha you thought you could fool the system?!
The system fools you!”);
System.out.println(“Nah but seriously, you can only choose
between 1-3…..“);
i++;
} // if i 0
else if (i == 1) {
System.out.println(“Alright I get that its hard but
COMEON!”);
i++;
} // if i 1
else if (i == 2) {
System.out.println(“OKEY YOU GET ONE LAST CHANCE!!”);
i++;
} // if i 2
else if (i == 3) {
System.out.println(“Alright thats it…. GET OUT!”);
System.exit(0);
} // if i 3
} // Else
} // do while loop
while(difficultyLoop == true);
} //Difficulty metod.
} // Menu class.
class Nivå {
//Menu level = new Menu();
//int levelChoice = level.getL();
int levelChoice;
private int enemyLife;
public int getenemyLife() {
return enemyLife;
}
private int enemyDMG;
public int getenemyDMG() {
return enemyDMG;
}
Nivå(){
Menu level = new Menu();
levelChoice = level.getL();
System.out.println("testNivå");
}
void fiendeLiv() {
if (levelChoice == 1)
enemyLife = 100;
else if (levelChoice == 2)
enemyLife = 150;
else if (levelChoice == 3)
enemyLife = 200;
} // fiendeliv method
void fiendeDMG() {
if (levelChoice == 1)
enemyDMG = 5;
else if (levelChoice == 2)
enemyDMG = 10;
else if (levelChoice == 3)
enemyDMG = 15;
} // fiendeDMG method
} // Nivå class
class EnemyValue {
public int HP;
public int DMG;
int maxLife;
int maxDMG;
EnemyValue(){
Nivå stats = new Nivå();
maxLife = stats.getenemyLife();
maxDMG = stats.getenemyDMG();
System.out.println("TestEnemyValue");
}
void rank1() {
HP = maxLife;
DMG = maxDMG;
} // rank1 easy method
} // EnemyValue class
You say that when you save something in l (poor choice of a variable name, by the way) it does not save the value. How do you know that? Where in the code do you check whether the value is saved?
In the constructor for class Nivå you create a new Menu and then call getL() on that menu before you have ever set the value of that variable.
Everything runs at the start of your public static void main(String[] args) method, and nothing will run if its instructions are not in there. For example, you are not actually creating any Niva objects in the main method, so the Niva constructor is never called. That is one issue. The other is your constructors are creating new instances of objects and then getting their values; this gives you empty values from a brand new object:
Nivå(){
Menu level = new Menu(); // Don't do this. This is an empty menu
levelChoice = level.getL(); // Getting the blank L value from the empty menu
System.out.println("testNivå");
}
Instead, you need to define constructors with parameters to pass the values into the class like this:
Nivå(int level){ // add an int parameter
levelChoice = level; // Direct assignment
fiendeDMG(); // Call this in the constructor to set up your last value
System.out.println("testNivå");
}
Then, when you call the constructor (which you must if you want it to exist), include the parameter. Inside the Stor class:
public static void main(String[] args) {
Scanner user_Input = new Scanner(System.in);
Menu user = new Menu();
user.namn();
user.AnvNamn = user_Input.next();
user.introMeny();
user.difficulty(); // Run this before creating the other classes; you need the l value
Nivå niva = new Nivå(user.getL()); // Creates new Niva while also assigning l to the levelChoice and then getting DMG
EnemyValue monster = new EnemyValue(/*add some parameters for life and dmg*/);
}
There is still more that needs to be done, like modifying the constructor of the EnemyLevel. Just remember that methods are never called unless they connect to something running from main and use parameters in functions and constructors to pass on data to other objects. Hope this helps.

System.out.println doesn't show text in console (IntelliJ)

I am writing a program which part is presented below:
public class Portal {
private String name;
private int[] positions; // positions of "ship"
private static int moves = 0; // moves made by player to sink a ship
public static int shot; // the value of position given by player
private int hits = 0; // number of hits
private int maxSize = 4; // max size of ship (the size will be randomized)
int first; // position of 1st ship block
int size; // real size of ship (randomized in setPortal method)
public void checkIfHit(){
for (int i : positions){
if (i == shot){
System.out.println("Hit confirmed");
hits++;
} else if (hits == positions.length){
System.out.println("Sunk");
} else {
System.out.println("Missed it");
}
}
moves++;
}
public void setPortal(){
size = 1 + (int)Math.random()*maxSize;
for (int i = 0; i < size - 1; i++){
if (i == 0){
positions[i]= 1 + (int)Math.random()*positions.length;
first = positions[i];
System.out.println(positions[i]);
continue;
}
positions[i]= first + 1;
System.out.println(positions[i]);
}
}
}
public class Main{
public static void main(String[] args){
// write your code here
Portal p1 = new Portal();
p1.setPortal();
}
}
code is split in two Java .class files.
The problem I'm dealing with is that using p1.setPortal(); doesn't show up text in IntelliJ console. The program works though and returns 0.
I don't have such problem in another program when I've put System.out.println in method other than main (also in separate class file).
What may be the cause of such issue?
It should properly throw an exception, because you forgot to initialize the integer array.
Have a look at this thread: Do we need to initialize an array in Java?
The Java's default value is null for an integer array. So your for wont even loop trough. The only thing that wonders me is why there is no exception..

Instance Variable Changing

I would like to make movement of a square with only using Instance Variable. I'm having troubles this is my code :
I have one for Variables.JAVA for Variables :
public class Variables {
String name;
int Playerx;
int Playery;
int Playerw;
int Playerh;
}
and one where it is the main but doesn't change the variables above. (simplified)
public static void main(String args[]) throws InterruptedException {
while (true) {
Variables P = new Variables(){
synchronized (c) {
c.clear();
first_level();
P.Playerx = 50;
P.Playery = 50;
P.Playerw = 100;
P.Playerh = 100;
c.drawRect(P.Playerx, P.Playery, P.Playerw, P.Playerh);
}
Thread.sleep(25);
// Controls
if (c.isKeyDown(Console.VK_UP)) {
P.Playery -= 10;
}
else if (c.isKeyDown(Console.VK_DOWN)) {
P.Playery += 10;
}
else if (c.isKeyDown(Console.VK_LEFT)) {
P.Playerx -= 10;
}
else if (c.isKeyDown(Console.VK_DOWN)) {
P.Playery += 10;
}
}
The P.Player(x,y,w,h) don't change?
How can this be solved?
You are setting the defaults in every iteration, your code is synchronic and therefore responding to the keys is done after you draw, and in the next iteration you are overriding the values again so you will never see any changes.
In addition you instantiate a new P object every time and not keeping the previous instances alive, therefore they are GC.

Thread terminating when running a function in java

I am programing a midi maker that you can make a song through the console (and later a window) but I'm having a thread issue. When I want the song to start, the thread starts but it doesn't run the function that has the song player. I copy and pasted the base code from a working project and I cant figure out why it is not running. IT prints "setting up" but not "running". Here is my code for the function:
public void songStart() throws InterruptedException {
int temp;
channelVolume = new int[channelNotes.length][channelNotes[0].length];
if (channelNotes.length < userChannels.length) {
temp = channelNotes.length;
} else {
temp = userChannels.length;
}
for (int j = 0; j < userChannelNotesNumLongest; j++) {
for (int i = 0; i < temp; i++) {
if (channelNotes[i][j] == r) {
channelVolume[i][j] = 0;
} else if (advanced == false){
channelVolume[i][j]=50;
}
}
}
System.out.println("running");
for (int i = 0; i < temp; i++) {
for (int j = 0; j < userChannelNotesNumLongest; j++) {
noteOn(userChannels[i],channelNotes[i][j],channelVolume[i][j]);
Thread.sleep(interval);
noteOff(userChannels[i],channelNotes[i][j]);
}
}
}
And this is the code for the thread:
public class SongThread extends Thread {
public void run(){
try {
Main.song.songStart();
} catch (InterruptedException e) { }
}
}
Here is were the code runs the thread (i have a print in there that does print)
if (userInput.equals("start")) {
System.out.println("setting up");
SongThread thread = new SongThread();
thread.start();
}
Note: everything works fine until the thread tries to run the function, then it just stops running it. Also, it is the same base code in the other project that works fine. The function that is displayed is in a class instance in Main called song. And I don't get an error from the catch. Keep in mind that I copy and pasted the code from a working project and the only thing different is that it is not static and runs the instance from the Main class
I have tried making the songStart function static with everything inside as well. I have used all the combinations of try / catch an d throws exceptions in the thread and the function (where the thread didn't have a try / catch or throws and where the function has a try / catch or a throws). the way I have it in my working project is a throws in the function and a try / catch in the thread.

Categories

Resources