Solved

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

Posted on 2003-11-26
23
534 Views
Last Modified: 2013-11-23
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?
0
Comment
Question by:dkim18
  • 10
  • 7
  • 6
23 Comments
 
LVL 92

Expert Comment

by:objects
ID: 9828847
You need to create a frame in your start() method:

JFrame f = new JFrame();
// add your compoinents to frame
f.pack();
f.show();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9828848
You need to create a JFrame in the applet
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 30 total points
ID: 9828858
JFrame appletFrame;
....


public void init() {
     appletFrame = new JFrame();
     appletFrame.getContentPane().add(new JLabel("Test label"));
     appletFrame.setSize(200, 200);
     appletFrame.setVisible(true);
}
0
 
LVL 92

Expert Comment

by:objects
ID: 9828865
you should read previous posts before posting :)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9828871
I did
0
 
LVL 92

Accepted Solution

by:
objects earned 220 total points
ID: 9828895
thats ok, as long as your copying :)

dkim18,

Here's a more complete outline as to how it needs to be handled.

public MyApplet extends JApplet
{
   private JFrame f;

   public void init()
   {
      f = new JFrame();
      JPanel myPanel = buildPanel();
      appletFrame.getContentPane().add(myPanel);
      f.pack();
   }

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

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

...
}
0
 

Author Comment

by:dkim18
ID: 9828949
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();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9828953
Just combine your init with previous examples
0
 
LVL 92

Expert Comment

by:objects
ID: 9828959
public void init() {    
    f = new JFrame();
    contentPane = f.getContentPane();
    layout = new GridBagLayout();
    contentPane.setLayout(layout);
    constraints = new GridBagConstraints();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 9828977
Does your applet have to have a gui layout of its own anyway?
0
 

Author Comment

by:dkim18
ID: 9829051
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....
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 86

Expert Comment

by:CEHJ
ID: 9829059
>>By the way, I tried to load the applet on ...

which code did you use?
0
 

Author Comment

by:dkim18
ID: 9829292
I used objects' code

public void init() {    
    f = new JFrame();
    contentPane = f.getContentPane();
    layout = new GridBagLayout();
    contentPane.setLayout(layout);
    constraints = new GridBagConstraints();
0
 
LVL 92

Expert Comment

by:objects
ID: 9829324
can u post the rest of the applet code?
0
 

Author Comment

by:dkim18
ID: 9829331
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();
   }
0
 
LVL 92

Expert Comment

by:objects
ID: 9829358
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().
0
 

Author Comment

by:dkim18
ID: 9829362
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



0
 
LVL 92

Expert Comment

by:objects
ID: 9829381
>  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?
0
 

Author Comment

by:dkim18
ID: 9829408
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...
0
 
LVL 92

Expert Comment

by:objects
ID: 9829449
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.
0
 
LVL 92

Expert Comment

by:objects
ID: 9829473
try quitting all browser windows, and reloading applet.
0
 

Author Comment

by:dkim18
ID: 9829522
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!!
0
 
LVL 92

Expert Comment

by:objects
ID: 9829539
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now