Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures


Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips


Submit News
Search the site here...

Swing Chapter 26. (Special topics) Swing and CORBA. Easy for reading, Click here!

Custom Search
Swing Chapter 26. (Special topics) Swing and CORBA. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 4/4 

Previous Page Previous Page (3/4)
Subpages: 1. Java 2 and CORBA
2. Creating a CORBA interface
3. Creating a CORBA server
4. Creating a CORBA client

26.4  Creating a CORBA client

Its finally time to take a look at how we can modify our stocks table application from chapter 18 to retrieve data from the CORBA server.

Figure 26.1 Login dialog used to connect to CORBA-enabled remote server.

<<file figure26-1.gif>>

The Code: StocksTable.java

see \Chapter26\1

import java.awt.*;

import java.awt.event.*;

import java.util.*;

import java.io.*;

import java.text.*;

import javax.swing.*;

import javax.swing.border.*;

import javax.swing.event.*;

import javax.swing.table.*;

import dl.*;

import MarketDataApp.*;

import org.omg.CosNaming.*;

import org.omg.CosNaming.NamingContextPackage.*;

import org.omg.CORBA.*;

public class StocksTable extends JFrame


  protected JTable m_table;

  protected StockTableData m_data;

  protected JLabel m_title;

  private String m_name = "CORBA";

  private String m_password = "Swing";

  protected MarketData m_server = null;    // Remote server ref.

  public StocksTable() {

    super("Swing Table [CORBA]");

    setSize(770, 300);

    getContentPane().setLayout(new BorderLayout());

    // Unchanged code

    WindowListener wndCloser = new WindowAdapter() {

      public void windowOpened(WindowEvent e) {

        LoginDialog dlg = new LoginDialog(StocksTable.this);


        if (!dlg.getOkFlag())


        // Connect to the server

        try {

          // create and initialize the ORB

          String[] args = new String[]

            { "-ORBInitialPort", "1250",

              "ORBInitialHost", "localhost" };

          ORB orb = ORB.init(args, null);

          // get the root naming context

          org.omg.CORBA.Object objRef =


          NamingContext ncRef = NamingContextHelper.narrow(objRef);

          // resolve the Object Reference in Naming

          NameComponent nc = new NameComponent("MarketData", "");

          NameComponent path[] = {nc};

          m_server = MarketDataHelper.narrow(ncRef.resolve(path));


        catch (Exception ex) {        






      public void windowClosing(WindowEvent e) {







  // Unchanged code

  public void retrieveData() {

    SimpleDateFormat frm = new SimpleDateFormat("MM/dd/yyyy");

    String currentDate = (m_data.m_date == null ? "7/22/1998" :


    String result = (String)JOptionPane.showInputDialog(this,

      "Please enter date in form mm/dd/yyyy:", "Input",

    JOptionPane.INFORMATION_MESSAGE, null, null,


    if (result==null)


    // Unchanged code


  // Unchanged code

  class LoginDialog extends JDialog


    protected JTextField m_nameTxt;

    protected JPasswordField m_passTxt;

    protected boolean m_okFlag = false;

    public LoginDialog(Frame owner) {

      super(owner, "Login", true);

      JPanel p = new JPanel(new DialogLayout2());

      p.add(new JLabel("Name:"));

      m_nameTxt = new JTextField(m_name, 20);


      p.add(new JLabel("Password:"));

      m_passTxt = new JPasswordField(m_password);


      p.add(new DialogSeparator());

      JButton btOK = new JButton("OK");

      ActionListener lst = new ActionListener() {

        public void actionPerformed(ActionEvent e) {

          m_name = m_nameTxt.getText();

          m_password = new String(m_passTxt.getPassword());

          m_okFlag = true;






      JButton btCancel = new JButton("Cancel");

      lst = new ActionListener() {

        public void actionPerformed(ActionEvent e) {






      p.setBorder(new EmptyBorder(10, 10, 10, 10));




      Dimension d1 = getSize();

      Dimension d2 = owner.getSize();

      int x = Math.max((d2.width-d1.width)/2, 0);

      int y = Math.max((d2.height-d1.height)/2, 0);

      setBounds(x, y, d1.width, d1.height);


    public boolean getOkFlag() {

      return m_okFlag;



  public static void main(String argv[]) {

    new StocksTable();



class ColoredTableCellRenderer extends DefaultTableCellRenderer


  public void setValue(java.lang.Object value) {

    // Unchanged code



class StockData


  // Unchanged code

  public StockData(DataUnit unit) {

    this(unit.getSymbol(), unit.getName(), unit.getLast(),

      unit.getOpen(), unit.getChange(), unit.getChangePr(),




class StockTableData extends AbstractTableModel


  // Unchanged code

  public StockTableData() {

    m_frm = new SimpleDateFormat("MM/dd/yyyy");

    m_vector = new Vector();

    //setDefaultData();        No longer used


  public int retrieveData(java.util.Date date, String name,

   String password, MarketData server) {

    GregorianCalendar calendar = new GregorianCalendar();


    int month = calendar.get(Calendar.MONTH)+1;

    int day = calendar.get(Calendar.DAY_OF_MONTH);

    int year = calendar.get(Calendar.YEAR);

    try {

      DataUnit unit = server.getFirstData(name, password,

        year, month, day);

      boolean hasData = false;

      while (unit != null) {

        if (!hasData) {


            hasData = true;


        m_vector.addElement(new StockData(unit));

        unit = server.getNextData();


      if (!hasData)    // We've got nothing

        return 1;


    catch (Exception e) {


      System.err.println("Load data error: "+e.getMessage());

      return -1;


    m_date = date;

    Collections.sort(m_vector, new

      StockComparator(m_sortCol, m_sortAsc));

    return 0;



// Unchanged code

Understanding the Code

Class StocksTable

Compared to the final stocks table example in chapter 18, we now import two custom packages (dl and MarketDataApp), and three CORBA-related packages.

New instance variables:

String m_name: user login name for authentication.

String m_password: user password for authentication.

MarketData m_server: a reference to the remote server obtained from CORBA.

The WindowAdapter used in this frame class now receives a new method, windowOpened(), which will be invoked when after the frame has been created and dispalyed on the screen (i.e. when setVisible(true) is called). We use this method to display a login dialog (see below). Then we connect to the CORBA server by following the same procedure as described above. Note that an additional property, ORBInitialHost, is passes to the ORB.init() method. This property determines an initial host address which will be checked for the required CORBA server (note that if both a CORBA server and client reside on the same machine, we can omit this property).

A reference to a MarketData is retrieved and stored in our m_server variable. Then the retrieveData() method is called to populate our table with the initial data fetched using the CORBA server. The only change made to this method is that it now sets the initial string for data input before calling JOptionPane.showInputDialog(). The rest of the job is delegated to StockTableData.retrieveData() method, as we did in the chapter 18 example.

Class LoginDialog

This inner class represents a custom modal dialog which allows input of a user name and password for authentication. Our custom DialogLayout2 layout manager (discussed in chapter 4) simplifies the creation of this dialog, which is shown in figure 26.1.

If the "OK" button is pressed, the username and password are retrieved and stored in class variables. It also sets the m_okFlag to true. This flag can be retrieved with the getOkFlag() method and indicates how this dialog was closed (i.e. whether "OK" or "Cancel" was pressed).

Class StockData

This class now receives a new constructor which creates a new StockData object from a DataUnit instance discussed above.

Class StockTableData

This class no longer uses the setDefaultData() method. All data must be retrieved from the remote server. The retrieveData() method now receives three new parameters: user name, password, and a reference to the remote server. This method no longer uses SQL queries to retrieve data, but instead calls the getFirstData() method on the remote server (as we discussed in the last section). Then it repeatedly calls getNextData() until no more data is available. Retrieved data objects are encapsulated in StockData instances and stored in our m_vector collection.

Running the code

At this point you can compile all code and run the Java 2 name server:

    tnameserv -ORBInitialPort 1250

Then run our CORBA server:

    java MarketDataApp.MarketDataServer

...and wait until it displays a message "Waiting for client connection" in the console. In another session, run our CORBA client:

    java StocksTable

Enter the user name and password, "CORBA" and "Swing" respectively (they are displayed by default). Select a date for retrieval of corresponding stock data from the remote CORBA server. This data will be retrieved and displayed in the table.

Note: Don't forget to verify that your database is correctly listed as an ODBC data source. If your server runs across a network, specify it's host while creating ORB object.

Note: We can improve this application's responsiveness during data retrieval by wrapping the associated code in threads. An even more professional application might implement progress bars to let the user know how far along the procedure is.

[ Return to Swing (Book) ]

Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color

[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3

[ More in News Section ]

Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy