Re: basic GUI question
jrobinss wrote:
[note to andrew: I think I understand what an SSCCE is, and I've spent
some time reducing its size before posting it]
Ok, here's an SSCCE. Its behavior currently is that, upon "start", a
I haven't read your SSCCE yet, but I thought I'd show you my solution. I
notice you have one extra niggle that was mentioned earlier (the
property change listener).
package serverwithgui;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/**
*
* @author Brenden
*/
public class ServerWithGui {
public static void main(String[] args) throws Exception
{
BufferedReader input = new BufferedReader( new InputStreamReader(
System.in ) );
for(;;) {
System.out.print(" cmd> ");
System.out.flush();
String s = input.readLine();
if (s != null) {
if ("start".equals(s)) {
Gui.start();
} else if ("stop".equals(s)) {
Gui.stop();
} else {
System.err.println("Didn't recognize: " + s);
}
} else { // s == null
break; // exit for(;;) loop
}
} // for(;;)
}
}
class Gui {
// Utility class: "start()" and "stop()"
private Gui() {} // non-instantiable, use start and stop methods
private static JFrame jf;
public static void start()
{
startGuiOnEdt();
}
public static void stop()
{
stopGuiOnEdt();
}
private static void startGuiOnEdt()
{
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
createAndShowGui();
}
} );
}
private static void createAndShowGui() {
jf = new JFrame( "Please answer the question.");
JPanel p = new JPanel();
p.add( new Label( "What is your quest?"));
final JTextField f = new JTextField( 20 );
f.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.out.println( f.getText() );
f.setText( "" );
}
} );
p.add( f );
jf.add( p );
jf.pack();
jf.setLocationRelativeTo( null );
jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
jf.setVisible( true );
}
private static void stopGuiOnEdt()
{
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
stopGui();
}
} );
}
private static void stopGui()
{
jf.setVisible( false );
jf.dispose();
jf = null;
}
}