Question for creating Java Applets

Discussion in 'Software' started by mcpp66, Mar 28, 2005.

  1. mcpp66

    mcpp66 Private E-2

    Below is the code for a program that is provided as practice out of the book I'm using. I have a few questions regarding this code:

    1. I understand that I have to use the import statements so that some built-in classes are available for my program, but doesn't the statement "import java.awt.*;" include "import java.awt.event.*;"? Or does the asterisk not act like a typical wildcard in Windows?

    2. The book's explanation of the words "implements ActionListener" and "addActionListener(this)" wasn't exactly clear to me. Would someone provide a clear explanation please? The book states that "implements ActionListener" prepares the swing applet to accept event messages and "addActionListener(this)" tells with swing applet to expect events to happen. Aren't those the same thing? Also, why is the word "this" a necessary argument to the addActionListener method? Thanks.

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JGreet7 extends JApplet implements ActionListener
    {
    JLabel greeting = new JLabel("Hello. Who are you?");
    Font bigFont = new Font("TimesRoman", Font.ITALIC, 24);
    JButton pressMe = new JButton("Press Me");
    JTextField answer = new JTextField("", 10);
    JLabel personalGreeting = new JLabel("");
    FlowLayout flow = new FlowLayout();

    public void init()
    {
    greeting.setFont(bigFont);
    Container con = getContentPane();
    con.add(greeting);
    con.setLayout(flow);
    con.add(answer);
    con.add(pressMe);
    con.add(personalGreeting);
    pressMe.addActionListener(this);
    answer.addActionListener(this);
    answer.requestFocus();

    }

    public void actionPerformed(ActionEvent thisEvent)
    {
    Object source = thisEvent.getSource();
    if(source == pressMe)
    {
    String name = answer.getText();
    personalGreeting.setText("Hi " + name);
    }

    else if(source instanceof JTextField)
    {
    String name = answer.getText();
    personalGreeting.setText("Hi " + name);
    }
    remove(answer);
    remove(pressMe);
    repaint();
    }
    }
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds