Java - Using TryCatch outside a method - java

import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Images {
try {
public static Image button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}
This just gives an error, I want to be able to store some images in static variables and access them from another class without instantiating it.
I could possibly make a method to initialise all them and set values to them, but then the variables wouldn't be static.
The reason I need TryCatch is because the constructor of the Image class throws a SlickException

Two options:
Use a static initializer block
public static final Image button;
static {
try/catch in here, assign to button
}
Use a method for initialization
public static final Image button = createButton();
private static Image createButton() {
try/catch in here
}
Personally I'm somewhat skeptical of this being a good idea though - making type initialization do "real work" can lead to bugs which are hard to track down. Is all the referring code really set up for it to be null in the case of problems?

You can put your exception handling code in a static block.
public static Image button;
static {
try {
button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}

Just declare the static variable outside the block..and it will work..
public static final Image button = setImageButt();
public static Image setImageButt(){
try {
button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}

try to place it into a static block
public static Image button;
static{
try {
button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}

You should use static constructor.
public class Images {
public static Image button;
static{
try {
button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}
}

Use a static block for initialization and take extra care to not swallow the exception:
public class Images {
public final static Image BUTTON;
static {
Image i;
try {
i = new Image("images/buttons/0/Button.png");
} catch (SlickException e) {
throw new ExceptionInInitializerError(e);
}
BUTTON = i;
}
}
I corrected some things from your code:
Creating the image in initializer implies it should be a constant, thus final.
Constants should have uppercase names, thus BUTTON.
Exceptions during initialization should not be swallowed but properly indicated. Otherwise you can spend hours debugging the image not being found because there will be no indication initialization failed. ExceptionInInitializerError is the standard exception to throw in that case.
There are other solutions, but this is the cleanest IMO.

I have faced similar problem once and while for finding the solution I just came across to this question. I have solved similar problem just putting all of the code in the default constructor.
Your solution code will be like this:
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Images {
public Images{
try {
public static Image button = new Image("images/buttons/0/Button.png");
} catch(SlickException e) {
e.printStackTrace();
}
}
}

Related

Java Robot doesnt Press Enter Key how it should

Im trying to program a litte Robot, that should just write for some hours the same phrase with a delay.
But somehow, if i have mor than 1 Letter at the same time before the Enter Key, it rather types a Pyramide.
For Example, if i wanna print "ted", it prints the following:
ted
tedted
tedtedted
tedtedtedted
[...]
(There is no empty line between the Pyramide-Lines)
It gets really frustrating.
I Tried many solutions, but none worked. Making a Delay for the robot, an extra Robot for the Enter Key, put it in an extra Thread or creating new Robots every time before a new Typing. It just doesnt work. What am i doing wrong?
Here is a SSCCE with some trys i did:
#SuppressWarnings("CallToPrintStackTrace")
public class RobotTest {
private static Robot robo;
private static Robot okRobo;
static {
createRobos();
}
private static void createRobos(){
try {
robo = new Robot();
okRobo = new Robot();
} catch (AWTException ex) {
ex.printStackTrace();
}
}
#SuppressWarnings({"CallToPrintStackTrace", "SleepWhileInLoop"})
public static void main(String[] args) throws InterruptedException {
Thread.sleep(5000);
for (int i = 0; i < 16; i++) {
createRobos();
perform();
// Thread.sleep(500);
performOk();
}
}
private static void perform() {
robo.keyPress(KeyEvent.VK_SHIFT);
robo.keyPress(KeyEvent.VK_1);
robo.keyRelease(KeyEvent.VK_SHIFT);
robo.keyRelease(KeyEvent.VK_1);
robo.keyPress(KeyEvent.VK_B);
robo.keyRelease(KeyEvent.VK_B);
robo.keyPress(KeyEvent.VK_O);
robo.keyRelease(KeyEvent.VK_O);
robo.keyPress(KeyEvent.VK_O);
robo.keyRelease(KeyEvent.VK_O);
robo.keyPress(KeyEvent.VK_S);
robo.keyRelease(KeyEvent.VK_S);
robo.keyPress(KeyEvent.VK_T);
robo.keyRelease(KeyEvent.VK_T);
robo.keyPress(KeyEvent.VK_E);
robo.keyRelease(KeyEvent.VK_E);
robo.keyPress(KeyEvent.VK_D);
robo.keyRelease(KeyEvent.VK_D);
// robo.waitForIdle();
}
private static void performOk() {
okRobo.keyPress(KeyEvent.VK_ENTER);
okRobo.keyRelease(KeyEvent.VK_ENTER);
// okRobo.waitForIdle();
}
}
And here is my first try, that should work in my opinion too, but it doesnt:
public class RobotTest {
private static Robot robo;
#SuppressWarnings("CallToPrintStackTrace")
static {
try {
robo = new Robot();
} catch (AWTException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
Thread.sleep(5000);
for (int i = 0; i < 16; i++) {
perform();
}
}
private static void perform() {
robo.keyPress(KeyEvent.VK_SHIFT);
robo.keyPress(KeyEvent.VK_1);
robo.keyRelease(KeyEvent.VK_SHIFT);
robo.keyRelease(KeyEvent.VK_1);
robo.keyPress(KeyEvent.VK_B);
robo.keyRelease(KeyEvent.VK_B);
robo.keyPress(KeyEvent.VK_O);
robo.keyRelease(KeyEvent.VK_O);
robo.keyPress(KeyEvent.VK_O);
robo.keyRelease(KeyEvent.VK_O);
robo.keyPress(KeyEvent.VK_S);
robo.keyRelease(KeyEvent.VK_S);
robo.keyPress(KeyEvent.VK_T);
robo.keyRelease(KeyEvent.VK_T);
robo.keyPress(KeyEvent.VK_E);
robo.keyRelease(KeyEvent.VK_E);
robo.keyPress(KeyEvent.VK_D);
robo.keyRelease(KeyEvent.VK_D);
robo.keyPress(KeyEvent.VK_ENTER);
robo.keyRelease(KeyEvent.VK_ENTER);
robo.delay(500);
}
Try not to initialize your Robot at each iteration of the loop. Call createRobos() outside of the loop. That is unless you have a specific reason that you're doing it that way.
I don't think you need two separate instances of Robot to get this to work.
Instead of using Thread.sleep(), you can use the delay() method within the Robot class. This is if you want to add a delay between Robot method calls.
You may want to try to add a delay between when you're typing out the letter keys and when you're pressing the enter key and after you press the enter key. A 50 - 100 ms delay will usually do the trick. Sometimes, things get a little messed up, especially when you throw Thread.sleep() into the mix.
I ran your code with these small changes and it seemed to work fine.

"A connector with id is already registered! " in vaadin

I would like to fix the issue which is solved in this posting:
Vaadin "A connector with id xy is already registered"
When I add the following code to MyUI I get an error in the getLogger() lline: "The method getLogger() from the type ConnectorTracker is not visible"
public class SomeUI extends UI {
private ConnectorTracker tracker;
#
Override
public ConnectorTracker getConnectorTracker() {
if (this.tracker == null) {
this.tracker = new ConnectorTracker(this) {
#
Override
public void registerConnector(ClientConnector connector) {
try {
super.registerConnector(connector);
} catch (RuntimeException e) {
getLogger().log(Level.SEVERE, "Failed connector: {0}", connector.getClass().getSimpleName());
throw e;
}
}
};
}
return tracker;
}
}
Is there a quick work around for this or any other solution how to fix the xy connector exception?
I am using spring boot with vaadin 7.
The getLogger() method is private, and you are implementing an anonymous subtype, which can only access public and protected methods. You can easily add your own getLogger to your UI subclass:
private static Logger getLogger() {
return Logger.getLogger(SomeUI.class.getName());
}
private ConnectorTracker connectorTracker;
#Override
public ConnectorTracker getConnectorTracker() {
if (connectorTracker == null) {
connectorTracker = new ConnectorTracker(this) {
#Override
public void registerConnector(ClientConnector connector) {
try{
super.registerConnector(connector);
} catch (RuntimeException e) {
getLogger().log(Level.SEVERE, "OOPS!");
throw e;
}
}
};
}
return connectorTracker;
}
To fix the a connector xy is already registered problem you need to check if any of your Components(Views, Layouts, Buttons, Panels, whatever...) are added to a view more than once.
So if a Layout is created with new VerticalLayout() there is no way to reuse it.
Meaning you should check all your Vaadin components and your own Views/UI-Components if they are used twice or if some of them are static.

Using reflection to customize private field of superclass

I am running into a problem trying to modify the behavior of my superclass' private fields from the sub-class (The superclass wasn't designed to be extended and I can't change that).
Basically, what I have is :
public class OrthoCanvas {
private OrthoView xy, xz, zy;
public class OrthoView { ... }
}
And I want to do something like that :
public class CustomOrthoCanvas extends OrthoCanvas {
public CustomOrthoCanvas {
// Sets superclass xy, xz, zy to instances of CustomOrthoView
// This seem to work fine (I'm using reflection to change the fields)
}
public class CustomOrthoView extends OrthoView { ... }
}
As I said, the reflection seems to work (I'm building CustomOrthoView). But, for the moment, I didn't override any method, and my constructor is just super(whatever), and a Sysout to check what I'm doing. Yet, the original behavior of OrthoView just disappeared, and nothing is working.
Did I make a mistake in my code or is this something more related to my specific case ?
Thanks a lot
Edit : I've just thought that it would be easier if I showed you how I used reflection, so there it is :
Field fieldXY = null;
Field fieldXZ = null;
Field fieldZY = null;
try {
System.out.println(this.getClass().getSuperclass().getName());
fieldXY = Class.forName(this.getClass().getSuperclass().getName()).getDeclaredField("xy");
fieldXZ = Class.forName(this.getClass().getSuperclass().getName()).getDeclaredField("xz");
fieldZY = Class.forName(this.getClass().getSuperclass().getName()).getDeclaredField("zy");
} catch (NoSuchFieldException e) {
System.out.println("-- No such field --");
System.out.println(e.getMessage());
} catch (SecurityException e) {
System.out.println("-- Security failure --");
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("-- Class not found --");
System.out.println(e.getMessage());
}
fieldXY.setAccessible(true);
fieldXZ.setAccessible(true);
fieldZY.setAccessible(true);
try {
fieldXY.set(this, new CustomOrthoView(this, DimensionId.Z));
fieldXZ.set(this, new CustomOrthoView(this, DimensionId.Y));
fieldZY.set(this, new CustomOrthoView(this, DimensionId.X));
} catch (IllegalArgumentException e) {
System.out.println("-- Illegal argument --");
System.out.println(e.getMessage());
} catch (IllegalAccessException e) {
System.out.println("-- Illegal access --");
System.out.println(e.getMessage());
}
Edit2 : This is a simplified behavior of the superclass :
public class Orthoviewer {
// This class creates a canvas to display an image
public class OrthoCanvas {
// This class represents how an image is displayed
// It implements listeners (to navigate through the image for
// example), and ways to refresh the image
public class OrthoView extends JPanel {
// This class displays one part of the image (one plane)
// To represent a 3D point by the intersection of the three corresponding planes
// It has an attribute which indicates its dimension
// (X is for ZY plane, Y for XZ plane etc)
// It overrides the method paintComponent to draw itself
public class ImageCache implements Runnable {
// This handles the image to display on the corresponding plane
}
}
}
}

Basic layout/structure of a Java Applet

I have a very simple Java applet that just works.
import java.sql.*;
import org.apache.commons.lang3.*;
public class doQuery {
public static void main (String[] args) {
...
try {
...
} catch (Exception e) {
...
}
try {
...
try {
...
} catch (SQLException e) {
...
} finally {
...
}
} catch (SQLException e) {
...
}
}
}
It allows me to open a database, do some queries, and perform a series of outputs that is captured through stdio of a bash script, connections closed and then bash script emails the output.
However, I am looking to expand it, and I am stuck. I am programmer, just not a Java programmer. What I have come up with is something I hacked together. I want to add some functions, and more. I have tried to the function definitions in different places in the code, but it always generates compilation errors.
Can anyone provide some insight as to what I can change to enable me to add some functions? Generally programming say define the function before you attempt to use it, but I probably am not using the right keywords or something.
I can not figure out where to place a simple function like:
function display_number(number) {
return number + "";
}
in the source code that I can call and have it compile! :(
import java.sql.*;
import org.apache.commons.lang3.*;
public class doQuery {
public static void main (String[] args) {
...
try {
...
} catch (Exception e) {
...
}
try {
...
try {
...
} catch (SQLException e) {
...
} finally {
...
}
} catch (SQLException e) {
...
}
displayNumber(4); // Replace 4 with a variable to output or what not
}
private int displayNumber(int number) {
return number;
}
}
In Java you'll add your methods inside the scope of the class like so, when you want to use them call them inside of another function like in the example above. I'd recommend reading this link, it should give you a good understanding of how methods work, how to call them, etc.
If you just want a quick and easy function, here is a layout you can use.
public void display_number(int number) {
System.out.print(number);
}
Or if you prefer returning the number to use it somewhere else...
public int display_number() {
return number;
}
Your methods can be basically anywhere between the start { and the end } of your class, assuming you do not place it inside another method (such as the main method from your code). As far as anything else I recommend reading up on the subject, I am sure a google search will give you millions of examples of method calls.

How can I pass a variable to an inner thread class?

I want to load an image at periodic intervals to an imageitem. My outer class is generating the URL and I need to pass it to the innerclass. How do I achieve this?
public class MapTimer extends TimerTask{
public void run() {
System.out.println("Map starting...");
String URL=null,serverquery=null;
try {
sendMessage(this.message);
item.setLabel(item.getLabel()+"start");
serverquery=receiveMessage();
item.setLabel(item.getLabel()+"stop");
URL = getURL(serverquery); // my url to be passed to innerclass
System.out.println("URl is "+serverquery);
item.setLabel(URL+item.getLabel());
Thread t = new Thread() {
public void run() {
item.setLabel(item.getLabel()+"6");
try {
Image image = loadImage(URL); // using url
System.out.println("GEtting image....");
item = new ImageItem(null, image, 0, null);
form.append(item);
display.setCurrent(form);
} catch (IOException ioe) {
item.setLabel("Error1");
}
catch (Exception ioe) {
item.setLabel("Error1");
}
}
};
t.start(); // write post-action user code here
}
catch(Exception e){
System.out.println("Error3"+e);
}
}
}
How do I pass the URL to my innerthread class?
You have to declare the variable final or don't use a variable but a field in the class.
public class YourClass {
private String url;
public void yourMethod {
url = getURL(serverquery);
System.out.println("URl is "+serverquery);
item.setLabel(URL+item.getLabel());
Thread t = new Thread() {
public void run() {
item.setLabel(item.getLabel()+"6");
try {
Image image = loadImage(url); // using url
System.out.println("GEtting image....");
item = new ImageItem(null, image, 0, null);
form.append(item);
display.setCurrent(form);
} catch (IOException ioe) {
item.setLabel("Error1");
}
catch (Exception ioe) {
item.setLabel("Error1");
}
}
};
t.start(); // write post-action user code here
}
}
It should work if your URL is contained in a final reference. This means that the reference won't move. Consequently, you can't initialize it to null and then call getURL, you need to declare it at this point:
final String URL = getURL(serverquery);
I found that there are (at least) 2 major ways of doing this on whever your thread gets the information or recieves the information (in your case URL)
1) gets the informations:
what you want to do is keep a reference of the object containing the data you need (like URL) in your Thread, and when your ready the Thread gets the next item/URL to load.
public class MapTimer extends TimerTask{
public void run() {
...
}
private URLGenerator urlGenerator = null;
public MapTimer(URLGenerator urlGen){
...
}
This will give you the option to get the next URL when your thread is free (with a if(urlGen != null) of course)
2) Receives Information
Works better for cases where the thread is called only when the rest of the program wants to (user inputing data etc)
public class MapTimer extends TimerTask{
public void run() {
...
}
private URL urlToLoad = null;
public void setURL(URL urlToLoad){
...
//store and wake up thread
}
this way your thread recieve with a setter the data it needs to run, processes it then waits for the next data to be send to it (of course you need to be careful of thread issues like multiple calls etc.)
Hope this helps you
Jason
Just make the field a static variable belonging to the class and not any object instance of the class, like this:
public YourClass {
private static String url;
//...
}
Please note however that the static variable will be shared among all object instances of the class.

Categories

Resources