dinsdag 19 mei 2009

Java Swt layout designer

Today I found an example about SWT layouts. This is a great example, it is possible to design your Gui with this program, experimenting with different sorts of layouts and its parameters. There is a button Code, which will show you the source code. I really like this sort of programs.

The source code can be found here

zondag 17 mei 2009

Execute a program from Java, providing it with input

package net.arjenmax.mprimegui.linux;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class ExecPgmFromJava {

public static void main(String[] args) {
String execDir = "/gimps/";
String pgm2exec = execDir + "mprime -m";
String[] cmd = {"/bin/sh", "-c", pgm2exec};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
pb.directory(new File(execDir));
String inputCmd = "17\n\n3\n\n5\n";
try {
Process proc = pb.start();
ExecInputHandler inputGobbler = new ExecInputHandler(proc.getOutputStream(), inputCmd);
ExecOutputHandler outputGobbler = new ExecOutputHandler(proc.getInputStream());
outputGobbler.start();
inputGobbler.input2Exec();
} catch (Throwable t) { t.printStackTrace(); }
}

}

class ExecOutputHandler extends Thread  {

private InputStream is;
private boolean bNoOutput;

ExecOutputHandler(InputStream is) {
this.is = is;
}

public void run() {
try {
String line=null;
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
if (line.indexOf("Main Menu") != -1) {
bNoOutput = true;
}
if (bNoOutput == false) {
if (line.startsWith("[Main") == false) {
System.out.println(line);
}
}
if (line.indexOf("Your choice:") != -1) {
bNoOutput = false;
}
}
} catch (IOException ioe) { ioe.printStackTrace(); }
}
}

class ExecInputHandler {

private OutputStream outputStream;
private String cmd;

public ExecInputHandler(OutputStream outputStream, String cmd) {
this.outputStream = outputStream;
this.cmd = cmd;
}

public void input2Exec() {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
try {
writer.write(cmd);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}

}

}