# Japplet in Applikation einbinden



## drinkingJava (8. Feb 2006)

Hallo, 
ich habe folgendes  Problem. bin noch ein programmieranfänger und keine besondere Erfahrung.
Ich habe einen JApplet den ich gerne in eine Applikation integrieren möchte. Und zwar kann ich der Gui des JApplets
in einem Textfield eine Formel eintragen und die GUi gibt mir dann als ausgabe parameter aus ob die Formel richtig oder falsch ist. meine Frage ist, kann ich irgendwie in meiner Applikation diesem Beweiser meine Eingabeformel übergeben ohne die Gui aufzurufen, einfach intern? die java klassen dieses Beweisers habe ich, doch aus dem quellcode werde ich nicht wirklcih schlau. 


```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;

public class Main extends JApplet {
	public static Gui gui = null;

	public static EscherInterface escherInterface = null;

	public void init() {
		gui = new Gui("Theorem Prover (version " + Config.version + ")", this);
	}

	public static void main(String[] args) {
		args = Config.parseOptions(args);

		if (Config.showGui) {
			gui = new Gui("Theorem Prover (version " + Config.version + ")",
					null);
		}
		if (args.length == 1) {
			if (gui != null) {
				gui.inputTextField.setText(args[0]);
			}
			(new Prover(0, args[0], System.out, gui)).start();
		} else if (Config.escherPort > 0) {
			try {
				escherInterface = new EscherInterface(Config.escherPort);
				new Thread(escherInterface).start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (args.length == 0) {
			try {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(System.in));
				while (true) {
					String input = reader.readLine();
					if (input == null || input.equals(""))
						break;
					(new Prover(0, input, System.out, gui)).start();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			System.err.println("Error reading command-line arguments ");
			System.exit(1);
		}
	}
}
```
das ist die Main klasse die das Applet aufruft.


