Hello again stack community,
I am working on a program to graphically display prompts, stored in a 2D array, and their correct response counterparts - I start off by calling the creation of a Menu object:
public static void main (String [] args){
SwingUtilities.invokeLater(new Runnable(){
public void run() { new Menu(); }
});
}
Within Menu I define various buttons:
JButton chem3Button, chin1Button, mathstatButton//etc...
followed by an action listener that follow the addition of properties such as the the tooltip and such:
mathstatButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent j) {
new matstatMenu();
}
});
which in turn passes control to matstatMenu, which allows the selection of an area in Mathematics, which in this case is only one, the available:
mathstatb1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent l) {
new SwingImplementation(2, 1);
}});
Which sends Subject 2 (Math), and Subject Subset 1 (Descriptive Statistics) to SwingImplementation via the mathstatb1 button, to fly through this loop that copies the statistics array to oneRay:
case 2:
switch(unit){
case 1:
oneRay = new String[Master.MathaRay_Part2.length][2];
for(int i = 0; (Master.MathaRay_Part2.length) > i; i++){
oneRay[i][0] = Master.MathaRay_Part2[i][0]; oneRay[i][1] =
Master.MathaRay_Part2[i][1];} break;
default: System.exit(0); break;
} break;
and then fails to progress through this do-loop, which cycles infinitely despite the fact that the array Master.MathaRay_Part2 is full and by the above code should be fully copied.
Why is this do loop failing, or rather, never exiting?
do{
System.out.println("C");
pick = random.nextInt(oneRay.length);
}while((oneRay[pick][0]).isEmpty());
Please, I am just a swing-neophyte trying to create a program to help myself and peers in school, any help will be greatly appreciated.
I'm not sure what your problem is - there isn't enough code here for me to figure it out; and I know nothing about the Master.MathaRay_Part2 class. However, doing the following should help you, and would help me help you if you edit the results into your original post.
First, add the following function to your class that has the do loop:
private static final String toTwoDArrayString(Object[][] arr) {
StringBuilder sb = new StringBuilder();
sb.append('[');
boolean first = true;
for(Object[] row : arr) {
if (!first) {
// Requires Java 7. replace %n with either \n or \r\n for Java 6
sb.append(String.format(",%n "));
}
first = false;
sb.append(Arrays.toString(row));
}
sb.append(']');
return sb.toString();
}
Second, make sure that Master.MathaRay_Part2.toString() is implemented in a useful way, if it isn't already. In Eclipse, you can use Right Click -> Source -> Generate toString()...
Finally, immediately before the do loop, call:
System.out.println(toTwoDArrayString(onepick));
Related
I am trying to make a Book Database GUI which inserts the title,author and price of each book in the array created.
There is a search function to search a particular book in the database by its title.
However my code only seems to work for only one book and not for multiple books.
I am trying to enter 10 book details here for instance.
I am only able to search the book which was created the last.
My Code is as follows:
class Book{
public String title,author;
public int price;
Book(String t,String a,int p){
this.title=t;
this.author=a;
this.price=p;
}
}
class Swingdemo implements ActionListener{
Book B[]=new Book[10];
JLabel jl1;
JTextField a1,a2,a3,a4;
JButton j1,j2,j3;
Swingdemo() {
JFrame jfrm = new JFrame("Welcome");
jfrm.setSize(180,300);
jfrm.setLayout(new FlowLayout());
jfrm.setDefaultCloseOperation(jfrm.EXIT_ON_CLOSE);
a1 = new JTextField(8);
a2 = new JTextField(8);
a3 = new JTextField(8);
j1 = new JButton("Create");
a4 = new JTextField(8);
j2 = new JButton("Search");
jl1 = new JLabel("Press a Button");
j1.setActionCommand("1");
j2.setActionCommand("2");
j1.addActionListener(this);
j2.addActionListener(this);
jfrm.add(a1);
jfrm.add(a2);
jfrm.add(a3);
jfrm.add(j1);
jfrm.add(a4);
jfrm.add(j2);
jfrm.add(jl1);
jfrm.setVisible(true);
}
int num=0;
public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("1")){
B[num]=new Book(a1.getText(),a2.getText(),Integer.parseInt(a3.getText()));
jl1.setText("Book has been added");
num++;
}
else{
int i;
for(i=0;i<B.length;i++){
if(B[i].title.equals(a4.getText()))
jl1.setText("Book has been found");
}
if(i==B.length)
jl1.setText("Book was not found");
}
}
public static void main(String []args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Swingdemo();
}
});
}
}
I prefer use Optional wrapper instead of local variable such as found
Optional<Book> mbyBook = Optional.empty();
for (Book b : B) {
if (b.title.equals(a4.getText())) {
mbyBook = Optional.of(b);
break;
}
}
if (mbyBook.isPresent()) {
jl1.setText(String.format("Book has been found %s", mbyBook));
} else {
jl1.setText("Book was not found");
}
The way to solve a problem like this is to separate it from all the irrelevant Swing stuff, into a method of its own:
public String findBook(String title) {
int i;
for(i=0;i<B.length;i++){
if(B[i].title.equals(title))
return("Book has been found");
}
if(i==B.length)
return("Book was not found");
}
}
All I have done here is copy/paste your code from int i onward, and put it in a method, passing title instead of looking directly at the Swing text fields. Then I replaced the setTexts with return.
You can call this by replacing the whole chunk in your main code with:
jl1.setText(findBook(a4.getText());
Now the method is independent of Swing, and you can test it on its own.
The first problem is that it won't compile. Now that we've returned the setTexts with return the compiler can noticed that there's a route through the code that doesn't return anything -- where all the ifs are false.
So let's make it compile, by adding a return at the end. We'll also add braces {} so that the ifs are visually consistent. Never leave out braces, even though the compiler lets you.
public String findBook(String title) {
for(int i=0;i<books.length;i++){
if(books[i].title.equals(title))
return("Book has been found");
}
if(i==books.length) {
return("Book was not found");
}
}
return null;
}
I also moved the declaration of i into its initialiser. It's a familiar form.
And I renamed B to books. In Java we tend towards descriptive variable names, and variables always start with a lower-case letter.
Now we have something that compiles. One good approach is to run tests in a debugger (your IDE has one). But we can eyeball this code, and work out what it would do when the book is not found.
Let's say B[] is just 3 items long. i starts at 0.
Is 0 < 3 ? Yes. Continue with loop.
Does B[0] match on title? No. Skip if.
Does 0 == 3? No. Skip if.
i++ -- i == 1
Is 1 < 3 ? Yes. Continue with loop.
Does B[1] match on title? No. Skip if.
Does 1 == 3? No. Skip if.
i++ -- i == 2
Is 2 < 3 ? Yes. Continue with loop.
Does B[2] match on title? No. Skip if.
Does 2 == 3? No. Skip if.
i++ -- i == 3
Is 3 < 3 ? No. Exit loop.
return null
We never pass the if(i==B.length) test, because we only ever enter that block when i<B.length.
But that return null gets hit. So you can make it do what you want by putting the not found response after the loop:
public String findBook(String title) {
for(int i=0;i<Books.length;i++){
if(Books[i].title.equals(title))
return("Book has been found");
}
}
return("Book was not found");
}
boolean found = false;
for(i=0;i<B.length;i++) {
if(B[i].title.equalsIgnoreCase(a4.getText().trim())) {
found = true;
break;
}
}
if(!found)
jl1.setText("Book was not found");
else
jl1.setText("Book has been found");
Or you could also do,
for(i=0;i<B.length;i++) {
if(B[i].title.equalsIgnoreCase(a4.getText().trim())) {
break;
}
}
if(B.length > 0 && i < B.length)
jl1.setText("Book has been found");
else
jl1.setText("Book was not found");
I've just started to learn Java,and I've got some questions for my code. Well,the task is to get a number and print a matrix like this:
get 3,and print:
1 2 3
8 9 4
7 6 5
get 4,and print:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
Because I'm learning algorithm,so I deal the question by DFS, here's my cpp code,which can solve the task.
#include "iostream"
using namespace std;
int n;
int matrix[100][100]={0};
int visited[100][100]={0};
void dfs(int n,int x,int y,int i,int dire)
{
//x,y is the coordinate,i is the number to write
//dire is the variety to control the direction of the dfs
if(i==n*n+1)return;
switch(dire)
{
case(1)://write the number on right
{
if(visited[x][y+1]==0&&y+1<n)
{
visited[x][y+1]=1;
matrix[x][y+1]=i;
i++;
dfs(n,x,y+1,i,1);
}
else dfs(n,x,y,i,2);
break;
}
case(2)://down
{
if(visited[x+1][y]==0&&x+1<n)
{
visited[x+1][y]=1;
matrix[x+1][y]=i;
i++;
dfs(n,x+1,y,i,2);
}
else dfs(n,x,y,i,3);
break;
}
case(3)://left
{
if(visited[x][y-1]==0&&y-1>=0)
{
visited[x][y-1]=1;
matrix[x][y-1]=i;
i++;
dfs(n,x,y-1,i,3);
}
else dfs(n,x,y,i,4);
break;
}
case(4)://up
{
if(visited[x-1][y]==0&&x-1>=0)
{
visited[x-1][y]=1;
matrix[x-1][y]=i;
i++;
dfs(n,x-1,y,i,4);
}
else dfs(n,x,y,i,1);
break;
}
}
}
void output(int n)
{
int p,q=0;
for(q=0;q<n;q++)
{
for(p=0;p<n;p++)
{
cout<<matrix[q][p]<<" ";
if(matrix[q][p]<10)
cout<<" ";
if(matrix[q][p]<100)
cout<<" ";
}
cout<<endl;
}
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
matrix[i][j]=0;
visited[i][j]=0;
}
}
///dfs_r(n,0,-1,1);
dfs(n,0,-1,1,1);
output(n);
}
But things goes wrong when I translate it into Java
import java.util.Scanner;
public class mainclass{
public static class method{
int n;
int visited[][]=new int[n][n];
int matrix[][]=new int[n][n];
method(int temp){
n=temp;
}
void dfs(int x,int y,int i,int dire)
{
if(i==n*n+1)return;
switch(dire)
{
case(1):
{
if(visited[x][y+1]==0&&y+1<n)
{
visited[x][y+1]=1;
matrix[x][y+1]=i;
i++;
dfs(x,y+1,i,1);
}
else dfs(x,y,i,2);
break;
}
case(2):
{
if(visited[x+1][y]==0&&x+1<n)
{
visited[x+1][y]=1;
matrix[x+1][y]=i;
i++;
dfs(x+1,y,i,2);
}
else dfs(x,y,i,3);
break;
}
case(3):
{
if(visited[x][y-1]==0&&y-1>=0)
{
visited[x][y-1]=1;
matrix[x][y-1]=i;
i++;
dfs(x,y-1,i,3);
}
else dfs(x,y,i,4);
break;
}
case(4):
{
if(visited[x-1][y]==0&&x-1>=0)
{
visited[x-1][y]=1;
matrix[x-1][y]=i;
i++;
dfs(x-1,y,i,4);
}
else dfs(x,y,i,1);
break;
}
}
}
void output()
{
int p,q=0;
for(q=0;q<n;q++)
{
for(p=0;p<n;p++)
{
System.out.print(matrix[q][p]);
if(matrix[q][p]<10)
System.out.print(" ");
if(matrix[q][p]<100)
System.out.print(" ");
}
System.out.println();
}
}
}
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
int n=reader.nextInt();
method c=new method(n);
c.dfs(0,-1,1,1);
c.output();
}
}
I think my algorithm is all right,but I can't work it out why my Java code crashes. I think I should learn more about basic grammar of Java.
edit:
I use dev-cpp to run my cpp code and eclipse to run my Java code. I'm not really know how to describe how does the crash of my Eclipse got, the code is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at mainclass$method.dfs(mainclass.java:17)
at mainclass.main(mainclass.java:87)
<terminated, exit value: 1>C:\Program Files\Java\jre1.8.0_101\bin\javaw.exe (2016年9月27日 上午9:51:32)
the crash scene
(The answer there supposes you have an IDE, like Eclipse).
The really, really dirty way
You can, when in doubt, always rely on a good old System.out.println(yourobject). Be careful about objects, never forget that you can turn them into String and check inner objets (in your case, visited[1][2] or matrix[2][0] for example). BUT it sucks. Really. It might suffice for your needs, but it is really a bad habit to take.
The 'okay' way (EDIT)
Use a tool named SLF4J to get some additional traces. As you are only on a small method and not a complete project, I would not command you to deploy this tool yet, but keep in mind that it is a good way to both figure out what happens and have your console logging what you need, especially when the projects are getting intersting (read: bigger).
The good and elegant way
Learn a bit about a tool called debug mode. You can find further help on the Eclipse help center, but basically the steps are:
Place a breakpoint. On the left of your code (with line numbers), you can right-click to toogle / enable / disable breakpoints.
Run your program in debug. It is a little bug (how convenient) near the classic run icon. You'll get redirected to the debug perspective.
The run will be interrupted where you toogled your breakpoint. There, you will be able to go, step by step, into your code. You will also be able to check the state of every variable you declared, in order to identify your problem.
[Your job here is to make the necessary changes]
Now you know about debugger, ArrayOutOfBoundsException and became a better person in general thanks to this good practice.
Vogella has a good tutorial about how to use the debugger in a nice way. Learn to use it if you plan on keeping on Java, because this will save you a lot of time (an awful lot, believe me).
I have a class called InstructionBlock, which is a JPanel
On my main form, which is a JFrame, I've created 6 instances of InstructionBlock. I need to have my main form do something based on a button being pressed in the instances of InstructionBlock and it needs to know which instances had the button pressed.
I have the following code in the class InstructionBlock:
public void InstBlockAddActionListener(ActionListener al) {
CheckMarkClicked.addActionListener(al);
}
I've add the instances of InstructionBlock to my main form as follows:
ArrayList<InstructionBlock> instructionPane = new ArrayList<>();
int i;
for (int i = 0; i<6;i++) {
instructionPane.add(new InstructionBlock());
InstructionLayer.add(instructionPane.get(i));
}
Now here is where I have an issue:
for (i = 0; i<6;i++) {
instructionPane.get(i).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(i+1);});
}
When I hit the 1st button, I expected to pass a value of 1, but I'm passing a value of 7
I know I can do it as follows:
instructionPane.get(0).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(1);});
instructionPane.get(1).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(2);});
instructionPane.get(2).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(3);});
instructionPane.get(3).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(4);});
instructionPane.get(4).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(5);});
instructionPane.get(5).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(6);});
But I don't know why the loop isn't working. Is there another way to make it work?
Your problem is here:
for (i = 0; i<6;i++) {
instructionPane.get(i).InstBlockAddActionListener((ActionEvent ae) -> {InstructionCheckMarkButtonPressed(i+1);});
}
You must be making i a field of the class for this to compile, and by doing this, you set it to 7 and only 7 after this for loop has finished. To solve this, don't use a class field but rather an inner final variable, something like:
for (int j = 0; j < 6; j++) {
final int finalIndex = j + 1;
instructionPane.get(j).InstBlockAddActionListener((ActionEvent ae) -> {
InstructionCheckMarkButtonPressed(finalIndex);
});
}
As a side recommendation, and in order to help us now and to help yourself in the future, please edit your code and change your variable names to conform with Java Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
I have started a Java coding short course at a university about 5 months ago. I have learnt quite the amount of things with regards to Java coding, but am still lacking in other things such as threads, handling exceptions, or even making JFrame games. I decided to embark on a text based game to just learn and figure out how a game loop should work (kind of), and how the logic should work (still, very "kind of"). The game I wrote runs with if-else commands, thus you get displayed a screen, type in the command of the option you want to pick, and it bumps you to the next menu, very standard of course. I run these if-else statements within nested for loops.
My nested for loops looks like the following:
// This is just an example, they're actually a lot more cluttered
// in my actual source code.
mainMenu.writeOutput();
reply = keyboardInput.nextLine();
for (int i = 0; i <= 10; i--)
{
for (int ii = 0; i <= 10; i--)
{
if (reply.equalsIgnoreCase("/help")
{
System.out.println("Here I have a separate call to a class
file (excuse me, forgot the exact wording), thus it
call something like help.writeOutput(); to display
the help menu");
reply = keyboardInput.nextLine();
if (reply.equalsIgnoreCase("/makegameeasy")
{
// Just an example.
gamedifficultyEasy.writeOutput();
reply = keyboardInput.nextLine();
if (reply.equalsIgnoreCase("/back")
{
mainMenu.writeOutput();
reply = keyboardInput.nextLine();
break;
}
}
else if (reply.equalsIgnoreCase("/makegamedifficult")
{
// Another example.
gamedifficultHard.writeOutput();
reply = keyboardInput.nextLine();
if (reply.equalsIgnoreCase("/back")
{
mainMenu.writeOutput();
reply = keyboardInput.nextLine();
break;
}
}
else if (reply.equalsIgnoreCase("/back")
{
mainMenu.writeOutput();
reply = keyboardInput.nextLine();
break;
}
}
else
{
System.out.println("Here I print out an error for incorrect
input received, standard fare.");
mainMenu.writeOutput();
reply = keyboard.nextLine();
break;
}
}
}
As mentioned, the above is just an example, it's not very elegant, and I can probably use Exceptions for any incorrect info submitted by the user, however I do not know too much of Exceptions to comfortably add them, so I'll do that at a later time, however my main issue at the moment is a part of my game where "resource mining" has to be done on regular intervals. I have been all over Google, but still can't quite catch how to set a Thread or Timer up for my game so it does the mining automatically, and the player can go on with their game.
The game is essentially one of those games where you build up a base, upgrade your mining tools, and generate more "stuff". I have pasted a few blocks of code from my "mining" class file below that will basically run how much of one thing should be mined. In the game you will be able to buy upgrades of course, so it will get factored into your mining speed.
// I initiate my variables a lot earlier, but just for some
// clarity, I have initiated the variables in the below methods,
// they will not work correctly anyway, I am aware of that, however
// I didn't want to add the other "get, set and initiate"
// variables and methods everywhere, as to not spam this block of code.
// upgradeOS, upgradeHF, and upgradeLM all have their own respective
// set and get methods. They are also all int variables.
public void handleOS()
{
// OS = short for Oxygen Silo
int mineOS = os.getStoredO2() + (1 * upgradeOS);
os.setStoredO2(mineOS);
}
public void handleHF()
{
// HF = short for Hydrogen Fuel
int mineHF = hf.getStoredO2() + (1 * upgradeHF);
hf.setStoredO2(mineHF);
}
public void handleLM()
{
// LM = short for Liquid Minerals
int mineLM = lm.getStoredMinerals() + (1 * upgradeLM);
lm.setStoredMinerals(mineLM);
}
// This is what's going to run the whole time on the set intervals.
public void mine()
{
mineOS = os.getStoredO2() + (1 * upgradeOS);
mineHF = hf.getStoredO2() + (1 * upgradeHF);
mineLM = lm.getStoredMinerals() + (1 * upgradeLM);
os.setStoredO2(mineOS);
hf.setStoredO2(mineHF);
lm.setStoredMinerals(mineLM);
}
// Using 10 seconds here to have it update as quickly as possible so I can
// see any changes. This is just here to write an output.
public void getUpgradeInfo()
{
System.out.println("Oxygen: " + (1 * upgradeOS) + " / per 10 seconds.");
System.out.println("Hydrogen: " + (1 * upgradeHF) + " / per 10 seconds.");
System.out.println("Liquid Mineral: " + (1 * upgradeLM) + " / per 10 seconds.");
}
I'm not the best naming schemes for my materials...
TL;DR: I can't figure out how to implement a thread or timer just for the above mentioned mine() method since I do not have the appropriate amount of knowledge. My if-else rules aren't too elegant, but I'll work on those of course. Basically the if-else rules should run separately from the mine() method, and you can do some AFKing without the game updating the System.out output, thus you can be floating in, for example, the Oxygen Silo upgrade menu, and you won't be bounced back to a different menu due to a thread "waking up", such as being bounced to the main menu, but the mine() method will still generate resources in the background as it should.
Any help on this, or just even a nudge in the right direction will be greatly appreciated.
To answer the question you asked, you can do something like this:
import java.util.*;
TimerTask tt = new TimerTask() {
public void run() {
mine();
}
}
Timer t = new Timer();
t.scheduleAtFixedRate(tt, 0, 1000);
Alternatively, you can use an ActionListener and the swing timer in a similar way. This has the advantage of being Thread-safe in case you build a swing gui on top
Lastly, you should check out the usage of synchronized and volatile to make sure that the variable(s) that are updated in mine() are done so in a thread-safe way
Thanks to #ControlAltDel, definite shove in the right direction. I have taken a bit of code and set it up like this:
import java.util.*;
// extends TimerTask needed
public class TimerTestOne extends TimerTask
{
// Needed
#Override
public void run()
{
TimerTestTwo ttt = new TimerTestTwo();
mine();
}
// Needed, method doesn't need the same name though.
private void completeTask()
{
try
{
//assuming it takes 10 secs to complete the task
Thread.sleep(10000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
// You will need to define the following line of code:
TimerTask tt = new TimerTestOne();
Scanner keyboard = new Scanner(System.in);
String reply;
// Following 2 lines of code, yup, need them.
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(tt, 0, 10*1000);
previousMenu();
for (int i = 0; i <= 10000; i++)
{
for (int ii = 0; ii <= 10000; i++)
{
System.out.println("Go to another menu?");
reply = keyboard.nextLine();
if (reply.equalsIgnoreCase("/yes"))
{
yes();
reply = keyboard.nextLine();
}
}
}
}
// I added the following methods, just so I didn't have to work
// off 2 class files.
public void mine()
{
System.out.println("Mined");
}
public static void yes()
{
System.out.println("Next menu");
}
public static void previousMenu()
{
System.out.println("Previous menu");
}
}
So there, if anyone ever needs to have a look at setting a timer up that won't break your text based game.
I have an issue loading a large dataset into R from Java. The problem is actually with the function I am using: re.eval(). I want to load a file into R so that I can analyse/manipulate it in R, however I want to do this from Java (this is in order to build a GUI).
What I want the function to do is parse and evaluate the string I provide, however, the eval function parses, evaluates and returns the result. I get an out of memory error from java regarding the heap size. This is the code I have at the moment:
JButton getFile = new JButton("Load");
getFile.setBounds(316, 10, 151, 23);
getFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
REXP x;
getFileName();
if (dataFilePath != null){
String file = dataFilePath.replace("\\", "\\\\\\\\");
re.eval("data<-read.csv(file='"+file+"', head=TRUE, sep='|')");
x = re.eval("names(data)");
String[] column_names = x.asStringArray();
originalDataLength = column_names.length;
for (int i = 0; i < column_names.length; i++) {
comboBox.insertItemAt(column_names[i], 0);
}
textField.setText("Data Loaded");
}
}
}
);
This code worked when I was working with a dataframe that was 13500x220. The new dataframe is 50000x700. I was also wondering what exactly is happening in the code above? Is it created in R and sent back to java (i.e duplicated?).
Any help/comments would be greatly appreciated. Also I have looked at the Rosuda Rengine class description and the functions available; I was thinking that maybe rniEval() might solve the problem but I don't know how to implement it.
actionPerformed is called on the event stack, and you should keep the event handling short. It just might help too. Call:
SwingUtilities.invokeLater(new Runnable() {
public void run() { ... your code ... }
}
Furthermore one should combine both eval expressions in R, if only the column names are wanted. Maybe just read the first line (by java?).