/* Simple GUI class for displaying and reading text */ import javax.swing.*; import java.awt.*; import java.awt.Graphics; import java.awt.event.*; import java.io.*; import java.net.*; public class plaingui extends JFrame implements ActionListener { public JTextArea outputarea; // multi-line editible areas public JTextField inputfield; // single line editible area public JScrollPane scroller; // to make an element scrollable public JButton clearbutton; // clears fields public JLabel il, ol; public int x, y, w, h; // window position and size public plaingui(int x0, int y0, int w0, int h0) { x=x0; y=y0; w=w0; h=h0; outputarea = new JTextArea(""); inputfield = new JTextField(w-20); scroller = new JScrollPane(outputarea); clearbutton = new JButton("Clear"); il = new JLabel("Input:"); ol = new JLabel("Output:"); scroller.setBounds(5,30,w-20,h-150); ol.setBounds(5,10,60,20); il.setBounds(5,h-110,w-20,20); inputfield.setBounds(5,h-90,w-20,30); clearbutton.setBounds(w/3,h-50,w/3,20); Container pane = this.getContentPane(); pane.setLayout(null); pane.add(scroller); pane.add(inputfield); pane.add(il); pane.add(ol); pane.add(clearbutton); inputfield.addActionListener(this); clearbutton.addActionListener(this); this.setBounds(x,y,w,h); outputarea.setEditable(false); this.setVisible(true); inputfield.requestFocus(); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } // constructor public void actionPerformed(ActionEvent e) { try { if (e.getSource() == clearbutton) { inputfield.setText(""); outputarea.setText(""); } else { // can also use callback, but then need special interface wakeinput(); } } catch (Exception ee) {} } // actionPerformed. /* When inputfield.getText() is called, it does not wait for the user to hit return. It simply returns what it finds there at the moment. This is probably not the desired behavior. The following synchronization mechanisms will improve on this: */ private String inputtext = ""; public synchronized String getinput(String prompt) { try { if (prompt!=null) il.setText(prompt); wait(); } catch (InterruptedException e) {System.out.println(e);} return inputtext; } // getinput // the following method is called form actionPerformed: private synchronized void wakeinput() { notifyAll(); il.setText("Input:"); inputtext = inputfield.getText(); inputfield.setText(""); // clear }// wakeinput // convenient output call: public void println(String s) { outputarea.append(s+"\n"); } /* sample usage: public static void main(String[] args) { plaingui p = new plaingui(40,200,300,400); // makes gui at position 40,200, width 300, height 400 p.println("Hello, it's me!\n"); String s = p.getinput("say something:"); p.println("what does "+s+ " mean?"); } */ } // plaingui