Link to home
Start Free TrialLog in
Avatar of dkim18
dkim18

asked on

The applet will load a free-floating top-level window

I am trying to write an applet will be loaded by web browser. The applet HTML page title is Library Applet and it has a heading of Library Applet. The applet will load a free-floating top-level window that contains all your GUI components, So the applet frame is resizable.

My program start with "public class LibraryApplet extends JApplet implements ActionListener{" and it doen't free-floating top-level window.

Can someone give hint or example?
Avatar of Mick Barry
Mick Barry
Flag of Australia image

You need to create a frame in your start() method:

JFrame f = new JFrame();
// add your compoinents to frame
f.pack();
f.show();
You need to create a JFrame in the applet
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you should read previous posts before posting :)
I did
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dkim18
dkim18

ASKER

My code is something like this.
How do I create a JFrame in the applet ?(Sorry for my ignorance.)

public class LibraryApplet extends JApplet implements ActionListener{
...
...
...

 public void init() {    
    contentPane = getContentPane();
    layout = new GridBagLayout();
    contentPane.setLayout(layout);
    constraints = new GridBagConstraints();
Just combine your init with previous examples
public void init() {    
    f = new JFrame();
    contentPane = f.getContentPane();
    layout = new GridBagLayout();
    contentPane.setLayout(layout);
    constraints = new GridBagConstraints();
Does your applet have to have a gui layout of its own anyway?
Avatar of dkim18

ASKER

Now, I think a my gui layout is under frame. I don't see any components.
By the way, I tried to load the applet on web browser and it wasn't free-floating top-level window. I am not sure it is related to layout problem....
>>By the way, I tried to load the applet on ...

which code did you use?
Avatar of dkim18

ASKER

I used objects' code

public void init() {    
    f = new JFrame();
    contentPane = f.getContentPane();
    layout = new GridBagLayout();
    contentPane.setLayout(layout);
    constraints = new GridBagConstraints();
can u post the rest of the applet code?
Avatar of dkim18

ASKER

I tried below code and now I have two seperate frame and I see the components on Frame I think. (the size was minimized, so i had to enlarged in order to see all components.)
On web browser, nothing has been changed.

 public void init()
   {
     f = new JFrame();
    contentPane = f.getContentPane();
    layout = new GridBagLayout();
    contentPane.setLayout(layout);
    constraints = new GridBagConstraints();
      f.pack();
   }

   public void start()
   {
      // applet is loaded so popup frame
      f.show();
   }

   public void stop()
   {
      // applet is unloaded so hide frame
      f.hide();
   }
There are no components being added in that code you posted, where do you add the components? You should be adding them to f.getContentPane().
Avatar of dkim18

ASKER

This is my LibraryApplet.java file.
---------------------------------------

package dkim18.library;

//java extension and core packages
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.net.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.lang.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;

/**
 * Library class is used to imiates Tech Library in project
 * description
 *
 *
 */
public class LibraryApplet extends JApplet implements ActionListener{

  private String[] name_office;               //patron string array for public func
  private String[] patronsArr;                //patron string array for public init
  private Container contentPane;              //content pane
  private JButton checkoutBtn;                //check out button
  private JButton checkinBtn;                 //check in button
  private GridBagLayout layout;               //GridBagLayout layout
  private GridBagConstraints constraints;     //GridBagConstraints constraints
  private JList patronsList;                  //patrons list;
  private JList bookList;                     //book list
  private JList logList;                      //log list
  private JLabel patronsLabel;                //patrons label
  private JLabel bookLabel;                   //available book label
  private JLabel logLabel;                    //log entry label
  private Vector vecBookAuthor;               //Book by Author vector
  private Vector vecLog;                      //log entry record vector
  private Vector recordVec;                   //record book and author vector
  private Calendar gc;                        //Calendar for check out date
  private JFrame f;

  /**
   * Initializes all privates and constructs frames, panel and
   * components
   */
  public void init() {

     
     f = new JFrame();
  contentPane = f.getContentPane();
  layout = new GridBagLayout();
  contentPane.setLayout(layout);
  constraints = new GridBagConstraints();
  f.pack() ;


      vecLog  = new Vector();
    recordVec = new Vector();

    //instantiate GregorianCalendar
    gc = new GregorianCalendar();

    //Book book= new Book();
    //Employees employee = new Employees();

    //read in patrons book record from file
    //vecBookAuthor = book.readBookFile();
    //patronsArr = employee.readEmployeeFile();
    vecBookAuthor = readBookFile();
    patronsArr = readEmployeeFile();

    //instantiate text for buttons and read in imges
    String[] BUTTON_NAMES = {"Check Out","Check In"};
    Icon[] icons = getButtonIcons();
    JPanel buttonHolder = new JPanel();
    checkoutBtn = new JButton(BUTTON_NAMES[0], icons[0]);
    checkinBtn = new JButton(BUTTON_NAMES[1], icons[1]);

    //set button mode to disabled
    checkoutBtn.setEnabled(false);
    checkinBtn.setEnabled(false);

    //instantiate patrons list its mode
    patronsList = new JList(patronsArr);
    patronsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    //instantiate book list and its mode
    //sortVector(vecBookAuthor);
    bookList = new JList(vecBookAuthor);
    bookList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    //instantiate log list and its mode
    logList = new JList();
    logList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    //instantiate patrons list and sets label text
    logLabel = new JLabel("Log Entries(by book title):");
    logList.add(logLabel);

    //handles mouse event to detect patrons and book list selection
    MouseListener mouseListener = new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {

        if ( (! (bookList.isSelectionEmpty())) &&
            (! (patronsList.isSelectionEmpty()))) {
          if (e.getClickCount() == 1) {
            checkoutBtn.setEnabled(true);
            checkinBtn.setEnabled(false);
          }
        }
        if (!logList.isSelectionEmpty()) {
          if (e.getClickCount() == 1) {
            checkoutBtn.setEnabled(false);
            checkinBtn.setEnabled(true);
          }
        }
      }
    };

    //add mouse listener for three lists
    patronsList.addMouseListener(mouseListener);
    bookList.addMouseListener(mouseListener);
    logList.addMouseListener(mouseListener);

    //add mouse listener for two buttons
    checkinBtn.addActionListener(this);
    checkoutBtn.addActionListener(this);

    //instantiate three JPanels
    JPanel libraryPanel = new JPanel(new GridLayout(1, 2));
    JPanel patronsPanel = new JPanel(new BorderLayout());
    JPanel bookPanel = new JPanel(new BorderLayout());

    //instantiate library panel's border and scrollpane
    libraryPanel.add(bookPanel, BorderLayout.BEFORE_FIRST_LINE);
    JScrollPane bookJSP = new JScrollPane(bookList);
    patronsPanel.add(bookJSP);

    //instantiate library panel's border and scrollpane
    libraryPanel.add(patronsPanel, BorderLayout.BEFORE_FIRST_LINE);
    JScrollPane patronsJSP = new JScrollPane(patronsList);
    bookPanel.add(patronsJSP);

    //instantiate patrons and book labels and its location
    patronsLabel = new JLabel("Patrons:");
    bookLabel = new JLabel("Available Books:");
    bookPanel.add(patronsLabel, BorderLayout.BEFORE_FIRST_LINE);
    patronsPanel.add(bookLabel, BorderLayout.BEFORE_FIRST_LINE);

    //instantiate check out panel, mode, border and label
    JPanel checkoutlogPanel = new JPanel(new BorderLayout());
    checkoutlogPanel.add(new JScrollPane(logList));
    checkoutlogPanel.add(logLabel, BorderLayout.BEFORE_FIRST_LINE);
    libraryPanel.setBorder(new TitledBorder(new EtchedBorder(), "In-Library"));

    //set library panel
    constraints.weightx = 1000;
    constraints.weighty = 1;
    constraints.fill = GridBagConstraints.BOTH;
    addComponent(libraryPanel, 0, 0, 5, 6);

    //set library panel
    constraints.weightx = 0;
    constraints.weighty = 0;
    constraints.fill = GridBagConstraints.NONE;
    addComponent(checkoutBtn, 5, 2, 1, 1);

    //set check in button
    constraints.weightx = 0;
    constraints.weighty = 0;
    constraints.fill = GridBagConstraints.NONE;
    addComponent(checkinBtn, 5, 3, 1, 1);

    checkoutlogPanel.setBorder(new TitledBorder(new EtchedBorder(),
                                        "Check-out Log"));
    //set check out button
    constraints.weightx = 1000;
    constraints.weighty = 1;
    constraints.fill = GridBagConstraints.BOTH;
    addComponent(checkoutlogPanel, 6, 0, 1, 6);

    //set menu bar, JMenu and file menu
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu fileMenu = new JMenu("File");
    menuBar.add(fileMenu);
    JMenuItem closeW = new JMenuItem("Exit");
    closeW.getMinimumSize() ;
    fileMenu.add(closeW);

    //set action command for exit menu
    closeW.setActionCommand("closeWindow");
    closeW.addActionListener(this) ;
  }
  public void start()
    {
       // applet is loaded so popup frame
       f.show();
    }

    public void stop()
    {
       // applet is unloaded so hide frame
       f.hide();
    }

  /**
   * Reads in image icons from specfied location
   *
   * @return : array of Icon
   */
  private Icon[] getButtonIcons() {
    final String IMG_DIR = "/images/";
    final String[] IMAGE_NAMES = {"CheckOut.gif", "CheckIn.gif"};
    Icon[] icons = new Icon[IMAGE_NAMES.length];

    try {
      for (int i=0; i < IMAGE_NAMES.length; i++) {
        URL imageUrl = getClass().getResource(IMG_DIR + IMAGE_NAMES[i]);
          icons[i] = new ImageIcon(getImage(imageUrl));
        }
     }catch (Exception e) {
        System.out.println(e);
     }
     return icons;
  }

  /**
   * Provides column, row, width and height for GridBagLayout
   * @param : column, row, width and height
   */
  private void addComponent(Component component,
                            int column, int row, int width, int height) {

    // set gridx and gridy
    constraints.gridx = column;
    constraints.gridy = row;

    // set gridwidth and gridheight
    constraints.gridwidth = width;
    constraints.gridheight = height;

    // set constraints and add component
    layout.setConstraints(component, constraints);
    contentPane.add(component, constraints);
  }

  /**
   * Controls check-in and check-out action event
   * For check-out, when one list is selected from each patron list
   * and book list, proceed check-out process
   *
   * For check-in, when one log list is selected, proceed
   *
   * @param : ActionEvent event
   */
  public void actionPerformed(ActionEvent event){
    if ("closeWindow".equals(event.getActionCommand())) {
      //System.exit(0) ;
    }

    if((patronsList.getSelectedIndex() != -1)&&(bookList.getSelectedIndex() != -1)){

      //get selected lists
      String patron = patronsList.getSelectedValue().toString();
      String book = bookList.getSelectedValue().toString();
      Object bookName = bookList.getSelectedValue();

      //construnt log entry, insert and remove book
      String log = makeLogEntry(patron, book);
      insertLogEntry(log);
      vecBookAuthor.removeElement(bookName);

      //reset book and patron list disable check out button
      bookList.setListData(vecBookAuthor);
      patronsList.setListData(patronsArr);
      recordVec.add(bookName);
      checkoutBtn.setEnabled(false);
    }

    if(logList.getSelectedIndex() != -1){

      int splitLocation = 0;

      String bookName = "";
      String authorName = "";
      String bookAuthor = "";

      //get selected list from log entry list remove and reset
      String log = logList.getSelectedValue().toString() ;
      Object logObj = logList.getSelectedValue() ;
      vecLog.removeElement(logObj);
      logList.setListData(vecLog);

      //re map book title and author name
      splitLocation = log.indexOf("out");
      bookName = log.substring(0, splitLocation);
      authorName = getAuthorName(bookName);
      bookAuthor = bookName + "by" + authorName;

      //insert book and disable check in button
      insertBook(bookAuthor);
      checkinBtn.setEnabled(false);
    }
 }

 /**
  * Get author name according to book name
  * Book name is passed in
  * Returns author name
  *
  * @param : string book
  * @return : author name
  */
  public String getAuthorName(String book){
     int splitLocation = 0;
     String bookName = null;
     String authorName = null;
     String bookAuthor = null;

     for(int i = 0; i < recordVec.size()  ; i++){
       bookAuthor = recordVec.remove(i).toString() ;
       splitLocation = bookAuthor.indexOf("by");
       bookName = bookAuthor.substring(0, splitLocation);

       if(bookName.equals(book)) {
        authorName = bookAuthor.substring(splitLocation+2);
     }
    }
     return authorName;
  }

  /**
   * Records log entry into log vector alphabetical order
   * Parameter: log entry
   *
   * @param : log entry
   */
  public void insertLogEntry(String logRecord){
    vecLog.add(logRecord);
    sortVector(vecLog);
    logList.setListData(vecLog) ;
  }

  /**
  * Retruns book from log entry and sorts book vector
  * Parameter: book name
  *
  * @param : book
  */
  public void insertBook(String book){
    vecBookAuthor.add(book);
    sortVector(vecBookAuthor);
    bookList.setListData(vecBookAuthor) ;
  }

  /**
   * Sorts book vector and log vector.
   * Vector is passed in as a parameter
   *
   * @param : vector
   */
  public void sortVector(Vector vec){
    Object temp[] = new String[vec.size()];
    for(int n = 0; n < temp.length; n++){
      temp[n]  = vec.elementAt(n) ;
    }
    Arrays.sort(temp);
    vec.removeAllElements();
    for(int i = 0; i < temp.length ; i++){
      vec.add(temp[i].toString() );
    }
  }

  /**
   * Construct log entry for each time when check-out book
   * employee name and book title are passed in
   *
   * @param : patron and book string
   * @return : completed log entry
   */
  public String makeLogEntry(String patron, String book) {
    int splitLocation = 0;
    String bookName = null;
    String patronName = null;
    String logEntry = null;

    StringBuffer buffer = new StringBuffer(gc.get(Calendar.MONTH)+1 +"/"+
                 gc.get(Calendar.DATE )+ "/" +gc.get(Calendar.YEAR));
    String time = buffer.toString() ;

    splitLocation = book.indexOf("by");
    bookName = book.substring(0, splitLocation);

    splitLocation = patron.indexOf("at");
    patronName = patron.substring(0, splitLocation);

    logEntry = bookName + "out by " + patronName +" on "+ time;
    return logEntry;
  }



 /**
  * Read in employee.txt file and returns String array that contain
  * each line of the file
  *
  * @return : string array
  * @throws :IOException (one throws tag for each exception)
  */
  public String[] readEmployeeFile(){
    final int EMPLOYEE_NUM = 6;
    int counter =0;
    String[] name_office = new String[EMPLOYEE_NUM];
    BufferedReader inFile = null;

    try {

     Properties props = new Properties();
     props.load(this.getClass().getResourceAsStream("/config/library.properties"));
     String employeeResource = props.getProperty("employees");
     inFile = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(employeeResource)));

      String line = null;
      String name = null;
      String office = null;
      int splitLocation = 0;

      while((line = inFile.readLine()) != null) {
        splitLocation = line.indexOf('|');
        name = line.substring( 0, splitLocation) ;
        office = line.substring( ++splitLocation) ;
        line = name + " at " + office;
        name_office[counter] = line;
        counter++;
      }
  }catch (IOException e) {
    System.out.println(e);
  }
  return name_office;
}

/**
 * Read in book.txt file and returns Vector that contain each line of the file
 *
 * @return: book vector
 * @throws :IOException (one throws tag for each exception)
 */

  public Vector readBookFile() {
    Vector vector = new Vector();
    BufferedReader inFile = null;
    String line = null;

    try {
      Properties props = new Properties();
      props.load(this.getClass().getResourceAsStream("/config/library.properties"));
      String bookResource = props.getProperty("books");

      inFile = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(bookResource)));
      String book = null;
      String author = null;
      int splitLocation = 0;
      int i = 0;

      while ( (line = inFile.readLine()) != null) {
        splitLocation = line.indexOf('|');
        book = line.substring(0, splitLocation);
        author = line.substring(++splitLocation);
        line = book + " by " + author;
        vector.add(line);
        i++;
      }
    }catch (IOException e) {
    System.out.println(e);
  }
  return vector;
 }


}//end of class



>  f.pack() ;

Move this call to the end of the init() method.

You appear to be adding components to the frame. Are u saying the components are appearing in the applet and not the frame?
Avatar of dkim18

ASKER

You appear to be adding components to the frame. Are u saying the components are appearing in the applet and not the frame?
>>Yes, the components are appearing in the applet. Sorry, if I mislead you...
I can't see anywhere in that code where components are added to the applet. Are u sure thats the code you're running and that you're not running an old cached version.
try quitting all browser windows, and reloading applet.
Avatar of dkim18

ASKER

By moving  f.pack() ; to the end of the init() method, I do see free-floating top-level window on the web browser!!
I just need to move File menu to Frame, addng heading of Library Applet and centering location of buttons.

Thank you so much!!