Hot questions for Using Applets in jframe

Question:

I am trying to modify a JFrame application to an applet. The jframe application can run in eclipse well. But I don't know how to make an applet class and how to compile it so that it can be used in the HTML codes. Now the JFrame application contains a main method.


Answer:

Just inherit from java.applet.Applet. Create a file named MyClass.java and write an applet like this:

import java.awt.Graphics;
import java.applet.Applet;



public class MyClass extends Applet {

    @Override
    public void init() {

        // Probably your constructor code here.
        // Or rather create a separate constructor for MyClass 
    }

    @Override
    public void paint(Graphics g) {

        // Your code here.
    }
}

Compile the code as:

javac MyClass.java

Now create an html file and save it by the name MyApp.html like this.

<!DOCTYPE html>
<html>
    <body>
        <applet code="MyClass.class" width=500 height=500>
            Any message to be printed if browsers do not support applets.
        </applet>
    </body>
</html>

Open the html document in a browser.

Nowadays browsers don't support unsigned applets. So I suggest you to hit the command line and type:

appletviewer MyApp.html  

and view your applet in an appletviewer. Hope this helps.

Question:

I'm making a Java Applet in Eclipse IDE. I have a JMenu and a JFrame. The menu is appearing behind the JFrame for some reason..

like this:

Here is where it is calling it:

public Main() throws Exception{

    JFrame i = new JFrame("My Applet");
    JLabel label = new JLabel();

    ImageIcon icon = new ImageIcon(new URL(
               "loader.gif"));
    icon.setImageObserver(null);
    label.setIcon(icon);
    i.setBackground(Color.BLACK);


    JMenuBar menuBar = new JMenuBar();

    i.setJMenuBar(menuBar);

    JMenu accountMenu = new JMenu("Account");
    JMenu toolsMenu = new JMenu("Tools");
    JMenu optionsMenu = new JMenu("Options");

    menuBar.add(accountMenu);
    menuBar.add(toolsMenu);
    menuBar.add(optionsMenu);

    JMenuItem accountdetAction = new JMenuItem("Account Details");
    JMenuItem exitAction = new JMenuItem("Exit");

    accountMenu.add(accountdetAction);


    optionsMenu.addSeparator();
    optionsMenu.add(exitAction);

    ButtonGroup bg = new ButtonGroup();

    accountdetAction.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            System.out.println("test");
        }
    });

    i.add(label);
    i.pack();
    i.setVisible(true);


    String str = getPageSource(new URL("my url link goes here"));
    Pattern pattern = Pattern.compile("gamep\\w+");
    Matcher match = pattern.matcher(str);
    if (match.find()){
         Main stub = new Main(Pattern.compile("<param name=\"([^\\s]+)\"\\s+value=\"([^>]*)\">"), str);
         Download("my url link goes here", match.group(0)+ "jar");
         stub.setCodeBase(new URL("my url link goes here" + match.group(0)+ ".jar"));
         stub.setDocumentBase(new URL("my url link goes here" + match.group(0)+ "jar"));
         stub.getParameter (parameters.get("java_arguments"));
         URLClassLoader classLoader = new URLClassLoader(new URL[]{ new URL("file:thejar.jar")});
         Applet applet = (Applet) classLoader.loadClass ("client").newInstance();
         applet.setStub(stub);
         applet.setPreferredSize(new Dimension(1000, 500));
         applet.init();
         applet.start();

         i.setJMenuBar(menuBar);


         i.add(applet);
         i.pack();
         i.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         label.setVisible(false);


    }
}

I have tried calling the menu in the if statement too, which does not work. Is there a way to force it on top? I heard using JPanels works but I don't know how to work that...

Thanks in advance for any advice :)


Answer:

As an example, you can try this

import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

import java.awt.Graphics;

public final class PullingAppletExample{
    private JFrame mainWindow = null;   
    private JMenuBar menuContainer = null;
    private JMenu    menu1 = null; 
    private JMenu    menu2 = null;
    private JMenuItem mnuItem1 = null;
    private JMenuItem mnuItem2 = null;
    private JMenuItem mnuItem3 = null;
    private JMenuItem mnuItem4 = null;

