Multi-Catches Problems - java

I copied something from a different class, and yet it gave me an error even though it didn't in the original. Here's the code:
package com.dinobuilding;
import java.awt.EventQueue;
import java.awt.FontFormatException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.ImageObserver;
import java.io.IOException;
import javax.swing.*;
public class Window {
public static int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
public static int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
public static ImageIcon background = new ImageIcon("resources/images/Background.png");
public static ImageObserver observer;
public Window() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("DinoBuilding");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setSize(screenWidth, screenHeight);
frame.setVisible(true);
}
});
}
public static void main(String[] args) {
new Window();
}
}
I've probably messed something up really trivial, but it will not stop telling me "Multi-catches are not supported at this language level". If you need more information that I probably forgot to mention, just ask. Thanks in advance!

Multi catch statements are only supported in Java 7 and higher versions, make sure that you are not running a version below that.
Check this out to see how you can change the Project language level in IDEA. I am assuming that you have Java 7 or a version higher installed on your system, if you don't then go and get the latest version of Java

Multi-catches like catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) are only supported from Java 7 and onwards. I believe your JDK/Java compliter is earlier than JDK1.7.
http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Please check that. If possible, upgrade to JDK 1.7. Else use the catch block as following...
try {
// Do something
} catch (ClassNotFoundException ex) {
// Do something
} catch(InstantiationException ex) {
// Do something
} catch(IllegalAccessException ex) {
// Do something
} catch(UnsupportedLookAndFeelException ex) {
// Do something
}
Cheers!

Related

Loading assets in libgdx for JUnit tests

I am currently developing a game using libgdx and java. I am wanting to run some JUnit tests on some of the features of my game, however I am having difficulties loading in my assets. I have tried to implement Mockito so that I can make headless JUnit tests to see if this helped solved the problem but this has not helped. Here is the test class that I am trying to load an asset in (the asset is being loaded on line 17)
import com.kroy.game.FireEngine;
import com.kroy.game.Fortress;
import com.kroy.game.Tile;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
#RunWith(GdxTestRunner.class)
public class FireEngineTests {
Tile testTile = new Tile();
FireEngine testFireEngine = new FireEngine(100, 10, 10, testTile, 10, 100, "fireEngineSprite.png");
Class ReflectionClass = FireEngine.class;
#Test
public void testRefillAmount() {
testFireEngine.refillAmount(50);
assertEquals(50, testFireEngine.getWaterAmount());
testFireEngine.refillAmount(5000);
assertEquals(100, testFireEngine.getWaterAmount());
}
#Test
public void testCanShoot() {
}
#Test
public void testDeath() {
testFireEngine.setHealth(0);
assertTrue(testFireEngine.isDisabled());
}
#Test
public void testTakeDamage() {
try {
testFireEngine.setHealth(100);
Method takeDamageReflection = ReflectionClass.getDeclaredMethod("takeDamage");
takeDamageReflection.setAccessible(true);
takeDamageReflection.invoke(50, takeDamageReflection);
assertEquals(50, testFireEngine.getHealth());
takeDamageReflection.invoke(5000, takeDamageReflection);
assertEquals(0, testFireEngine.getHealth());
} catch (NoSuchMethodException e) {
} catch (InvocationTargetException e) {
} catch (IllegalAccessException e) {
}
}
#Test
public void testTransferTo() {
Tile newLocation = new Tile(2,2);
try {
Method transferToReflection = ReflectionClass.getDeclaredMethod("transferTo");
transferToReflection.setAccessible(true);
transferToReflection.invoke(newLocation, transferToReflection);
assertEquals(testTile.getInhabitant(),null);
assertEquals(newLocation.getInhabitant(), testFireEngine);
} catch (NoSuchMethodException e) {
} catch (InvocationTargetException e) {
} catch (IllegalAccessException e) {
}
}
#Test
public void testShootTarget() {
Fortress testFortress = new Fortress(1000, 10,2,testTile, "fortress1", "lavaTile.png");
testFireEngine.shootTarget(testFortress);
assertEquals(testFortress.getHealth(), (testFortress.getMaxHealth() - testFireEngine.getDamage()));
assertEquals(99, testFireEngine.getWaterAmount());
}
}
Here is the error message that I get for each of the tests that I try to run:
com.badlogic.gdx.utils.GdxRuntimeException: Asset not loaded: /Users/michaelShepherd/Documents/University Work/Year 2/SEPR/Assessment 3/Septagon3/tests/assets/fireEngineSprite.png
The searched for file is definitely in that location specified and I have also made the assets folder the resouces root for this module, yet still the file does not load.
Any suggestions?
I am not sure how you work with textures in FireEngine class but you probably need to load and access textures through AssetManager as you usually do in game.

