Hot questions for Using Applets in japplet

Question:

I'm trying to develop an applet in NetBeans which can read the MAC address.

So here is my directory structure

Here is my UPDATED Code

MacAddrApplet.java

import java.awt.Graphics;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.swing.JApplet;

/**
 *
 * @author jay.patel
 */
public class MacAddressApplet extends JApplet {

    public static String getMacFromInterface(NetworkInterface ni) throws SocketException {
        byte mac[] = ni.getHardwareAddress();

        if (mac != null) {
            StringBuilder macAddress = new StringBuilder("");
            String sep = "";
            for (byte o : mac) {
                macAddress.append(sep).append(String.format("%02X", o));
                sep = ":";
            }
            return macAddress.toString();
        }

        return "";
    }

    public static String[] getInterfaces() {
        try {
            Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();

            ArrayList<String> result = new ArrayList<String>();
            while (nis.hasMoreElements()) {
                NetworkInterface ni = nis.nextElement();
                if (ni.isUp() && !ni.isLoopback() && !ni.isVirtual()) {
                    String mac = getMacFromInterface(ni);
                    String str = ni.getDisplayName() + ";" + mac;
                    result.add(str);
                }
            }
            return result.toArray(new String[0]);
        } catch (SocketException e) {
            System.out.println("SocketException:: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("Exception:: " + e.getMessage());
        }

        return new String[0];
    }

    public static String getInterfacesJSON() {
        try {
            String macs[] = getInterfaces();

            String sep = "";
            StringBuilder macArray = new StringBuilder("['");
            for (String mac : macs) {
                macArray.append(sep).append(mac);
                sep = "','";
            }
            macArray.append("']");

            return macArray.toString();
        } catch (Exception e) {
            System.out.println("Exception:: " + e.getMessage());
        }

        return "[]";
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
         AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                String macs[] = getInterfaces();

                for (String mac : macs) {
                    System.out.println(" Interfaces = " + mac);
                }

                System.out.println(" Interfaces JSON = " + getInterfacesJSON());
                g.drawString("MAC: " + getInterfacesJSON(), 100, 100);
                return null;
            }
        });

    }

}

MacAddrApplet.html

<HTML>
<HEAD>
    <TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>

    <H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>

    <P><APPLET codebase="classes" code="MacAddrApplet.class" width=350 height=200></APPLET></P>

    <HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>

applet.policy

grant {
permission java.security.AllPermission;
};

When I try to run my applet from Run -> Run File it works perfectly fine and shows my Mac address in it, with this log that I'm printing

Interfaces = en1;XX:XX:XX:XX:XX:XX
Interfaces JSON = ['en1;XX:XX:XX:XX:XX:XX']

But when I try to run it using

appletviewer build/MacAddrApplet.html

it prints

Interfaces = en1;
Interfaces JSON = ['en1;']

How can I solve this issue??

P.S. I think it's happening because it's not using the permissions of applet.policy


Answer:

Eventually I figured out what's wrong with the terminal command

appletviewer build/MacAddrApplet.html

because if you see the project.properties file located in nbproject folder, at the end part, you'll see

run.jvmargs=-Djava.security.policy=applet.policy

So when I run the applet using Run -> Run File Netbeans internally took care of everything and hence the applet is running perfectly fine.

But, in case of the terminal, I need to specify the policy file explicitly (This is what I want to know when I asked the question!), So run the applet with this command and it will work fine...

appletviewer -J-Djava.security.policy=applet.policy build/MacAddrApplet.html

Question:

Look at the following program:

public class HouseOfCards 
{
    public static void main(String[] args)
    {
        for (int cards = 1; cards <= 4; cards++)
        {
           if (cards == 1) 
           {
               System.out.println("Ace of Clubs");
                for (int singles = 2; singles <= 9; singles++)
                { 
                   System.out.println(singles + " of Clubs");
                }//end of for loop()
               System.out.println("Jack of Clubs");
               System.out.println("Queen of Clubs");
               System.out.println("King of Clubs");
               System.out.println("Ace of Clubs");
          }//end of if() 
                            ......
             //More else if() blocks for each suit
                            ......
        }//end of for loop()
     }//end of method main() 
   }//end of class HouseOfCards

