Tips and Tricks

 

Action handler for push button
Create a border
Center a screen
Converting Objects to Strings
Exceptions - Creating and using exception classes
Use Dimension to set the height and length of a field
Exit an application when the close button on a frame is pressed
How to work with menus
JOptionPane - Creating a Message boxe
JTextArea
JTextField
JLabel
JTabel
Layouts
 

 

Action handler for push button

JButton myButton = new JButton("Cancel");
myPanel.add(myButton);
showArrayButton.addActionListener(new ActionListener()
  { public void actionPerformed(ActionEvent evt)
    { Do something when the button is pushed......  
    }
  } );

Create a border

To create a border e.g. around a label you nedd to import the classes:

import javax.swing.BorderFactory;
import javax.swing.border.Border;

Types of borders:

Create status label with lowered border:


loweredbevel = BorderFactory.createLoweredBevelBorder();
JLabel statusLabel = new JLabel("Status");
statusLabel.setBorder(loweredbevel);
myPane.add(statusLabel,"South");

 

 

 

Center a screen

You can place this code inside a sub class of JFrame

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);

Converting Objects to Strings

Object types can be converted to strings using the toString method.

private Object[][] myData;

myData = new Object[3][10];

myData[0][0] = "10";
myData[1][0] = "Copper";
myData[2][0] = "1.000";
myData[0][1] = "20";
myData[1][1] = "Iron";
myData[2][1] = "500";
for (int i = 0 ; i <= 9;i++)
 { String lineString = myData[0][i].toString();
 }

Exceptions - Creating and using exception classes

This example shows how to crerate your own exception class. Note trhat a class can throw more than one exceptio, but the they all has to be declared e.g.
myClass throws myException1 myException2.

Note: If you want to view the Exception stack use mException.printStackTrace() :

    try
     { sapConnection1.mConnection.execute(jcoFunction);
     }
    catch (Exception mException)
     { mException.printStackTrace();
     }

 

 

//This class catches the exceptionj
public class YYY
 { public YYY()
   { try
      { XXX myXXX = new XXX();
      }
      catch (Exception mException)
      { .. Do something when the exception occurs
      }

   }


}
// This class throws an exception 
public class XXX
 {

 public XXX() throws MyException
  {  if ..........
      throw new MyException();
     
  }

// Exception class
  class MyException extends Exception
  {
    public MyException()
    { super("My exception occurred");  }

  }
}

 

 

 

Use Dimension to set the height and length of a field

txtDocType = new JTextField("TA");
txtDocType.setMaximumSize(new Dimension(100,Short.MAX_VALUE));
or
txtDocType.setMaximumSize(new Dimension(100,50));

 

Exit an application when the close button on a frame is pressed

To close down the whole applikation when the exit button on the frame (The cross in th upperright corner of the frame) is pressed, use the following code:

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Note that there are other possibillities using the setDefaultCloseOperation method:

How to work with menus

Steps:

  1. Make a subclass of the AbstractActions class to handle events from the menus
  2. Declare actions
  3. Declare menu as JMenu
  4. Add actions to the menu

 

1. Make a subclass of the AbstractActions class to handle events from the menus

The parameter p_name is the text that will be displayed in the menu. The p_Action parameter is a string that indicates which action shoud be taken. Instaed of using one class for all actions, you could define a class for every action or a class for every catehgory of action.

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" )
      System.exit(0);
   else if ( actionType == "OPEN_FILE" )
      System.exit(0);

 }

}

2. Declare actions

The code below declares 3 actions from the menuActions class

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

3. Declare menu as JMenu

JMenu myFileMenu = new JMenu("File");

4. Add action to menu

myFileMenu.add(saveFile);
myFileMenu.add(openFile);
myFileMenu.addSeparator();
myFileMenu.add(exitApp);

JTextArea

Here wee adds a text area to a panel named textPanel. The Text Area will have a vertical scrollbar that is show always, and will have the inutial text "Test" and default 20 columna and 20 rows. Note that the actuial number of column and rows will depends of the layout manager.

    JTextArea 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;
    scrollPane.setVerticalScrollBarPolicy(22);
    textPanel.add(scrollPane,"Center");
    //Add listener - Remember to implement the DocumentListener interface
    textArea.getDocument().addDocumentListener(this);

 

JTextField

A JTextFiled is added to a panel named textPanel..

JTextField textField = new JTextField(20);
textField.setText("Dette er en test tekst");
textPanel.add(textField,"North");

 

JLabel

 

JTabel

Click here to see a working example of a table that reads and saves its data in an array.

Creating a simple table

Object[][] data = {
      {"10", "P-100", "1.000"}
      };

String[] columnNames = {"Item", "Material", "Quantity"};
JTable myTable = new JTable(data, columnNames);
JScrollPane myPane = new JScrollPane(myTable);
myContentPane.add(myPane);

Creating simple table with table model

import javax.swing.table.*;

 

Class ....

 

TableModel myModel = new ItemTable();
JTable myTable = new JTable(myModel);
JScrollPane myPane = new JScrollPane(myTable);
myContentPane.add(myPane);
class ItemTable extends AbstractTableModel
   {
    Object[][] data = {
      {"10", "P-100", "1.000"}
      };

    String[] columnNames = {"Item", "Material", "Quantity"};

    public int getColumnCount() {
        return columnNames.length;
    }

    public int getRowCount() {
        return data.length;
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        return data[row][col];
    }



   }
Table tips
Setting the size of the table
myTable.setPreferredScrollableViewportSize(new Dimension(500,200));

Setting column width

TableColumn column = null;
column = myTable.getColumnModel().getColumn(0);
//column.setPreferredWidth(10);
//column.setWidth(10);
//column.setMinWidth(30);
  column.setMaxWidth(30);

 

 

Layouts

Click here to see an example of how to use the Box layout.

Box layout:

Box vBox = Box.createVerticalBox() or Box vBox = Box.createHorizontalBox()

Adding a filler box to make space between components:

vBox.add(txtPurchOrd);

Dimension minSize = new Dimension(5, 30);
Dimension prefSize = new Dimension(5, 30);
Dimension maxSize = new Dimension(Short.MAX_VALUE, 30);
vBox.add(new Box.Filler(minSize, prefSize, maxSize));

JButton itemsButton = new JButton("Create items");
vBox.add(itemsButton);

This makes a vertical space of 30 between txtPurchOrd and itemsButton.

 

Message box using JOptionPane

JOptionPane.showMessageDialog(this, "Logon ok");

Note: For more complex screens you can program you own dailog boxes Example

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