    public PullingAppletExample(){

        menu1 = new JMenu("Menu #1");
        menu2 = new JMenu("Menu #2");
        mnuItem1 = new JMenuItem("Item #1");
        mnuItem2 = new JMenuItem("Item #2");
        mnuItem3 = new JMenuItem("Item #3");
        mnuItem4 = new JMenuItem("Item #4");

        menu1.add(mnuItem1);
        menu1.add(mnuItem2);
        menu1.add(mnuItem3);

        menu2.add(mnuItem4);

        menuContainer = new JMenuBar();
        menuContainer.add(menu1);
        menuContainer.add(menu2);

        mainWindow = new JFrame();
        mainWindow.setTitle("Applet Inside JFrame");
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainWindow.setBounds(100,100,500,500);
        mainWindow.setJMenuBar(menuContainer);
        mainWindow.setVisible(true);
        mainWindow.setContentPane(new CustomApplet());

    }
    private class CustomApplet extends JApplet{
        @Override
        public void init(){
            repaint();
        }
        @Override
        public void paint(Graphics g){
            g.drawString("Hello World",100,50);
        }
    }

    public static void main(String[] args) {
        new PullingAppletExample();
    }
}

Question:

I am trying to programmatically set table in my Applet program. I tried the following code, it works fine. But, This is opening new window and then drawing the table. Can I have sample for drawing such table in the Applet view itself

 JFrame frame = new JFrame();
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 Object rowData[][] = { 
         { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
         { "Row2-Column1", "Row2-Column2", "Row2-Column3" } 
 };
 Object columnNames[] = { "Column One", "Column Two", "Column Three" };
 JTable table = new JTable(rowData, columnNames);

 JScrollPane scrollPane = new JScrollPane(table);
 frame.add(scrollPane, BorderLayout.CENTER);
 frame.setSize(300, 150);
 frame.setVisible(true);

Answer:

Instead of creating a JFrame and adding your JScrollPane to that, you should extend JApplet and simply add your JScrollPane to that.

Recommended reading: http://docs.oracle.com/javase/tutorial/deployment/applet/getStarted.html

This is, of course, after taking into account the link Andrew Thompson already gave you.

Question:

I've tried writing it in first Applet and it worked but I used repaint() method just after drawOval line and it was flashing too much that I cant see..Please help me to fix it.

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;


public class MouseEvents extends JFrame implements MouseListener, MouseMotionListener {

  JFrame frame;

  public static void main(String args[]){

  MouseEvents obj=new MouseEvents();

  obj.go();

}

public void go(){

  frame=new JFrame();

  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  frame.setSize(300,300);

  frame.setVisible(true);

  addMouseListener(this);

  addMouseMotionListener(this);

}

public void mouseClicked(MouseEvent me) {

}

public void mouseEntered(MouseEvent me) {

}

public void mouseExited(MouseEvent me) {

}

public void mousePressed(MouseEvent me) {

}

public void mouseReleased(MouseEvent me) {

}

public void mouseDragged(MouseEvent me) {

  repaint();

}

public void mouseMoved(MouseEvent me) {

  Graphics g=getGraphics();

  g.drawOval(me.getX(), me.getY(), 30,30);

}

}

Answer:

  1. It's not an applet, it's frame
  2. Learn how painting in Swing is suppose to be done (ie not by using getGraphics). See Painting in AWT and Swing and Performing Custom Painting for more details.

Start by creating a class that extends from JPanel. To this, register a MouseMoitionListener to track the current mouse position. Override it's paintComponent to paint the circle where the mouse moves...

public class CirclePane extends JPanel {

    private Point p = new Point(100, 100);

    public CirclePane() {
        MouseAdapter mouseHandler = new MouseAdapter() {

            @Override
            public void mouseMoved(MouseEvent e) {
                p = e.getPoint();
                repaint();
            }

        };
        addMouseMotionListener(mouseHandler);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.drawOval(p.x - 50, p.y - 50, 100, 100);
        g2d.dispose();
    }

}

Add this to your frame...

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class MouseEvents {

    public static void main(String[] args) {
        new MouseEvents();
    }

    public MouseEvents() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new CirclePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}