User Interface Components with Swing

 

This example shows the use of the following features:

 

 

//----------------------------------------------------------------------
// buttonPanel class. Panel that contains the pushbuttons
//----------------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;



public class buttonPanel extends JPanel
{
  public buttonPanel()
  {
   Action saveFile = new menuActions("Save","SAVE_FILE");
   Action openFile = new menuActions("Open","OPEN_FILE");
   Action exitApp = new menuActions("Exit","EXIT_APP");

   openButton = new JButton(openFile);
   saveButton = new JButton(saveFile);
   exitButton = new JButton(exitApp);

   add(openButton);
   add(saveButton);
   add(exitButton);


  }
  private JButton openButton;
  private JButton saveButton;
  private JButton exitButton;
}
//----------------------------------------------------------------
// menuActions class
// General action handler for menus and pushbuttons.
// Uses the parameter p_Action to determine what
// action should be carried out
//----------------------------------------------------------------

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class menuActions extends AbstractAction
{

  public menuActions(String p_name,String p_Action)
  { putValue(Action.NAME, p_name);
    putValue("myAction", p_Action);
  }

 public void actionPerformed(ActionEvent evt)
 { String actionType = (String)getValue("myAction");

   if ( actionType == "EXIT_APP" )
     System.exit(0);
   else if ( actionType == "SAVE_FILE" )
//    When a file is saved the Save menu is disabled
      Test_it.frame1.ChangeFileMenuState(0,false);
   else if ( actionType == "OPEN_FILE" )
//    This functionality is not impelmented
      System.exit(0);
 }

}

 

//----------------------------------------------------------------
// myFrame class. 
//----------------------------------------------------------------

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;


public class myFrame extends JFrame implements DocumentListener, ActionListener

{ public myFrame()
  {
    //------------------------------------------------------------
    //Set size of window and center it on the screen
    //------------------------------------------------------------
     setSizeAndPosition();


    //------------------------------------------------------------
    //To avoid writing all the code for the WindowsListener interface
    //to implement Exit of the application, you can avoid the
    //WindowsListener interface by writing this code
    //------------------------------------------------------------
    addWindowListener(new WindowAdapter()
      {  public void windowClosing(WindowEvent e)
         { System.exit(0);
         }
      } );

       Container myContentPane = getContentPane();

    //------------------------------------------------------------
    //  Add buttons
    //------------------------------------------------------------
    buttonPanel bPanel = new buttonPanel();
    myContentPane.add(bPanel,BorderLayout.NORTH);

    //------------------------------------------------------------
    //  Add menus
    //------------------------------------------------------------

    Action saveFile = new menuActions("Save","SAVE_FILE");
    Action openFile = new menuActions("Open","OPEN_FILE");
    Action exitApp = new menuActions("Exit","EXIT_APP");


    myFileMenu = new JMenu("File");
    myFileMenu.add(saveFile);
    myFileMenu.add(openFile);
    myFileMenu.addSeparator();
    myFileMenu.add(exitApp);

    //Save menu is initialized as disabled.
    //It will first be enabled when a text has changed
    saveFile.setEnabled(false);

    JMenuBar MenuBar = new JMenuBar();
    MenuBar.add(myFileMenu);
    setJMenuBar(MenuBar);

    //------------------------------------------------------------
    //  Add a Textfield and a label + a TextArea field
    //  here we have to add two extra panels to place the fields
    //  as we want. In the center of the contentpane, we place
    //  a new panel named textPanel with a border layout. In the North of
    //  textPanel  we palce a new panel named titelPanel with Flow layout,
    //  and place the JLabel and the JTextFiled in it. In the center of
    //  textPanel we place the JTextArea field.
    //------------------------------------------------------------

    // Create layout for the textPanel
    BorderLayout textPanelLayout = new BorderLayout();
    textPanelLayout.setVgap(10);

    //Create textPanel and add it to the CENTER of the content pane
    JPanel textPanel = new JPanel();
    textPanel.setLayout(textPanelLayout);
    myContentPane.add(textPanel,BorderLayout.CENTER);

    //Create titelPanel and add it to the north of the textpanel.
    //Note that it is not necessary to use a layout, as the default layout
    //for a panel is Flow
    JPanel titelPanel = new JPanel();
    textPanel.add(titelPanel,"North");

    //Create label and add it to titelPanel
    JLabel myLabel = new JLabel("Titel: ");
    titelPanel.add(myLabel);

    //Create TextField and add it to titelPanel
    JTextField textField = new JTextField(50);
    textField.setText("Dette er en test tekst");
    titelPanel.add(textField);

    //--Add TextArea field
    textArea = new JTextArea("Test",20,20);
    textArea.setLineWrap(true);  //Wordwrap on
    //Make scrollbar and always show it
    JScrollPane scrollPane = new JScrollPane(textArea);

    //int VERTICAL_SCROLLBAR_ALWAYS = 22 (This constant does not work why ?)
    scrollPane.setVerticalScrollBarPolicy(22);
    textPanel.add(scrollPane,"Center");

    //Add listeners to textField and textArea field
    textField.getDocument().addDocumentListener(this);
    textArea.getDocument().addDocumentListener(this);


    //Add Checkboxes for Bold font
    JPanel checkboxPanel = new JPanel();
    myContentPane.add(checkboxPanel,BorderLayout.SOUTH);
    checkBox1 = new JCheckBox("Bold");
    checkboxPanel.add(checkBox1);
    checkBox1.addActionListener(this);

    //Add radiobutons for coolor of TeaxtArea
    ButtonGroup colorGroup = new ButtonGroup();

    blackButton = new JRadioButton("Black",true);
    redButton   = new JRadioButton("Red",false);
    yellowButton   = new JRadioButton("Yellow",false);

    colorGroup.add(blackButton);
    colorGroup.add(redButton);
    colorGroup.add(yellowButton);

    checkboxPanel.add(blackButton);
    checkboxPanel.add(redButton);
    checkboxPanel.add(yellowButton);

    blackButton.addActionListener(this);
    redButton.addActionListener(this);
    yellowButton.addActionListener(this);

//  Adds a border arpobnd the button panel bPanel and the
//  panel for radiobuttons and cehckboxes checkboxPanel.
//  Note that the one is sunken, and the other raised.
//  There are also a other types of border than BevelBorder
    Border bevel0 = BorderFactory.createBevelBorder(0);
    Border bevel1 = BorderFactory.createBevelBorder(1);
    checkboxPanel.setBorder(bevel1);
    bPanel.setBorder(bevel0);

  }