error trying to attach to virtual machine

I'm trying to attach to a running JVM to debug it using the Virtual Machine class in java. I'm currently have java 8, with jdk1.8.0_11. I have tried to add a manifest to it, with but to no avail. I'm also importing the tools.jar file from my JDK\libs folder.
My code:
import java.io.IOException;
import java.util.List;
import com.sun.tools.attach.AgentInitializationException;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
public class loadVM {
public static void main(String[] args) {
String name = "replaceAfterNameFound";
List <VirtualMachineDescriptor> vms = VirtualMachine.list();
for (VirtualMachineDescriptor vmd: vms) {
System.out.println(vmd.displayName());
if (vmd.displayName().equals(name)) {
try {
VirtualMachine vm = VirtualMachine.attach(vmd.id());
String agent = "";
vm.loadAgent(agent);
} catch(AttachNotSupportedException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(AgentLoadException e) {
e.printStackTrace();
} catch(AgentInitializationException e) {
e.printStackTrace();
}
}
}
}
}
Here is a copy of the error I get when running it:
java.util.ServiceConfigurationError:com.sun.tools.attach.spi.AttachProvider:
Provider sun.tools.attach.WindowsAttachProvider could not be
instantiated
Thank you guys for all your help!

altgr doesn't work with jnativehook?

It's just for testing purposes.
I tried to change some parts of the code and read also the api-docs.
On begin I added "typedC += e.getKeyChar();" and it looked like to log the altgr-keys, but later not anymore.
How to change it to let work altgr-keys ?
Thanks
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class JkL implements NativeKeyListener {
private String typedC = "";
private String typedC1 = "";
private final JFileChooser fc = new JFileChooser();
private File direc;
private void openFchooser1() throws FileNotFoundException,
InterruptedException, IOException, Exception {
Thread.sleep(2000);
int returnVal = fc.showDialog(null, "Choose a Logfile");
if(returnVal == JFileChooser.APPROVE_OPTION) {
direc = fc.getSelectedFile();
}
/* Construct the example object and initialze native hook. */
GlobalScreen.addNativeKeyListener(new Kl());
try {
/* Register jNativeHook */
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
/* Its error */
System.err.println("There was a problem registering the native
hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
// Clear previous logging configurations.
LogManager.getLogManager().reset();
// Get the logger for "org.jnativehook" and set the level to off.
Logger logger =
Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.OFF);
}
#Override
public void nativeKeyPressed(NativeKeyEvent nke) {
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
#Override
public void nativeKeyReleased(NativeKeyEvent nke) {
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
#Override
public void nativeKeyTyped(NativeKeyEvent nke) {
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
class Kl extends JkL {
/* Key Pressed */
#Override
public void nativeKeyPressed(NativeKeyEvent e) {
//typedC += NativeKeyEvent.getKeyText(e.getKeyCode());
typedC += e.getRawCode();
typedC += e.getKeyChar();
typedC += e.getKeyCode();
try {
writeToFile(typedC);
} catch (IOException ex) {
Logger.getLogger(JkL.class.getName()).log(Level.SEVERE, null,
ex);
}
/* Terminate program when one press ESCAPE */
if (e.getKeyCode() == NativeKeyEvent.VC_F12) {
try {
GlobalScreen.unregisterNativeHook();
} catch (NativeHookException ex) {
Logger.getLogger(JkL.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
#Override
public void nativeKeyReleased(NativeKeyEvent e) {
//System.out.println("Key Released: " +
//NativeKeyEvent.getKeyText(e.getKeyCode()));
}
/* I can't find any output from this call */
#Override
public void nativeKeyTyped(NativeKeyEvent e) {
//typedC1 += NativeKeyEvent.getKeyText(e.getKeyCode());
typedC1 += e.getRawCode();
typedC1 += e.getKeyChar();
typedC1 += e.getKeyCode();
try {
writeToFile(typedC1);
} catch (IOException ex) {
Logger.getLogger(JkL.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}
private void writeToFile(String ln) throws IOException {
//System.out.println(direc);
FileWriter fw = new FileWriter(direc);
try (BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(ln);
bw.newLine();
bw.flush();
}
}
public static void main(String[] args) throws
IOException,InterruptedException, Exception {
new JkL().openFchooser1();
}
}
What operating system? There are some known issues with 2.0 on Linux but they will be fixed in 2.1. If there are any other issues, you will probably need to report a bug. Please include your exact keyboard layout, model and language. Also provided detailed information about what key is pressed, the observed behavior and the expected behavior. I only know how to use a US keyboard, so I am not sure how all of the Alt-Gr language/region specific keys, masks and locks are suppose to work.

Java clipboard as stack in paste override

I have done my research, no useful results found.
Here is the deal, I'm writing a 'new' clipboard that works like a stack instead of a 'area'. And I'm brave or stupid enoght to do that in Java. So far in my tests to see if this is possible I have managed to create this stack behavior. The only problem I'm getting is that sometimes, mainly when I paste the top of the stack (pop operation), it doesn't pop or for some other reason it pastes twice.
Example:
If i copy this three words: Carlos, Lucas, Eastwood
The stack clipboard behaves like this at paste: Eastwood, Eastwood, Lucas, Carlos
I'm using JNativeHooks for reading the system keypresses and determining when the user is pasting.
I think what is happening is that the system is pasting before my code... Well, here is the code anyway (It is a test, that explains why it is badly commented):
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.Transferable;
import java.util.Stack;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.NativeInputEvent;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class Test3 implements NativeKeyListener {
Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
Stack<Transferable> clipStack = new Stack<>();
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err
.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
Test2 t2 = new Test2();
// Construct the example object and initialze native hook.
GlobalScreen.getInstance().addNativeKeyListener(t2);
}
#Override
public void nativeKeyPressed(NativeKeyEvent ev) {
// Copy
if (ev.getKeyCode() == NativeKeyEvent.VK_C
&& NativeInputEvent.getModifiersText(ev.getModifiers()).equals(
"Ctrl")) {
// Clip the pop
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
clipStack.push(sysClip.getContents(null));
System.out.println("Ctrl+C : Stack(" + clipStack.size() + ")");
}
// Paste
if (ev.getKeyCode() == NativeKeyEvent.VK_V
&& NativeInputEvent.getModifiersText(ev.getModifiers()).equals(
"Ctrl")) {
// Clip the pop
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (clipStack.size() > 1) {
sysClip.setContents(clipStack.pop(), null);
} else
sysClip.setContents(clipStack.peek(), null);
System.out.println("Ctrl+V : Stack(" + clipStack.size() + ")");
}
}
#Override
public void nativeKeyReleased(NativeKeyEvent e) {
}
#Override
public void nativeKeyTyped(NativeKeyEvent e) {
}
}
I would think the same as you suggested.
Have a copy and paste key combination something different from ctrl+c and ctrl+v and you can even bypass using the system clipboard. Simply push the selected text and pop the text directly to your text pointer in your application provided of course that you are using this stack behavior for only a particular application.
The system retains it's own copy of latest clip and it gets a duplicate from your sysClip.setContents(clipStack.pop(), null) on paste operation.
I don't have much idea on disabling the system behavior. You can do research on that. But you can always make sure that it's the only problem by changing the key combination.

JOptionPane: Installing Custom icon has no effect when look and feel set

I would like to install a custom icon in place of the standard JOptionPane information icon..
I tried
ImageIcon myCustomIcon = ...;
UIManager.put("OptionPane.informationIcon", myCustomIcon);
However, apparently this has no effect due to the following line:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Commenting out this line gives the correct behaviour. I have of course tried putting the icon into the UIManager both before/after the look and feel is being set.
Can I somehow combine the two to override the information icon globally?
I am working on Ubuntu 10.04 right now..
Regards,
Morten
Works fine for me using the Metal and Windows LAF's.
Maybe your LAF doesn't support the UIManager property. Check out UIManager Defaults for a list of properties.
If you need more help the post your SSCCE that demonstrates the problem.
Have you tried to specify your icon after setting look&feel, in such a way:
JOptionPane.showMessageDialog(frame,
"Eggs are not supposed to be green.",
"Inane custom dialog",
JOptionPane.INFORMATION_MESSAGE,
myCustomIcon);
Update:
The following code works fine on my Windows 7:
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class OptionPaneIcon {
public static void main (String[] args) {
ImageIcon myCustomIcon = loadImageIcon("image.png");
UIManager.put("OptionPane.informationIcon", myCustomIcon);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JOptionPane.showMessageDialog(null, "Hello!");
}
/** Returns an ImageIcon, or null if the path was invalid. */
private static ImageIcon loadImageIcon(String path) {
URL imgURL = OptionPaneIcon.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
P.S. Sorry for my impatience.

Categories