import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import java.io.*; import javax.script.*; class FileIO extends JFrame implements ActionListener { JLabel text; JButton button; JPanel panel; JTextField textField; private boolean _clickMeMode = true; FileIO() { // Begin Constructor text = new JLabel("Text to save to file:"); button = new JButton("Click Me"); button.addActionListener(this); textField = new JTextField(30); panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setBackground(Color.white); getContentPane().add(panel); panel.add(BorderLayout.NORTH, text); panel.add(BorderLayout.CENTER, textField); panel.add(BorderLayout.SOUTH, button); } // End Constructor public void actionPerformed(ActionEvent event){ ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("jruby"); // Enable the JRuby script engine to invoke a script in a file. Invocable inv = (Invocable) engine; Object obj = null; try { // Open a file reader on the external JRuby script file. FileReader f = new FileReader("connectivity.rb"); // Evaluate (execute) the script. engine.eval(f); // This error is thrown when there is a problem in the script. } catch (javax.script.ScriptException e) { System.out.println("Script Exception"); } catch(java.io.FileNotFoundException e) { System.out.println("Cannot write to text.txt"); e.printStackTrace(); } Object source = event.getSource(); if (source == button) { if (_clickMeMode){ try { // Get application data. Object text = textField.getText(); // Invoke write function with text parameter. inv.invokeFunction("write", text); // Invoke read function and get the return value. obj = inv.invokeFunction("read"); } catch (javax.script.ScriptException e) { System.out.println("Script Exception"); String mess = e.getMessage(); System.out.println(mess); } catch (java.lang.NoSuchMethodException e) { System.out.println("No such method"); e.printStackTrace(); } // Clear text field. textField.setText(""); // Display data returned from function. text.setText("Text retrieved from file:"); if(obj.toString() == null) { String empty = null; textField.setText(empty); } else { String s = obj.toString(); textField.setText(s); } button.setText("Click Again"); _clickMeMode = false; } else { text.setText("Text to save to file:"); textField.setText(""); button.setText("Click Me"); _clickMeMode = true; } } } public static void main(String[] args){ FileIO frame = new FileIO(); frame.setTitle("Example"); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; frame.addWindowListener(l); frame.pack(); frame.setVisible(true); } }