 //----------------------------------------------------------------
 // ActionListener methods
 //----------------------------------------------------------------
 public void actionPerformed(ActionEvent evt)
 { Object source = evt.getSource();
   // Handle changes of the Font checkbox
   // If it is the first time the checkbox is
   // is changed, save the current font
    if (normalFont == null)
      normalFont = textArea.getFont();

    if (source == checkBox1)
    {  if (checkBox1.isSelected())
         textArea.setFont(new Font("Serif", Font.BOLD,20));
       else
         textArea.setFont(normalFont);
    }

    //Handle events from the radiobutton group
    if (source == blackButton)
      textArea.setForeground(Color.black);
    else if (source == redButton)
      textArea.setForeground(Color.red);
    else if (source == yellowButton)
      textArea.setForeground(Color.yellow);


 }

 //----------------------------------------------------------
 // The 3 methods from the DocumentListener interface
 // When a text is changed, the DocumentListener
 // will enable the Save button
 //----------------------------------------------------------
  public void insertUpdate(DocumentEvent evt)
  { ChangeFileMenuState(0,true);

  }
  public void removeUpdate(DocumentEvent evt)
  { ChangeFileMenuState(0,true);
  }
  public void changedUpdate(DocumentEvent evt)
  { // Will never be called from a textfield
  }



//---------------------------------------------------------
//Set window properties and center the frame on the screen
//---------------------------------------------------------
  private void setSizeAndPosition()
  { 
    setSize(800,600);
    setTitle("Event handling");

    //Center the window
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = this.getSize();
    if (frameSize.height > screenSize.height) {
      frameSize.height = screenSize.height;
    }
    if (frameSize.width > screenSize.width) {
      frameSize.width = screenSize.width;
    }
    this.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);


    //Change look and feel to Windows
      try
        { //Call the static setLookAndFeel method and give it the name of the
          //look and feel you want
          UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
          //Refresh components
          SwingUtilities.updateComponentTreeUI(this);
         }
       catch(Exception e) {}

  }


  //--------------------------------------------------------------------------
  // This method enables/disables menu items in the file menu
  //--------------------------------------------------------------------------
  public void ChangeFileMenuState(int index,boolean newState)
  { JMenuItem item = myFileMenu.getItem(index);
    if (newState == true)
      item.setEnabled(true);
    else if (newState == false)
      item.setEnabled(false);
  }

// Class level variables
   private JMenu myFileMenu;
   private JCheckBox checkBox1;
   private JTextArea textArea;
   private Font normalFont;
   private JRadioButton blackButton;
   private JRadioButton redButton;
   private JRadioButton yellowButton;


}
//--------------------------------------------------------------------------
// Test the thing
//--------------------------------------------------------------------------
public class Test_it
{ public static void main(String[] args)
  { frame1 = new myFrame();
    frame1.show();
  }
//We have to be able to reference the frame from other classes
  public static myFrame frame1;

}

 

 

 

 

Converted from CHM to HTML with chm2web Standard 2.7 (unicode)