```
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.TextField;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.BoxLayout;
import javax.swing.filechooser.FileFilter;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Gui implements ActionListener {
	JFrame frame;
	JMenuBar jMenuBar;
	JMenuItem exitMenuItem;
	JComboBox rulesOptionComboBox;
	JTextField rulesTextField1;
	JTextField rulesTextField2;
	JButton addRulesButton;
	JButton clearRulesButton;
	JComboBox verbosityComboBox;
	JLabel rulesJLabel;
	JButton startButton;
	JButton stopButton;
	JButton pauseButton;
	JButton clearButton;
	JButton printButton;
	JButton exitButton;
	JButton saveButton;
	TextField inputTextField;
	JTextArea outputTextArea;
	String saveFolder = "";
	ImageIcon startIcon;
	Prover prover = null;
	
	
	
	public Gui(String title, JApplet japplet) {
		frame = new JFrame(title);
		JPanel mainPanel = new JPanel();
		mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
		mainPanel.setPreferredSize(new Dimension(Config.frameWidth, Config.frameHeight));
		
	// Set up JMenuBar
		jMenuBar = new JMenuBar();
		JMenu file = new JMenu ("File");
		file.addSeparator();
		file.add(exitMenuItem = new JMenuItem ("Exit"));
		exitMenuItem.addActionListener(this);
		jMenuBar.add(file);
		if ( japplet == null ) {
			frame.setJMenuBar(jMenuBar);
		}
		
	// Set up panel 1
		JPanel panel1 = new JPanel();
		mainPanel.add(panel1);
		panel1.setPreferredSize(new Dimension(Config.frameWidth - 2 * Config.paddingWidth, Config.buttonHeight + 2 * Config.paddingWidth));
		panel1.setLayout(new FlowLayout(FlowLayout.LEFT));
		panel1.setBorder(new TitledBorder(LineBorder.createGrayLineBorder(), "Controls"));
		
		startIcon = new ImageIcon(this.getClass().getResource("Icons/start.png"));
		startButton = new JButton(startIcon);
		startButton.setToolTipText("Start a new proof");
		startButton.setPreferredSize(new Dimension(Config.iconSize, Config.iconSize));
		startButton.setBorder(new BevelBorder(BevelBorder.RAISED));
		startButton.addActionListener(this);
		panel1.add(startButton);
		
		pauseButton = new JButton(new ImageIcon(this.getClass().getResource("Icons/pause.png")));
		pauseButton.setToolTipText("Pause the current proof");
		pauseButton.setPreferredSize(new Dimension(Config.iconSize, Config.iconSize));
		pauseButton.setBorder(new BevelBorder(BevelBorder.RAISED));
		pauseButton.addActionListener(this);
		panel1.add(pauseButton);
		
		stopButton = new JButton(new ImageIcon(this.getClass().getResource("Icons/stop.png")));
		stopButton.setToolTipText("Stop the current proof");
		stopButton.setPreferredSize(new Dimension(Config.iconSize, Config.iconSize));
		stopButton.setBorder(new BevelBorder(BevelBorder.RAISED));
		stopButton.addActionListener(this);
		panel1.add(stopButton);
		
		panel1.add(new JLabel("     "));
		clearButton = new JButton(new ImageIcon(this.getClass().getResource("Icons/clear.png")));
		clearButton.setToolTipText("Clear the input formula and output log messages");
		clearButton.setPreferredSize(new Dimension(Config.iconSize, Config.iconSize));
		clearButton.setBorder(new BevelBorder(BevelBorder.RAISED));
		clearButton.addActionListener(this);
		panel1.add(clearButton);
		
		printButton = new JButton(new ImageIcon(this.getClass().getResource("Icons/print.png")));
		printButton.setToolTipText("Print the output log messages");
		printButton.setPreferredSize(new Dimension(Config.iconSize, Config.iconSize));
		printButton.setBorder(new BevelBorder(BevelBorder.RAISED));
		printButton.addActionListener(this);
		panel1.add(printButton);
		
		saveButton = new JButton(new ImageIcon(this.getClass().getResource("Icons/save.png")));
		saveButton.setToolTipText("Save the output log messages to a file");
		saveButton.setPreferredSize(new Dimension(Config.iconSize, Config.iconSize));
		saveButton.setBorder(new BevelBorder(BevelBorder.RAISED));
		saveButton.addActionListener(this);
		panel1.add(saveButton);
		
		exitButton = new JButton(new ImageIcon(this.getClass().getResource("Icons/exit.png")));
		exitButton.setToolTipText("Exit");
		exitButton.setPreferredSize(new Dimension(Config.iconSize, Config.iconSize));
		exitButton.setBorder(new BevelBorder(BevelBorder.RAISED));
		exitButton.addActionListener(this);
		panel1.add(exitButton);
		
		panel1.add(new JLabel("     "));
		panel1.add(new JLabel("Verbosity: "));
		verbosityComboBox = new JComboBox();
		verbosityComboBox.addItem("0");
		verbosityComboBox.addItem("1");
		verbosityComboBox.addItem("2");
		verbosityComboBox.setEditable(false);
		verbosityComboBox.setSelectedItem("" + Config.verbosity);
		verbosityComboBox.addActionListener(this);
		panel1.add(verbosityComboBox);
		
	// Set up panel 2
		JPanel panel2 = new JPanel();
		mainPanel.add(panel2);
		panel2.setPreferredSize(new Dimension(Config.frameWidth - 2 * Config.paddingWidth, 2 * Config.buttonHeight + 2 * Config.paddingWidth));
		panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
		panel2.setBorder(new TitledBorder(LineBorder.createGrayLineBorder(), "Input formula"));
		
		inputTextField = new TextField();
		panel2.add(inputTextField);
		inputTextField.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				int key = e.getKeyCode();
				if ( key == KeyEvent.VK_ENTER ) {
					startButton.doClick();
				}
			}
		});
		
	// Set up panel 3
		JPanel panel3 = new JPanel();
		mainPanel.add(panel3);
		panel3.setPreferredSize(new Dimension(Config.frameWidth - 2 * Config.paddingWidth, 9999));
		panel3.setLayout(new FlowLayout());
		panel3.setBorder(new TitledBorder(LineBorder.createGrayLineBorder(), "Output log"));
		panel3.setLayout(new BorderLayout());
		outputTextArea = new JTextArea(10,10);
		outputTextArea.setEditable(false);
		outputTextArea.setFont(new Font("monospaced", Font.PLAIN, 12) );
		panel3.add(new JScrollPane(outputTextArea), BorderLayout.CENTER);
		
	// Set up panel 4
		JPanel panel4 = new JPanel();
		mainPanel.add(panel4);
		panel4.setPreferredSize(new Dimension(Config.frameWidth - 2 * Config.paddingWidth, 2 * Config.buttonHeight + 2 * Config.paddingWidth));
		panel4.setLayout(new FlowLayout(FlowLayout.LEFT));
		panel4.setBorder(new TitledBorder(LineBorder.createGrayLineBorder(), "Rules"));
		
		rulesOptionComboBox = new JComboBox();
		rulesOptionComboBox.addItem("K");
		rulesOptionComboBox.addItem("D");
		rulesOptionComboBox.addItem("T");
		rulesOptionComboBox.addItem("K4");
		rulesOptionComboBox.addItem("B");
		rulesOptionComboBox.addItem("S4");
		rulesOptionComboBox.addItem("S5");
		rulesOptionComboBox.addItem("I");
		rulesOptionComboBox.addItem("P");
		rulesOptionComboBox.addItem("Resolution");
		rulesOptionComboBox.setEditable(false);
		panel4.add(rulesOptionComboBox);
		
		panel4.add(new JLabel("i:"));
		rulesTextField1 = new JTextField();
		rulesTextField1.setPreferredSize(new Dimension(Config.buttonWidth / 2, Config.buttonHeight));
		panel4.add(rulesTextField1);
		panel4.add(new JLabel("j:"));
		rulesTextField2 = new JTextField();
		rulesTextField2.setPreferredSize(new Dimension(Config.buttonWidth / 2, Config.buttonHeight));
		panel4.add(rulesTextField2);
		
		addRulesButton =  new JButton("Add");
		addRulesButton.setPreferredSize(new Dimension(Config.buttonWidth, Config.buttonHeight));
		addRulesButton.setToolTipText("Add a rule");
		addRulesButton.addActionListener(this);
		panel4.add(addRulesButton);
		
		clearRulesButton =  new JButton("Clear");
		clearRulesButton.setPreferredSize(new Dimension(Config.buttonWidth, Config.buttonHeight));
		clearRulesButton.setToolTipText("Clear all rule");
		clearRulesButton.addActionListener(this);
		panel4.add(clearRulesButton);
 		
		panel4.add(new JLabel("     Rules = "));
 		rulesJLabel = new JLabel(Config.show());
 		panel4.add(rulesJLabel);
		

		
	// Set up the main frame
		if ( japplet != null ) {
			japplet.setContentPane(mainPanel);
		} else {
			frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			frame.setContentPane(mainPanel);
			frame.pack();
			frame.setLocationRelativeTo(null);
			frame.show();
		}
	}
	
	public void actionPerformed(ActionEvent e) {
		if ( e.getSource() == exitMenuItem || e.getSource() == exitButton ) {
			System.exit(0);
		} else if ( e.getSource() == addRulesButton ) {
			String selected = (String)rulesOptionComboBox.getSelectedItem();
			if ( selected.equals("I") || selected.equals("P") ) {
				Config.setRule(selected, rulesTextField1.getText(), rulesTextField2.getText(), true);
			} else if ( selected.equals("Resolution") ) {
				Config.setRule("R", "" , true);
				Config.setRule("v", "" , false);
			} else {
				Config.setLogic(selected, rulesTextField1.getText());
			}
			rulesJLabel.setText(Config.show());
		} else if ( e.getSource() == clearRulesButton ) {
			Config.clearRules();
			rulesJLabel.setText(Config.show());
		} else if ( e.getSource() == verbosityComboBox ) {
			Config.verbosity = Integer.parseInt((String)verbosityComboBox.getSelectedItem());
		} else if ( e.getSource() == startButton ) {
			outputTextArea.setText("");
			[color=red]startProver(inputTextField.getText());[/color]
		} else if ( e.getSource() == pauseButton ) {
			if ( pauseProver() ) {
				//addLogMessage("-- Paused --");
			}
		} else if ( e.getSource() == stopButton ) {
			if ( stopProver() ) {
				//addLogMessage("Stopping...");
			}
		} else if ( e.getSource() == clearButton ) {
			inputTextField.setText("");
			outputTextArea.setText("");
		} else if ( e.getSource() == printButton ) {
			try {
				PrinterJob job = PrinterJob.getPrinterJob();
				PageFormat format = job.pageDialog(job.defaultPage());
				job.setPageable(new PageableText(outputTextArea.getText(), format));
				if (job.printDialog()) job.print();
			} catch ( Exception ex ) {
				errorPopup("Printing error: " + ex);
			}
		} else if ( e.getSource() == saveButton ) {
			JFileChooser fc = new JFileChooser((new File(saveFolder)));
			fc.addChoosableFileFilter(new TextFileFilter());
			String filename = null;
			if ( fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION ) {
				filename = fc.getSelectedFile().getPath();
				saveFolder = (new File(filename)).getParent();
				try {
					PrintWriter writer = new PrintWriter(new FileWriter(filename));
					writer.print(outputTextArea.getText());
					writer.close();
				} catch ( Throwable t ) {
					errorPopup("Problem writing file: " + filename);
				}
			}
		}
	}
	
	public void addLogMessage(String message) {
		class AddMessage implements Runnable {
			String message;
			
			public AddMessage(String message) {
				this.message = message;
			}
			
			public void run() {
				outputTextArea.append(message + "\n");
				outputTextArea.setCaretPosition(outputTextArea.getText().length());
			}
		}
		SwingUtilities.invokeLater(new AddMessage(message));
	}
	
	public void errorPopup(String message) {
		final int MAX_MESSAGE_LENGTH = 200;
		if ( message.length() > MAX_MESSAGE_LENGTH ) {
			message = message.substring(0, MAX_MESSAGE_LENGTH - 1) + " ...";
		}
		JOptionPane.showMessageDialog(frame, message, "Error", JOptionPane.ERROR_MESSAGE);
	}
	
	[color=red]public void startProver(String formula) {
		if ( !formula.equals("") ) {
			stopProver();
			prover = new Prover(0, formula, System.out, this);
			prover.start();
		}
	}[/color]	
	public boolean stopProver() {
		if ( prover != null ) {
			prover.interrupt();
			prover = null;
			return true;
		} else {
			return false;
		}
	}
	
	public boolean pauseProver() {
		if ( prover != null ) {
			return prover.pause();
		} else {
			return false;
		}
	}
	
	public void setActivityIcon(boolean on) {
		if ( on ) {
			startButton.setIcon(null);
		} else {
			startButton.setIcon(startIcon);
		}
	}
	
	public void toggleActivityIcon() {
		if ( startButton.getIcon() == null ) {
			setActivityIcon(false);
		} else {
			setActivityIcon(true);
		}
	}
	
	class TextFileFilter extends FileFilter {
		public boolean accept(File file) {
			String filename = file.getName();
			return filename.endsWith(".txt") || file.isDirectory();
		}
		
		public String getDescription() {
			return "Text files (*.txt)";
		}
	}
}
```
das Ist die Gui klasse. Was mich eigentlich interessiert ist nur der inputTextfield. und was er macht wenn man den start button drückt.
und nach dem code zufolge wird dann die methode startProver aufgerufen.

