Why am I getting random errors in my Minecraft 1.7.10 mod using eclipse? - minecraft-forge

Sorry, I'm not sure if I'm in the right forum or if I'm wording it right. People may call this vague or something. I won't care.
Anyway, I've started to get random errors after trying something. It didn't turn out well. Here's the code + errors of my main mod file.
package com.harry.MoStuff;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
#Mod(modid = "ms", name = "Mo' Stuff", version = "a-1.0")
public class MoStuff {
public static Item itemRuby;
public static Item itemChain;
public static Item itemRubyEssence;
public static Item itemRubyShard;
public static Item itemRedBull;
public static Block blockRubyOre;
#EventHandler
public void preInit(FMLPreInitializationEvent event) {
//Item/block init and registering
//Config handling
itemRuby = new ItemRuby().setUnlocalizedName("ruby").setTextureName("ms:ruby");
itemChain = new ItemChain().setUnlocalizedName("chain");
blockRubyOre = new BlockRubyOre(Material.rock).setBlockName("ruby_ore").setBlockTextureName("ms:ruby_ore");
itemRubyShard = new ItemRubyShard().setUnlocalizedName("ruby_shard");
itemRubyEssence = new ItemRubyEssence().setUnlocalizedName("ruby_essence");
itemRedBull = new ItemFood(8, 1.0F, true).setUnlocalizedName("red_bull").setTextureName("ms:red_bull");
}
GameRegistry.registerItem(itemRuby, itemRuby.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemChain, itemChain.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemRubyShard, itemRubyShard.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemRubyEssence, itemRubyEssence.getUnlocalizedName().substring(5));
GameRegistry.registerBlock(blockRubyOre, blockRubyOre.getUnlocalizedName().substring(5));
GameRegistry.registerItem(itemRedBull, itemRedBull.getUnlocalizedName().substring(5));
#EventHandler
public void init(FMLInitializationEvent event) {
//Proxy, tile entity, entity, GUI, packet reg.
GameRegistry.addRecipe(new ItemStack(itemRuby), new Object[]{"RRR","RRR","RRR", 'R', itemRubyShard});
GameRegistry.addRecipe(new ItemStack(itemChain), new Object[] {"III","I I","III", 'I', Items.iron_ingot});
GameRegistry.addRecipe(new ItemStack(itemRubyEssence, 5), new Object[]{" "," R "," ", 'R', itemRuby});
}
#EventHandler
public void postInit(FMLPostInitializationEvent event) {
}
}
The errors are:
Multiple markers at this line (38, where GameRegistry.registerItem(itemRuby) and so on):
Syntax error on token ".", > expected.
Syntax error on token "(", < expected.
Syntax error on token ".", { expected.
Syntax error on token ")", delete this token.
Multiple markers at this line (46, where public void init(params) is.)
Syntax error on token "(", ; expected.
Syntax error on token ")", ; expected.
Multiple markers at this line (54, where public void postInit(params) is.)
Syntax error on token "(", ; expected.
Syntax error on token ")", ; expected.
That's all I can say. Thanks in advance.

On line 37, you closed the brace. Close it after all your GameRegistry.register

Related

How to add Microsoft Word content in Email Body from Java Code

I am trying to put content of Microsoft Word Document in Email body from Java Code but getting following error:
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: IOException while sending message;
nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
at co.kush.DemoEmail.main(DemoEmail.java:134)
Caused by: javax.mail.MessagingException: IOException while sending message;
nested exception is:
javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:625)
at co.kush.DemoEmail.main(DemoEmail.java:128)
Caused by: javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/msword
at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:896)
at javax.activation.DataHandler.writeTo(DataHandler.java:317)
at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1350)
Refer my code :
package co.kush;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.CharacterRun;
/**
* #author Kush
*
*/
public class DemoEmail {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties prop = new Properties();
String Filepath = "Email.Properties";
FileInputStream propFile = new FileInputStream(Filepath);
prop.load(propFile);
String timeStamp = new SimpleDateFormat("M/dd # HH:mm:ss").format(Calendar.getInstance().getTime());
// Fetching values from property file
String sender = prop.getProperty("sender");
String recevier = prop.getProperty("recevier");
String password = prop.getProperty("password");
String proxyHost = prop.getProperty("proxyHost");
String proxyPort = prop.getProperty("proxyPort");
String smtpHost = prop.getProperty("smtpHost");
String smtpPort = prop.getProperty("smtpPort");
String attachFilePath = prop.getProperty("attachFilePath");
String mailSubject=prop.getProperty("mailSubject")+" on " + timeStamp;
String mailBody = prop.getProperty("mailBody");
Properties sys_prop = System.getProperties();
// Setting values for sending Email
sys_prop.put("mail.smtp.starttls.enable", "true");
sys_prop.put("mail.transport.protocol", "SMTP");
sys_prop.put("mail.smtp.host", smtpHost);
sys_prop.put("mail.smtp.auth", "true");
sys_prop.put("mail.smtp.port", smtpPort);
sys_prop.put("mail.smtp.debug", "true");
sys_prop.put("mail.smtp.socketFactory.port", smtpPort);
sys_prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
sys_prop.put("mail.smtp.socketFactory.fallback", "false");
sys_prop.put("proxySet", "true");
sys_prop.put("proxyPort", proxyPort);
sys_prop.put("socksProxyHost", proxyHost);
sys_prop.put("proxyHost", proxyHost);
Session session = Session.getDefaultInstance(sys_prop, null);
try {
//Adding Sender/Receiver address and Subject Line
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(sender));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recevier));
msg.setSubject(mailSubject);
MimeBodyPart messageBodyPart=new MimeBodyPart();
Multipart multipart = new MimeMultipart();
//Reading Word Document
HWPFDocument doc = new HWPFDocument(new FileInputStream("<AbsolutePathWordDoc\\<WordDocFile>.doc"));
WordExtractor we = new WordExtractor(doc);
String[] paragraphs = we.getParagraphText();
for (String para : paragraphs) {
//Putting word document to email Body
messageBodyPart.setContent(paragraphs, "application/msword");
multipart.addBodyPart(messageBodyPart);
}
//Adding attachment and Body content to MIME msg object
msg.setContent(multipart);
//Sending the message
Transport transport = session.getTransport("smtp");
transport.connect(smtpHost, sender, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("Mail sent succesfully!");
} catch (MessagingException e) {
throw new RuntimeException(e);
} finally {
//Removing System properties
sys_prop.remove("proxySet");
sys_prop.remove("proxyHost");
sys_prop.remove("proxyPort");
sys_prop.remove("socksProxyHost");
sys_prop.remove("mail.smtp.socketFactory.class");
sys_prop.remove("mail.smtp.socketFactory.fallback");
sys_prop.remove("mail.smtp.socketFactory.port");
}
}
}
Property file 'Email.Properties':
sender=helloqa86#gmail.com
recevier=k.b#xx.com
password=*****
proxyHost=web-proxy.**.**.com
proxyPort= 8080
smtpHost=smtp.gmail.com
smtpPort=465
From the error I can understand that problem is in this part
messageBodyPart.setContent(paragraphs, "application/msword"); where I am adding word document content to MIME message body part.
I have tried several other ways to achieve this but not able to do so. Please suggest a way to achieve this?
I got a resolution to this problem.Actually , I have to put different font face and font sizes in email body which I am trying to read from word document.To achieve this I have changed my approach,so instead of word document I have embedded my content into html tags which is quite simple :) , refer the below line of code which will replace word document part
String htmltext = "+
Different Font Size+
Different Font Size+
";
messageBodyPart.setContent(htmltext, "text/html");
During my research one of my friend suggested me following third party API's , it might be helpful to anyone
http://www.oracle.com/technetwork/java/javamail/third-party-136965.html
https://github.com/bbottema/simple-java-mail/

