 |
|
|
OptionsDialog.java
|
/*
* Author: Havard Rast Blok
* E-mail: 
* Web : www.rememberjava.com
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class OptionsDialog extends JDialog implements ChangeListener, ActionListener
{
public OptionsDialog()
{
JTabbedPane tabs;
JPanel p1, p2;
//set up basic GUI
p1 = makeGameOptions();
p2 = makeFileOptions();
tabs = new JTabbedPane();
tabs.addTab("Game", p1 );
tabs.addTab("File", p2 );
getContentPane().add(tabs);
pack();
}
private JPanel makeGameOptions()
{
JPanel ans;
JLabel l1, l2;
JSpinner spinner;
JComboBox cb;
//create components...
ans = new JPanel( new GridLayout( 2, 2 ) );
l1 = new JLabel( "Speed" );
l2 = new JLabel( "Rules" );
spinner = new JSpinner();
cb = new JComboBox( new String[]{ "Play by the rules", "No rules" } );
//set names
spinner.setName( "speed" );
cb.setName( "rules" );
//add change listeners
spinner.addChangeListener( this );
cb.addActionListener( this );
//.. and add them
ans.add(l1);
ans.add(spinner);
ans.add(l2);
ans.add(cb);
return ans;
}
private JPanel makeFileOptions()
{
JPanel ans;
JCheckBox check;
JLabel l1;
JSlider slider;
//create components...
ans = new JPanel( new GridLayout( 3, 1 ) );
check = new JCheckBox( "Autosave files" );
l1 = new JLabel( "File size limit" );
slider = new JSlider( 0, 5 );
//set names
check.setName( "autosave" );
slider.setName( "fileLimit" );
//add change listeners
check.addChangeListener( this );
slider.addChangeListener( this );
//and add
ans.add( check );
ans.add( l1 );
ans.add( slider );
return ans;
}
private void getEventValue( EventObject e )
{
Object src;
String value, name;
src = e.getSource();
name = ((Component)src).getName();
value="";
//AbstractButton - isSelected()
//JSlider - getValue()
//JSpinner - getValue() (Object) casts into a Number for the NumberModel
if( src instanceof AbstractButton )
{
value = ""+((AbstractButton)src).isSelected();
}
else if( src instanceof JSlider )
{
value = ""+((JSlider)src).getValue();
}
else if( src instanceof JSpinner )
{
value = ""+((JSpinner)src).getValue();
}
else if( src instanceof JComboBox )
{
value = ""+((JComboBox)src).getSelectedIndex();
}
System.out.println( "name: "+name+", value="+value );
}
//method from ChangeListener
public void stateChanged(ChangeEvent e)
{
getEventValue(e);
}
//method from ActionListener
public void actionPerformed( ActionEvent e )
{
getEventValue(e);
}
public static void main( String args[])
{
//show the dialog
JDialog d = new OptionsDialog();
d.show();
}
}
|
|
|
 |