hier noch mal die Prover klasse:


```
import java.io.IOException;
import java.io.PrintStream;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class Prover extends SwingWorker {
	private String termlist;
	private Timer timer1;
	private Timer timer2;
	private long start;
	private PrintStream output;
	private Gui gui;
	private boolean paused;
	private boolean stopped;
	private int nestingLevel;
	
	public Prover(int nestingLevel, String termlist, PrintStream output, Gui gui) {
		this.nestingLevel = nestingLevel;
		this.termlist = termlist;
		this.output = output;
		this.gui = gui;
	}
	
	public Object construct() {
		(timer1 = new Timer()).schedule(new Timeout(this), 1000 * Config.timeout);
		(timer2 = new Timer()).scheduleAtFixedRate(new ActivityFeedback(this, gui), 0, 300);
		try {
			TruthValue result = prove(termlist);
			if ( Main.escherInterface != null ) {
				output.println(nestingLevel+ ":Answer:" + result + ";");
			} else {
				String resultString = result + " [" + ((Calendar.getInstance().getTimeInMillis() - start)/1000.0) + "s]";
				output.println(resultString);
				if ( gui != null ) gui.addLogMessage(resultString);
			}
		} catch ( OutOfMemoryError e ) {
			Debug.message(0, "Memory exhausted");
			interrupt();
			if ( gui != null ) gui.errorPopup("Memory exhausted!");
		}
		return null;
	}
	
	public void finished() {
		if ( stopped ) {
			Debug.message(0, "-- Stopped --");
		}
		if ( timer1 != null ) timer1.cancel();
		if ( timer2 != null ) timer2.cancel();
		if ( gui != null ) gui.setActivityIcon(false);
	}
	
	public void interrupt() {
		stopped = true;
		super.interrupt();
	}
	
	public boolean pause() {
		paused = !paused;
		return paused;
	}
	
	private TruthValue prove(String termlist) {
		start = Calendar.getInstance().getTimeInMillis();
		try {
			TermList l = Term.parseList(termlist);
			Debug.message(1, "Rules: " + Config.show());
			Debug.message(1, "Input: " + termlist);
			Debug.message(2, "Parsed as: " + l);
			Debug.message(2, "Normalised: " + l.normalise() + "\n");

			Tableaux tableaux = new Tableaux(nestingLevel, l.normalise());
			TruthValue result = tableaux.expand();
			Debug.message(1, tableaux.toString());
			return result;
		} catch ( ParseException pe ) {
			if ( Config.showGui ) {
				Main.gui.errorPopup(pe.toString());
			} else {
				Debug.message(0, pe.toString());
			}
		} catch ( Throwable t ) {
			t.printStackTrace();
		}
		return new TruthValue(TruthValue.DONTKNOW);
	}
	
	private class Timeout extends TimerTask {
		Prover prover;
		
		public Timeout(Prover prover) {
			this.prover = prover;
		}
		
		public void run() {
			Debug.message(0, "Timeout");
			prover.interrupt();
		}
	}
	
	private class ActivityFeedback extends TimerTask {
		Prover prover;
		Gui gui;
		
		public ActivityFeedback(Prover prover, Gui gui) {
			this.prover = prover;
			this.gui = gui;
		}
		
		public void run() {
			if ( gui != null ) gui.toggleActivityIcon();
		}
	}
}
```

habe ungefähr folgendes versucht:


```
public class Interface {
public Gui gui;


public static void  input(String eingabe){
	
	gui.startProver(eingabe);
}

public static void main(String[] args) {
input(" []p -> p");
}




}
```
aber beim ausführen gibt er mir ein nullpointer exception.was mache ich falsch.
bin für jede hilfe dankbar.


----------



## SlaterB (8. Feb 2006)

wieso nur versuchst du sowas riesig komplexes wenn du noch nicht mal weißt was eine NullPointerException ist/
wie man ganz elementar mit Objekten umgeht..  

gui.startProver(eingabe); 
gibt natürlich ne Excpetion denn gui ist null/ leer/ gar kein Objek

genau wie im JApplet.init() musst du irgendwann vorher einmal
gui = new Gui(name,japplet); ausführen

da du in diesem Fall kein JApplet hast musst du null als zweiten Parameter übergeben, der erste ist ein beliebiger String,


```
public class Interface {
	public static Gui gui = new Gui("Test",null);

	public static void input(String eingabe) {

		gui.startProver(eingabe);
	}

	public static void main(String[] args) {
		input(" []p -> p");
	}

}
```


----------



## drinkingJava (9. Feb 2006)

oh vielen Dank. hat geklappt


----------

