When changing anything in the GUI from the G4P GUI Builder tool, the program always crashes with a NullPointerException in 2 - 5 minutes and does not highlight the problematic line of code.
The GUI is part of a larger program which simulates a Magnifying Glass setting material on fire:
The error:
NullPointerException
NullPointerException
NullPointerException
NullPointerException
java.lang.NullPointerException
at g4p_controls.StyledString.getLines(Unknown Source)
at g4p_controls.GLabel.updateBuffer(Unknown Source)
at g4p_controls.GLabel.draw(Unknown Source)
at g4p_controls.GWindowAWT.draw(Unknown Source)
at processing.core.PApplet.handleDraw(PApplet.java:2482)
at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1547)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:313)
NullPointerException
===================================================
G4P GUI Builder 4.4.2 created by Peter Lager
===================================================
Could not run the sketch (Target VM failed to initialize).
For more information, read revisions.txt and Help ? Troubleshooting.
Code section for GUI Event Handlers:
public void pauseButtonClicked(GButton source, GEvent event) { //_CODE_:pauseButton:875606:
// If the program is running, stop
if(running) {
running = !running;
noLoop();
pauseButton.setText("Resume");
}
// If the program is paused, run
else {
running = !running;
loop();
pauseButton.setText("Pause");
}
} //_CODE_:pauseButton:875606:
public void massSliderChanged(GCustomSlider source, GEvent event) { //_CODE_:massSlider:958855:
println("massSlider - GCustomSlider >> GEvent." + event + " # " + millis());
} //_CODE_:massSlider:958855:
public void focalDistanceSliderChanged(GCustomSlider source, GEvent event) { //_CODE_:focalDistanceSlider:299666:
} //_CODE_:focalDistanceSlider:299666:
public void xPositionSliderChanged(GCustomSlider source, GEvent event) { //_CODE_:xPositionSlider:537864:
println("xPositionSlider - GCustomSlider >> GEvent." + event + " # " + millis());
} //_CODE_:xPositionSlider:537864:
public void yPositionSliderChanged(GCustomSlider source, GEvent event) { //_CODE_:yPositionSlider:494398:
println("yPositionSlider - GCustomSlider >> GEvent." + event + " # " + millis());
} //_CODE_:yPositionSlider:494398:
public void beamIntensitySliderChanged(GCustomSlider source, GEvent event) { //_CODE_:beamIntensitySlider:967979:
float num = beamIntensitySlider.getValueF();
if(num > 0.1 && num < 2 ) {
material.beamIntensity = num;
}
} //_CODE_:beamIntensitySlider:967979:
public void materialChoiceClicked(GDropList source, GEvent event) { //_CODE_:materialChoice:221684:
if (materialChoice.getSelectedText().equals("Ant")) {
currentMaterial = "ant";
}
else if (materialChoice.getSelectedText().equals("Paper")) {
currentMaterial = "paper";
}
else if (materialChoice.getSelectedText().equals("Grass")) {
currentMaterial = "grass";
}
else {
currentMaterial = "wood";
}
reset();
} //_CODE_:materialChoice:221684:
public void glassQualityChanged(GDropList source, GEvent event) { //_CODE_:glassQuality:419836:
if (glassQuality.getSelectedText().equals("Clear")) {
magnifyingGlass.lensQuality = "Clear";
magnifyingGlass.transparency = 1;
}
else if (glassQuality.getSelectedText().equals("Impurities")) {
magnifyingGlass.lensQuality = "Impurities";
magnifyingGlass.transparency = 0.75;
}
else if (glassQuality.getSelectedText().equals("Dirty")) {
magnifyingGlass.lensQuality = "Dirty";
magnifyingGlass.transparency = 0.5;
}
} //_CODE_:glassQuality:419836:
public void temperatureSliderChanged(GSlider source, GEvent event) { //_CODE_:temperatureSlider:230192:
surroundingTemperature = temperatureSlider.getValueI();
currentTemperature.setText(str(surroundingTemperature));
reset();
println("slider1 - GSlider >> GEvent." + event + " # " + millis());
} //_CODE_:temperatureSlider:230192:
What is the most efficient fix if we must stick to the G4P GUI builder?
We tried:
following solutions found in online forums e.g. use a slider instead of a textbox
defining all variables used in the program
using try-catch statements
recreating the GUI in the latest version of Processing
but there were no changes from the error.
Related
I wanted to say for a school project in Greenfoot, that if a rover encounters a system error, it should output this and then wait a short time and then terminate the current method. However, the pause is marked with the following error code: unreported exception java. lang. InterupptedException; must be cought or declared to be thrown, as I am very new to Java I have no idea what to change. Besides, he should then end the method, but with the current command the whole scenario is ended.
"
public Rover (String pname, char pfrequenz, int penergie)
{
energie = penergie;
name = pname;
temp = 15 ;
distance = 0;
systemcheck = true;
frequenz = pfrequenz ;
}
public void check()
{
if (markeVorhanden())
{
energie = energie + 100;
}
if (energie == 0){
systemcheck = false;
}
if (systemcheck = false){
nachricht("System Failure");
java.util.concurrent.TimeUnit.SECONDS.sleep(2);
System.exit(0);
}
if (distance > 100){
nachricht("Congrats you have passed 100");
}
anzeige.anzeigen("Akku: "+energie+ " %");
}
Try this
import java.io.*;
public class Yourclass{
public void Rover (String pname, char pfrequenz, int penergie)
{
Integer energie = penergie;
String name = pname;
Integer temp = 15 ;
Integer distance = 0;
boolean systemcheck = true;
char frequenz = pfrequenz ;
}
public void check() throws IOException
{
if (markeVorhanden())
{
energie = energie + 100;
}
if (energie == 0){
systemcheck = false;
}
if (systemcheck = false){
nachricht("System Failure");
throw new IOException("sorry device error");
}
if (distance > 100){
nachricht("Congrats you have passed 100");
}
anzeige.anzeigen("Akku: "+energie+ " %");
}
public static void main(String []args) throws InterruptedException
{
Yourclass demo= new Yourclass();
System.out.println("Hello World");
try{
demo.check();
}
catch(Exception e)
{
Thread.sleep(2000);
System.out.println("function stopped");
}
}
}
You will have to read up on exception handling in Java. The sleep method may get interrupted and may thus raise an InterruptedException. You can either forward this exception or ignore it.
To forward the exception, declare the function a
public void check() throws InterruptedException
but then callers of this function will have to deal with that potential exception. Since interrupted does not look a severe problem here (the sleep is just a bit shorter than the two seconds), it may be fine to ignore the exception:
try { java.util.concurrent.TimeUnit.SECONDS.sleep(2); }
catch (InterruptedException ignored) {}
In order to just return from the current method use return instead of System.exit()
I have a PhidgetRFID chip (P/N:1023, version 205). I am trying to make a simple program in order to detect tags and show their unique id number. I found the following source code from its manufacturer website
import com.phidgets.*;
import com.phidgets.event.*;
public class RFIDExample
{
public static final void main(String args[]) throws Exception {
RFIDPhidget rfid;
System.out.println(Phidget.getLibraryVersion());
rfid = new RFIDPhidget();
rfid.addAttachListener(new AttachListener() {
public void attached(AttachEvent ae)
{
try
{
((RFIDPhidget)ae.getSource()).setAntennaOn(true);
((RFIDPhidget)ae.getSource()).setLEDOn(true);
}
catch (PhidgetException ex) { }
System.out.println("attachment of " + ae);
}
});
rfid.addDetachListener(new DetachListener() {
public void detached(DetachEvent ae) {
System.out.println("detachment of " + ae);
}
});
rfid.addErrorListener(new ErrorListener() {
public void error(ErrorEvent ee) {
System.out.println("error event for " + ee);
}
});
rfid.addTagGainListener(new TagGainListener()
{
public void tagGained(TagGainEvent oe)
{
System.out.println("Tag Gained: " +oe.getValue() + " (Proto:"+ oe.getProtocol()+")");
}
});
rfid.addTagLossListener(new TagLossListener()
{
public void tagLost(TagLossEvent oe)
{
System.out.println(oe);
}
});
rfid.addOutputChangeListener(new OutputChangeListener()
{
public void outputChanged(OutputChangeEvent oe)
{
System.out.println(oe);
}
});
rfid.openAny();
System.out.println("waiting for RFID attachment...");
rfid.waitForAttachment(30000);
System.out.println("Serial: " + rfid.getSerialNumber());
System.out.println("Outputs: " + rfid.getOutputCount());
}
}
but i received the following error:
Phidget21 - Version 2.1.8 - Built Feb 22 2016 11:45:54
waiting for RFID attachment...
Exception in thread "main" PhidgetException 13 (Given timeout has been exceeded.)
at com.phidgets.Phidget.waitForAttachment(Native Method)
at RFIDExample.main(RFIDExample.java:58)
What i have alredy tried, is to increase timer but problem didn't solve.
I tried to use the manufacturer's application for my RFID chip and it worked, it detcted tags properly. But i need to use source code and not the ready application.
Any help would be very useful!
Thank you in advance! :)
BR,
Loukas
Finally, the problem was that i was trying to execute the code and i had the ready application open at the same time.
Now it works properly.
Problem solved.
I'm doing some text mining application. It consists of TextRazor API Java Swing. How can I use JButton to run main() class? Once the button is clicked, the code in main() class must be triggered. Below is the code, please help me.
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
//I want the main class to be called here**
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, "Completed Analysis!","Alert", 1);
jButton5.setEnabled(false);
jTextArea2.setEditable(false);
jTextArea3.setEditable(false);
}
/**
* #param args
* #throws NetworkException
*/
public static void main(String[] args) throws NetworkException, AnalysisException {
// Sample request, showcasing a couple of TextRazor features
String API_KEY = "7d5066bec76cb47f4eb4e557c60e9b979f9a748aacbdc5a44ef9375a";
TextRazor client = new TextRazor(API_KEY);
client.addExtractor("words");
client.addExtractor("entities");
client.addExtractor("entailments");
client.addExtractor("senses");
client.addExtractor("entity_companies");
String rules = "entity_companies(CompanyEntity) :- entity_type(CompanyEntity, 'Company').";
client.setRules(rules);
AnalyzedText response = client.analyze("Barclays misled shareholders and the public RBS about one of the biggest investments in the bank's history, a BBC Panorama investigation has found.");
for (Sentence sentence : response.getResponse().getSentences()) {
for (Word word : sentence.getWords()) {
System.out.println("----------------");
System.out.println("Word: " + word.getLemma());
for (Entity entity : word.getEntities()) {
System.out.println("Matched Entity: " + entity.getEntityId());
}
for (Sense sense: word.getSenses()) {
System.out.println("Word sense: " + sense.getSynset() + " has score: " + sense.getScore());
}
}
}
// Use a custom rule to match 'Company' type entities
for (Custom custom : response.getResponse().getCustomAnnotations()) {
for (Custom.BoundVariable variable : custom.getContents()) {
if (null != variable.getEntityValue()) {
for (Entity entity : variable.getEntityValue()) {
System.out.println("Variable: " + variable.getKey() + " Value:" + entity.getEntityId());
}
}
}
}
}
Main method in Class is also a normal method, which is designed to start the java application by JVM. But, you can also call it in your method
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, "Completed Analysis!","Alert", 1);
jButton5.setEnabled(false);
jTextArea2.setEditable(false);
jTextArea3.setEditable(false);
ClassName.main(new String[]{"arg1","arg2"});
}
added dummy arguments to just invoke the main method
Follow the path of eventList please. While it stores the proper objects as it's supposed to initially, it empties itself as soon as it enters MouseClicked(). There is a driver used to run initialize() in another class. I just can't seem to get eventList to hold its information.
public class Adventure_Chapter1 implements MouseListener
{
boolean success = true;
ArrayList<StoryEvent> eventList = new ArrayList<StoryEvent>();
public void initiliaze() throws FontFormatException, IOException
{
load(); // loads StoryEvents
play(0);
System.out.println("Init() eventList size: " + eventList.size());
}
private void load()
{
int x = 0;
switch(x)
{
case 0:
StoryEvent txt0 = new StoryEvent(parameters);
eventList.add(txt0);
case 1:
StoryEvent assassinStart = new StoryEvent(parameters);
eventList.add(assassinStart);
}
}
public void updatePlayer()
{
System.out.println("Player Updated ");
}
public void play(int c) // to be implemented
{
storyLineDisplay.setText("testing");
System.out.println("Play() eventList size:" + eventList.size());
//int c would typically change my buttons' options next to them. but for now it
is irrelevant.
}
public void mouseClicked(MouseEvent e)
{
if (e.getSource().equals(buttonOne));
{
if (success == true)
{
updatePlayer();
System.out.println("MouseClicked eventList size: " + eventList.size());
play(1);
}
else
{
updatePlayer();
currentCharacter.add(eventList.get(choice));
choice = currentCharacter.get(currentCharacter.size() -1).getFail1();
play(1);
}
}
}
Output is here:
Play() eventList size:2
Init() eventList size: 2
Player Updated
MouseClicked eventList size: 0
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.RangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at Adventure_Chapter1.mouseClicked(Adventure_Chapter1.java:277)
insert further lines of errors here.
You should break your switch statements.
if (success == true)
can be replaced by
if (success)
if (e.getSource().equals(buttonOne));
must be replaced by
if (e.getSource().equals(buttonOne))
put all of the involved code if you want help with debugging, we are not mind readers and guessers. Obviously there are missing code.
Edited
Can we see the code for StoryEvent. Are you touching the evenList list there
? Otherwise I don't understand how you get two elements in your
evenList, to begin with.
public void mouseClicked(MouseEvent e)
{
if (e.getSource().equals(buttonOne));
{
if (success == true)
{
updatePlayer();
System.out.println("MouseClicked eventList size: " + eventList.size());
play(choice);
}
else
{
updatePlayer();
currentCharacter.add(eventList.get(choice));
choice = currentCharacter.get(currentCharacter.size() -1).getFail1();
}
}
}
but what is "choice" ?
I have a program that simulates Gates to a ship. They run in threads. The idea is to let them run and pause during a random moment in the run method to simulate persons passing. This is done by all threads, meanwhile the main thread is waiting for notification and checking if the ship is getting full when notified by the threads that they added a person passing through the gate the main thread checks again if the ship is full. The program has three classes:
A counter:
public class Counter {
private int currentValue[];
private int maxValue;
public Counter(int[] nrOfPeople, int max) {
currentValue = nrOfPeople;
currentValue[0] = 0;
maxValue = max;
}
public synchronized void addPersons(int nr_p) {
currentValue[0] += nr_p;
}
public synchronized int getValue() {
return currentValue[0];
}
public synchronized boolean isFull() {
if(currentValue[0] < maxValue)
return false;
return true;
}
}
A Gate Class:
public abstract class Gate implements Runnable {
int nrOfPassengers;
int gatenr;
int gatesize;
Counter c;
private Thread t;
private Random r;
private boolean blocked; /* suspends people from passing */
public Gate(Counter c, int nr) {
this.c = c;
gatenr = nr;
this.open();
r = new Random();
t = new Thread(this);
t.start();
}
public void setGatesize(int size) {
gatesize = size;
}
public void close() {
blocked = true;
}
public void open() {
blocked = false;
}
public int getNoOfPassangers() {
return nrOfPassengers;
}
public int getId() {
return gatenr;
}
#Override
public void run() {
while(!blocked) {
int waitTime = (r.nextInt(5) + 1) * 1000; /* between 1-5 seconds */
System.out.println("Person-Gate " + gatenr + ": adding one to " + c.getValue());
try {
/* bigger throughput => amount can vary */
if(gatesize > 1) {
int persons = r.nextInt(gatesize)+1;
c.addPersons(persons);
nrOfPassengers += persons;
} else {
c.addPersons(1);
nrOfPassengers++;
}
Thread.sleep(waitTime);
} catch (InterruptedException e) {
System.out.println("Person-Gate " + gatenr + ": was interrupted adding person");
e.printStackTrace();
}
System.out.println("Person-Gate " + gatenr + ": added one to " + c.getValue());
t.notify();
}
}
public void join() {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
And a Simulator that runs the main method:
/*
* This class simulates cars and persons- entering a ferry.
*/
public class Simulator {
public static final int MAX = 30;
public static void main(String[] args) {
int nrOfPeople[] = new int[1]; /* array of size one for keeping count */
ArrayList<Gate> gates = new ArrayList<Gate>();
Counter counter = new Counter(nrOfPeople, MAX);
Thread mainThread = Thread.currentThread();
/* adding 3 person-gates */
for(int i=1; i<4; i++) {
gates.add(new PersonGate(counter, i));
}
/* let all gates work as long as passengers is under MAX */
while(!counter.isFull()) {
try {
mainThread.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Announcement: Ship is full!");
/* wait for child threads to finish */
for(Gate g: gates) {
g.close();
try {
g.join();
} catch (Exception e) { /* InterruptedException */
e.printStackTrace();
}
System.out.println(g.getNoOfPassangers() + " passed through gate nr " + g.getId());
System.out.println(counter.getValue() + " has passed in total");
}
}
}
Im getting a error
Person-Gate 1: adding one to 0
Person-Gate 2: adding one to 1
Person-Gate 3: adding one to 2
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at Simulator.main(Simulator.java:24)
Person-Gate 3: added one to 3Exception in thread "Thread-3"
Does anyone now whats going on?
You can only call wait and notify/notifyAll from within synchronized blocks.
t.notify();
You are notifying wrong monitor. This exception occurs, when you do not wrap monitor object with synchronize section. However, objects which you are using for notify and for wait methods are different. Create new Object() monitor and pass it to the constructor of Gate.
Also you can take a look at CountDownLatch, it does exactly what you are trying to achieve.
You must own the monitor of the object on which you call wait or notify. Meaning, you must be in a synchonize-Block, like
synchronized( objectUsedAsSynchronizer) {
while ( mustStillWait) {
objectUsedAsSynchronizer.wait();
}
}
This has been the subject of many other questions.