AspectJ - Is is possible to extend an enum's value?

Say I have an enum
public enum E {A,B,C}
Is it possible to add another value, say D, by AspectJ?
After googling around, it seems that there used to be a way to hack the private static field $VALUES, then call the constructor(String, int) by reflection, but seems not working with 1.7 anymore.
Here are several links:
http://www.javaspecialists.eu/archive/Issue161.html (provided by #WimDeblauwe )
and this: http://www.jroller.com/VelkaVrana/entry/modify_enum_with_reflection
Actually, I recommend you to refactor the source code, maybe adding a collection of valid region IDs to each enumeration value. This should be straightforward enough for subsequent merging if you use Git and not some old-school SCM tool like SVN.
Maybe it would even make sense to use a dynamic data structure altogether instead of an enum if it is clear that in the future the list of commands is dynamic. But that should go into the upstream code base. I am sure the devs will accept a good patch or pull request if prepared cleanly.
Remember: Trying to avoid refactoring is usually a bad smell, a symptom of an illness, not a solution. I prefer solutions to symptomatic workarounds. Clean code rules and software craftsmanship attitude demand that.
Having said the above, now here is what you can do. It should work under JDK 7/8 and I found it on Jérôme Kehrli's blog (please be sure to add the bugfix mentioned in one of the comments below the article).
Enum extender utility:
package de.scrum_master.util;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import sun.reflect.ConstructorAccessor;
import sun.reflect.FieldAccessor;
import sun.reflect.ReflectionFactory;
public class DynamicEnumExtender {
private static ReflectionFactory reflectionFactory =
ReflectionFactory.getReflectionFactory();
private static void setFailsafeFieldValue(Field field, Object target, Object value)
throws NoSuchFieldException, IllegalAccessException
{
// let's make the field accessible
field.setAccessible(true);
// next we change the modifier in the Field instance to
// not be final anymore, thus tricking reflection into
// letting us modify the static final field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
int modifiers = modifiersField.getInt(field);
// blank out the final bit in the modifiers int
modifiers &= ~Modifier.FINAL;
modifiersField.setInt(field, modifiers);
FieldAccessor fa = reflectionFactory.newFieldAccessor(field, false);
fa.set(target, value);
}
private static void blankField(Class<?> enumClass, String fieldName)
throws NoSuchFieldException, IllegalAccessException
{
for (Field field : Class.class.getDeclaredFields()) {
if (field.getName().contains(fieldName)) {
AccessibleObject.setAccessible(new Field[] { field }, true);
setFailsafeFieldValue(field, enumClass, null);
break;
}
}
}
private static void cleanEnumCache(Class<?> enumClass)
throws NoSuchFieldException, IllegalAccessException
{
blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6
blankField(enumClass, "enumConstants"); // IBM JDK
}
private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)
throws NoSuchMethodException
{
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
parameterTypes[0] = String.class;
parameterTypes[1] = int.class;
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
return reflectionFactory.newConstructorAccessor(enumClass .getDeclaredConstructor(parameterTypes));
}
private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes, Object[] additionalValues)
throws Exception
{
Object[] parms = new Object[additionalValues.length + 2];
parms[0] = value;
parms[1] = Integer.valueOf(ordinal);
System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));
}
/**
* Add an enum instance to the enum class given as argument
*
* #param <T> the type of the enum (implicit)
* #param enumType the class of the enum to be modified
* #param enumName the name of the new enum instance to be added to the class
*/
#SuppressWarnings("unchecked")
public static <T extends Enum<?>> void addEnum(Class<T> enumType, String enumName) {
// 0. Sanity checks
if (!Enum.class.isAssignableFrom(enumType))
throw new RuntimeException("class " + enumType + " is not an instance of Enum");
// 1. Lookup "$VALUES" holder in enum class and get previous enum
// instances
Field valuesField = null;
Field[] fields = enumType.getDeclaredFields();
for (Field field : fields) {
if (field.getName().contains("$VALUES")) {
valuesField = field;
break;
}
}
AccessibleObject.setAccessible(new Field[] { valuesField }, true);
try {
// 2. Copy it
T[] previousValues = (T[]) valuesField.get(enumType);
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
// 3. build new enum
T newValue = (T) makeEnum(
enumType, // The target enum class
enumName, // THE NEW ENUM INSTANCE TO BE DYNAMICALLY ADDED
values.size(), new Class<?>[] {}, // could be used to pass values to the enum constuctor if needed
new Object[] {} // could be used to pass values to the enum constuctor if needed
);
// 4. add new value
values.add(newValue);
// 5. Set new values field
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
// 6. Clean enum cache
cleanEnumCache(enumType);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
}
}
}
Sample application & enum:
package de.scrum_master.app;
/** In honour of "The Secret of Monkey Island"... ;-) */
public enum Command {
OPEN, CLOSE, PUSH, PULL, WALK_TO, PICK_UP, TALK_TO, GIVE, USE, LOOK_AT, TURN_ON, TURN_OFF
}
package de.scrum_master.app;
public class Server {
public void executeCommand(Command command) {
System.out.println("Executing command " + command);
}
}
package de.scrum_master.app;
public class Client {
private Server server;
public Client(Server server) {
this.server = server;
}
public void issueCommand(String command) {
server.executeCommand(
Command.valueOf(
command.toUpperCase().replace(' ', '_')
)
);
}
public static void main(String[] args) {
Client client = new Client(new Server());
client.issueCommand("use");
client.issueCommand("walk to");
client.issueCommand("undress");
client.issueCommand("sleep");
}
}
Console output with original enum:
Executing command USE
Executing command WALK_TO
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant de.scrum_master.app.Command.UNDRESS
at java.lang.Enum.valueOf(Enum.java:236)
at de.scrum_master.app.Command.valueOf(Command.java:1)
at de.scrum_master.app.Client.issueCommand(Client.java:12)
at de.scrum_master.app.Client.main(Client.java:22)
Now you can either add an aspect with an advice executed after the enum class was loaded or just call this manually in your application before extended enum values are to be used for the first time. Here I am showing how it can be done in an aspect.
Enum extender aspect:
package de.scrum_master.aspect;
import de.scrum_master.app.Command;
import de.scrum_master.util.DynamicEnumExtender;
public aspect CommandExtender {
after() : staticinitialization(Command) {
System.out.println(thisJoinPoint);
DynamicEnumExtender.addEnum(Command.class, "UNDRESS");
DynamicEnumExtender.addEnum(Command.class, "SLEEP");
DynamicEnumExtender.addEnum(Command.class, "WAKE_UP");
DynamicEnumExtender.addEnum(Command.class, "DRESS");
}
}
Console output with extended enum:
staticinitialization(de.scrum_master.app.Command.<clinit>)
Executing command USE
Executing command WALK_TO
Executing command UNDRESS
Executing command SLEEP
Et voilà! ;-)