In the above code, I want to print the first set of cards, that being clubs, then do the same for the rest of the suits in a "new deck order" format.

Clubs --> Spades --> Hearts --> Diamonds

I see that the first if() block, that being, (cards == 1), is a little repetitive. I don't want to do 4 if blocks to do the whole deck.

My questions to you are as follows, 1. how would I go about reducing the code in that way? 2. Is it possible? Or 3. is it just best to do 4 sets of if() blocks for each suit?

Thanks in advance for the help!


Answer:

private String[] cards = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
private String[] colors = {"Clubs", "Spades", "Hearts", "Diamonds"};

Then iterate through both array using for loops.

for (int iColor = 0; iColor < colors.length; iColor++) {
    for (int iCard = 0; iCard < cards.length; iCard++) {
        System.out.printf("%s of %s%n", cards[iCard], colors[iColor];
    }
}

Question:

I am trying to run an applet using appletviewer and I am getting the following Exception:

 Exception in thread "AWT-EventQueue-1" java.lang.NoClassDefFoundError: org/appache/commons/codec/binary/Base64

I added the jar files in the classpath but I get again the error. In the compiler run perfect but in cmd don't.

Any idea how to solve this problem?


Answer:

If you are running a program which needs external jar files, from command prompt then only adding the files to your class path is not enough, you need to explicitly mention while compiling and executing the program that which jar files you want to include.

For the same you can use the following

To compile

javac -g -cp YOUR_JAR.jar YOUR_FILE_NAME.java

To run

java -cp YOUR_JAR.jar; YOUR_MAIN_CLASS

Here -cp flag is for class path and after this you need to write write the name of the jar file you need to include.

Question:

This is a break the brick type of game where the user cannot let the ball fall below the paddle. By the way paddle_x is sets the x coordinate of the paddle. I have a MouseListener that works very well however, the KeyListener does not. I am wondering what I am doing wrong and if anyone has any suggestions.

public PaintSurface() {
    addMouseMotionListener(new MouseMotionAdapter() 
    {
        public void mouseMoved(MouseEvent e)
        {
            if (e.getX() - 30 - paddle_x > 5)
                english  = 1.5f;
            else if(e.getX() - 30 - paddle_x < -5)
                english = - 1.5f;
            else
                english = 1.0f;
            paddle_x = e.getX() - 30;
        }
    });
    addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub
            if(e.getID() == KeyEvent.KEY_TYPED){
                if(e.getKeyChar() == KeyEvent.VK_RIGHT){
                    paddle_x += 30;
                }
                else if (e.getKeyChar() == KeyEvent.VK_LEFT){
                    paddle_x -= 30;
                }
            }
        }
    });


    ball = new Ball(20);

}

Answer:

The Component which has a registered KeyListener must have focus for the KeyListener to fire. Call requestFocus on the Component to request that the component has focus, or use KeyBindings (recommended)

In addition, the keyPressed method has a conditional that checks the ID against KeyEvent.KEY_TYPED events (which will never happen).

Question:

In my Java applet I have JDialog with couple of radioButtons.

The problem is that this applet is of dimensions 700x300 and the JDialog appears in the center of screen. I want this JDialog to appear in the center of JApplet layout. My constructor invocation looks like this:

final JDialog dialog = new JDialog(
        SwingUtilities.windowForComponent(GUIComponentContainer.getInstance().getDocumentTable()),
        I18nCommonsImpl.constants.selectCertificate(), ModalityType.APPLICATION_MODAL);

This method:

GUIComponentContainer.getInstance().getDocumentTable()

returns JTable component which is a child of my JApplet.

I also used JDialog "setLocationRelativeTo" method:

dialog.setLocationRelativeTo(GUIComponentContainer.getInstance().getApplet());

None of these seem to work. Is there any other way to accomplish my goal? I searched along SO for similar questions, but didn't see any working solutions.

Thanks in advance.


Answer:

Getting the Window for the applet works for me, at least when the applet is launched in Eclipse. For example:

