Eileen said:
hey everyone, im doing my science fair project. and my project
calculates the cost of a internal conbustion engine vehicle and an
electric car in different time intervals.
and now i made a jDialog box so when i click run button, it should pop
up the jDialog box, so ppl can input some integers and the program
will use them in the calculation. so how can i make this thing pop up?
Well first, the Java tutorial is a great resource.
<
http://java.sun.com/docs/books/tutorial/uiswing/components/dialog.html>
Next, your basic plan of attack is to add an ActionListener to the
button. That's how you make a button do anything at all. The action
listener should show the dialog, and set the result back to the main window.
Here's a simple example:
class MyInputDialog implements ActionListener
{
MyFrame mainJFrame;
public MyInputDialog( MyFrame output ) {
mainJFrame = output;
}
public void actionPerformed( ActionEvent e )
{
String s = JOptionPane.showInputDialog(
mainJFrame,
"Please input some numbers",
"Your numbers please",
JOptionPane.PLAIN_MESSAGE );
double d;
if( s != null && s.length() > 0 ) {
d = Double.valueOf( s );
mainJFrame.setInput( d );
}
}
}
class MyFrame extends JFrame
{
JTextArea text;
JButton input;
public MyFrame()
{
text = new JTextArea();
input = new JButton( "Click me!");
add( new JScrollPane( text ) );
add( input, BorderLayout.SOUTH );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
pack();
setSize( 400, 300 );
setLocationRelativeTo( null );
}
public void setInput( double d ) {
text.append( String.valueOf( d ) + "\n" );
}
public void addInputButtonListener( ActionListener a ) {
input.addActionListener( a );
}
private static void createAndShowGui() {
MyFrame mine = new MyFrame();
mine.addInputButtonListener( new MyInputDialog( mine ) );
mine.setVisible( true );
}
public static void main( String... args )
{
javax.swing.SwingUtilities.invokeLater( new Runnable() {
public void run() {
createAndShowGui();
} });
}
}