Client Implementation
Listing 4.3 GreaterClient.java (Complete code)
import javax.swing.*;
import java.rmi.*;
import java.awt.*;
import java.awt.event.*;
// Client implementation
public class GreaterClient
extends JFrame{
//instance variables
private JTextField txtOne,txtTwo;
private JTextArea txtMessage;
private JLabel lblOne,lblTwo;
private JButton btnCompare;
private GreaterInterface obj;
//constructor
public GreaterClient(){
super("GreaterClient");
//calling method to create components
this.createComponents();
//method to get a remote reference
this.connect();
//setting the default close operation
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Causes this Window to be sized to fit the
//preferred size and layouts of its subcomponents.
pack();
//shows the window
show();
}
//method to create various components
private void createComponents(){
Container cp = getContentPane();
//panels for buttons, textfields.
JPanel
topPanel = new JPanel(new GridLayout(2,2)),
centerPanel= new JPanel(new BorderLayout()),
btnPanel = new JPanel(new GridLayout(1,1));
//text fields for entering numbers
txtOne = new JTextField(5);
txtTwo = new JTextField(5);
lblOne = new JLabel("First Number");
lblTwo = new JLabel("Second Number");
//text area used to show message
txtMessage = new JTextArea(7,25);
//button used to call remote method
btnCompare = new JButton("Compare");
//add an ActionListener to the button.
btnCompare.addActionListener(new ButtonHandler());
//add the components
topPanel.add(lblOne);topPanel.add(txtOne);
topPanel.add(lblTwo);topPanel.add(txtTwo);
centerPanel.add(txtMessage);
btnPanel.add(btnCompare);
cp.add(topPanel,BorderLayout.NORTH);
cp.add(centerPanel);
cp.add(btnPanel,BorderLayout.SOUTH);
}
//method used to connect to the server
private void connect(){
try{
obj = (GreaterInterface)Naming.lookup("Server");
}catch(Exception ex){
txtMessage.setText(ex.getMessage());
}
}
//main method
public static void main(String args[]){
new GreaterClient();
}
//Event handling class
private class ButtonHandler
implements ActionListener{
public void actionPerformed(ActionEvent ae){
try{
//get the value of first text field
int one = Integer.parseInt(txtOne.getText());
//get the value of second text field
int two = Integer.parseInt(txtTwo.getText());
//calling the remote method
String msg = obj.getGreater(one,two);
//shows the value returned by the method
txtMessage.setText(msg);
}catch(Exception ex){
txtMessage.setText("Error: " +ex.getMessage());
}
}
}
}
|