import java.awt.Dimension;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class AppletCentering extends JApplet {
    @Override
    public void init() {
        final JPanel panel = new JPanel();
        panel.add(new JButton(new AbstractAction("Press Me") {

            @Override
            public void actionPerformed(ActionEvent e) {
                Window win = SwingUtilities.getWindowAncestor(panel);
                System.out.println("win class: " + win.getClass().getCanonicalName());
                JDialog dialog = new JDialog(win, "My Dialog", ModalityType.APPLICATION_MODAL);
                dialog.add(Box.createRigidArea(new Dimension(200, 200)));
                dialog.pack();
                dialog.setLocationRelativeTo(win);
                dialog.setVisible(true);                    
            }
        }));

        add(panel);
    }
}

But having said this, your question begs the question: why are you even coding for an applet? These have been out of favor for years, and just recently has lost support from Oracle who has decided to finally drop applet browser plug in support.

Question:

Here is the code I am working on(Its part of the CalculatorTester Class which is an extension of the Calculator Class):

 if (choice == 1) //Addition
    {
        System.out.println("Math Operation: Addition."); 
        System.out.println("Enter First Number."); 
        int a = in.nextInt(); 
        System.out.println("Enter Second Number."); 
        int b = in.nextInt(); 
        int endValue = c1.addition(a, b); 
        System.out.println("The Sum is: " + endValue + "."); 
    }
    else if (choice == 2)
    {
          ...More Code Here...
    }//end of if() 

The addition method inside the Calculator object:

   public int addition(int a, int b)
   {
       endValue = a + b; 
       return endValue; 
   }//end of method addition() 

How would I reduce the Repetitiveness of the if Statements, as I have 5 in total due to the amount of different operations one can choose from?

Thanks!


Answer:

Ask for numbers before and give results after:

//user selects operation
System.out.println("Enter First Number."); 
int a = in.nextInt(); 
System.out.println("Enter Second Number."); 
int b = in.nextInt(); 

int endValue;
if (choice == 1) //Addition
    endValue = c1.addition(a, b); 
else if (choice == 2)
    endValue = c1.subtraction(a, b); 
else
    //throw exception since there was no endValue calculated

System.out.println("The result is: " + endValue + "."); 

You can also use a switch/case instead of if/if else/else.

Question:

I have made a blueprint of an Applet with functionality yet to insert. So, I instantiated arrays of various types in the class and then further instantiated their type in the init() function. But then, I changed the instantiation of the arrays in the constructor GPACalculator and it is giving me 70 Compilation Errors. I checked the opening and closing brackets beforehand and still it remains unresolved.

Errors are of many types. Some of them are as follows:

1. Illegal start of expression or type

2. Not a statement

3. Particular character expected

4. class interface or enum expected

Errors start from the line where I assigned the String[] description it's values.

Here is my program:

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;

public class GPACalculator extends JApplet {

    private JButton[] button; //initially instantiated here instead of the constructor
    private JComboBox[] c; //initially instantiated here instead of the constructor
    private JFrame frame;
    private JPanel[] p; //initially instantiated here instead of the constructor
    private JTextField[] course; //initially instantiated here instead of the constructor
    private JTextField finalGPA; 
    private JTextField[] points; //initially instantiated here instead of the constructor
    private SpringLayout s1;
    private String[] description; //initially instantiated here instead of the constructor

    public GPACalculator() {
        button = new JButton[2];
        c = new JComboBox[7];
        p = new JPanel[9];
        course = new JTextField[7];
        points = new JTextField[7];
        s1 = new SpringLayout();

        //error from the next line

        description = { "Select", "A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F" };
        p[0] = new JPanel(s1);
        for(int i=1; i<9; i++)
            p[i] = new JPanel(new FlowLayout());
        prepareGUI();
    }

    public void prepareGUI() {
        frame = new JFrame("GPA Calculator");
        frame.setSize(400, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(9,1));
        frame.setVisible(true);
    }