eventhough i change the environmental variables and classpath, while running sqlite jdbc program i get the error stating no class definition doun

im running a jdbc program on Sqlite. though i change the environmental variables or define the classpath of the jar file sqlite-jdbc-3.7.2.jar, i get an error stating ClassNotFoundException: org.sqlite.JDBC... how to rectify it?
my code is`
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sample
{
public static void main(String[] args)throws ClassNotFoundException
{
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(1, 'leo')");
statement.executeUpdate("insert into person values(2, 'yui')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}`
my jar file is sqlite-jdbc-3.7.2.jar
my class path is D:\jdk1.6.0_45\sqlite-jdbc-3.7.2.jar
my environmental variable is also the same
what should i do?
help pls
i found the solution to my problem...
the class path should be like
`javac Sample.java
java -classpath "D:\jdk1.6.0_45\sqlite-jdbc-3.7.2.jar";. Sample`
the problem is solved:)

Why is this creating an infinite loop?

Can someone explain why this is making an infinite loop? The hurcdata2 has about 30 straing values in it. I don't understand what the problem is.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Hurricanes2
{
public static void main(String[] args) throws IOException
{
int i = 0;
int hurricaneNumber = 0;
String hurricanes = "";
File fileName = new File("hurcdata2.txt");
Scanner inFile = new Scanner(fileName);
while (inFile.hasNext())
{
hurricaneNumber++;
}
}
}
In your while - loop you should call inFile.nextLine() to make it process each line in the file.
while (inFile.hasNext()) {
hurricaneNumber++;
String line = inFile.nextLine();
}
As noted in the comment by #ElectricLlama you need to advance your file pointer, to get the next token, otherwise the hasNext() will always be true. Check this question and this tutorial on File I/O in Java.