    public void init() {
        //Execute a job on the event-dispatching thread; creating this applet's GUI.
        JLabel label1 = new JLabel("<html><br>Course</html>");
        JLabel label2 = new JLabel("<html>Credit<br>Points</html>");
        JLabel label3 = new JLabel("<html><br>Grade</html>");
        p[0].add(label1);
        p[0].add(label2);
        p[0].add(label3);
        s1.putConstraint(SpringLayout.NORTH, label1, 5, SpringLayout.NORTH, p[0]);
        s1.putConstraint(SpringLayout.NORTH, label2, 5, SpringLayout.NORTH, p[0]);
        s1.putConstraint(SpringLayout.NORTH, label3, 5, SpringLayout.NORTH, p[0]);
        s1.putConstraint(SpringLayout.WEST, label1, 100, SpringLayout.WEST, p[0]);
        s1.putConstraint(SpringLayout.WEST, label2, 143, SpringLayout.WEST, label1);
        s1.putConstraint(SpringLayout.WEST, label3, 72, SpringLayout.WEST, label2);
        frame.add(p[0]);
        for (int i = 0; i<c.length; i++) {
            course[i] = new JTextField(18);
            points[i] = new JTextField(6);
            p[i+1].add(course[i]);
            p[i+1].add(points[i]);
            c[i] = new JComboBox();
            for(int j=0; j<description.length; j++) {
                c[i].addItem(description[j]);
            }
            p[i+1].add(c[i]);
            frame.add(p[i+1]);
        }
        button[0] = new JButton("Clear All");
        button[1] = new JButton("Calculate your GPA");
        finalGPA = new JTextField(6);
        p[8].add(button[0]);
        p[8].add(button[1]);
        p[8].add(finalGPA);
        frame.add(p[8]);
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        GPACalculator applet = new GPACalculator();
        applet.init();
    }
}

Answer:

 description = new String[] { "Select", "A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F" };

should do the trick

Question:

I have an applet in a web application (JSP page) in one domain somedomain/myjsp.jsp embedded via object tag and i have another object tag in the same jsp which loads some other domain url anotherdomain/another.jsp .I am unable to call the applet function from the jsp page of another domain.

function enableToUpdate() 
    {
     window.parent.document.MyApplet.EnableButton();               
    }

Answer:

I think the problem is, the jsp is runing in the server jvm. The applet is running in the client jvm.

This are two diferent programs in two different jvms. One can not call a function in the other.

You can use JavaScript: http://docs.oracle.com/javase/tutorial/deployment/applet/invokingAppletMethodsFromJavaScript.html

Question:

I'm building my first very basic game in JAVA without using any other external libraries. The problem I got is

You can see that the background is rendered over player how can I fix that The player rendering code is as follows

@Override
    public void render(Graphics g) {
        int bulletcount = 0;
        //render player
        g.setColor(color);
        g.fillRect(x,y,32,32);
        if(shooting) {
            handler.add(new bullet(x + 8, y - 24, ID.bullet, handler));
            bulletcount++;
        }
    }

and the background render code is as follows.

public class background extends GameObject{
    private int width;
    private Random random = new Random();
    public background(int x, int y , ID id,Handler handler){
        super(x,y,id,handler);
        valy = 2;
        width = getWidth(x,800);
    }
    public void tick() {
        y += valy;
        if(y>650)
            handler.remove(this);
    }
    public void render(Graphics g) {
        g.setColor(Color.white);
        g.fillRoundRect(x,y,width,10,1,1);
    }

    public int getWidth(int x,int width1){
        int wid;
        while(true){
            if((width - x) > 35) {
                wid = random.nextInt((width-x-35));
                break;
            }
            else{
             x -= 10;
            }
        }
        return wid;
    }
}

the main class of game can see the order of flow of execution.

 private void render() {
    // render the Game
        BufferStrategy bs = this.getBufferStrategy();
        if(bs == null)
        {
            this.createBufferStrategy(3);
            return;
        }

        Graphics g = bs.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(0,0,WIDTH,HEIGHT);
        handler.render(g);
        hod.render(g);    //handler is rendering every object in game
        g.dispose();
        bs.show();
    }

    private void tick() {
    //update Game
        handler.tick();
        hod.tick();
        spawner.tick(); // background is generating in spawner class.
    }

I know that telling the problem with this much less code is hard for you all. But I have complete faith in this large and powerful community.

Thanks in advance. Don't hesitate to edit and point out my mistakes Thanks!


Answer:

If I get the code right, the background is being generated after rendering the player which leads to the background being on top of the player. I would try calling spawner.tick() (where I guess the background is coming from given your code comment) before calling hod.tick(). Hopefully that should resolve this issue.

private void tick() { //update Game 
         spawner.tick();
         handler.tick();
         hod.tick();
}