JRI Fatal Error on Ubuntu

I have successfully installed JRI and rJava on Windows 7. I am now trying to get it to work on Ubuntu with 64bit OS. I can make rJava calls from within R but getting JRI to work is more difficult. I am running NetBeans 7.1.2 and I have followed various tricks in setting R_HOME and java.library.path to enable all the classes to be loaded. That is, I am past the error messages such as "jri library not found" and "R_HOME not set".
From my java code,I can see that R_HOME = /usr/lib64/R.
The error message I get now is
Fatal error: you must specify '--save', '--no-save' or '--vanilla'
This happens when Rengine is first called:
Rengine r = new Rengine(args,false,null);
This appears to be an error message from R; it seems to be expecting a command line argument. I haven't seen any posting with this error message. Any ideas? Thanks, Peter
Using R in this setting requires you to run R in non-interactive mode. To solve the issue, you need to choose on of the options given in the error message. I would try --no-save first. This prevents R from saving the workspace at the end of the run. In Java code:
String args[] = {"--no-save"};
Rengine re = new Rengine(args, false, null);
I will post my code for anyone trying to replicate these steps. The code is cobbled together from multiple web sources. Sorry for the re-formatting that occurs: I don't know how to show it as straight text.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package testjri;
/**
*
* #author root
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.rosuda.JRI.Rengine;
import org.rosuda.JRI.*;
import org.rosuda.REngine.*;
public class TestJRI {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{//in the folder /etc/ld.so.conf.d I created a file called libR.conf with the single line "/usr/lib64/R/lib/" in it (without the quotes).
//In the same folder I created a file called rJava.conf with the single line "/usr/lib/jvm/java-6-openjdk/jre/lib/amd64/server/" in it (without the quotes).
//I then ran ldconfig to force these changes.
//To get R_HOME set, I had to modify netbeans.conf adding the line "export R_HOME=/usr/lib64/R"
System.out.println("R_HOME: "+System.getenv("R_HOME"));
try{//This next line is a trick to force a change to java.library.path at runtime
addLibraryPath("/usr/lib64/R/site-library/rJava/jri/");
// I copied libR.so to the jri folder so I am not sure if the next line does anything
addLibraryPath("/usr/lib64/R/lib/");
}catch(Exception e){System.out.println(e.toString());}
System.out.println("java.library.path: "+java.lang.System.getProperty("java.library.path"));
//Set some labels for the plot
String title = "R Plot in JFrame";
String xlab = "X Label";
String ylab = "Y Label";
//Start R
String newargs[] = {"--no-save"};
Rengine r = new Rengine(newargs, false, null);
//Do some calcs and plot the chart but save as a png in the working folder
r.eval("a<-c(1,2,3,4,5,6,7,8,9,10)");
r.eval("b<-c(1,3,2,4,5,6,7,8,9,10)");
r.eval("png(file=\"graph2.png\",width=1600,height=1600,res=400)");
r.eval("plot(a,b,type='o',col=\"Blue\",main=\"" + title + "\",xlab=\""
+ xlab + "\",ylab=\"" + ylab + "\")");
r.eval("dev.off()");
//It took me a search to find where R stuck the image. I found it in /proc/29285/cwd.
//I will have to learn how to control the working folder for R from java.
//get the image and create a new imagepanel
File file = new File("/proc/29285/cwd/graph2.png");
Image image = ImageIO.read(file);
imagePanel myPanel = new imagePanel(image);
//Create a new frame and add the imagepanel
JFrame aFrame = new JFrame();
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.getContentPane().add(myPanel, BorderLayout.CENTER);
aFrame.pack();
aFrame.setVisible(true);
aFrame.setSize(new Dimension(600, 600));
}
static class imagePanel extends JPanel
{
Image image = null;
public imagePanel(Image image)
{
this.image = image;
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//there is a picture: draw it
if (image != null)
{
int height = this.getSize().height;
int width = this.getSize().width;
g.drawImage(image, 0, 0, width, height, this);
}
}
}
/**
* Adds the specified path to the java library path
*
* #param path the new library path to add
* #throws Exception
*/
public static void addLibraryPath(String path) throws Exception {
String oldPath = System.getProperty("java.library.path");
if (oldPath.length() >0)path = path+":"+oldPath;
System.setProperty("java.library.path", path);
//set sys_paths to null
final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
sysPathsField.setAccessible(true);
sysPathsField.set(null, null);
}
}

Resources