Box in JApplet?!

Just a quick question.. I have no problems with using Box Layout in a Java application, but the minute I try to use Box in an applet nothing appears! Can I use Box in JApplets?!
Thanks :-)

I found the answer in
http://www.jguru.com/faq/view.jsp?EID=27423

Similar Messages

  • Java rotate, drag RoundRectangle2D problem please help me!!!

    Hi,
    i have 2 program, the first program can rotate a RoundRectangle2D, and the secend program can create new RoundRectangle2D and drag them around.
    The problem is that i want the rotate and the drag functions in one file, could any wone plese help me with this??
    The code has been orginally written by phillips75. i have modified it.
    The first program that rotates a Rectangle2D
    package appli;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class minappli extends JApplet
    Vector shape = new Vector();
    class axel extends JPanel
    axel selectedRect;
    //RoundRectangle2D r;
    RectangularShape r;
    RectangularShape rsss;
    AffineTransform xform;
    int theta;
    public axel()
    shape.addElement(new axel(40, 50, 50, 60));
    shape.addElement(new axel(150, 100, 50, 60));
    shape.addElement(new axel(40, 150, 50, 60));
    setBackground(Color.white);
    addMouseListener(new RectSelector(this));
    public axel (int x, int y, int w, int h)
    r = new RoundRectangle2D.Double(x, y, w, h, 20, 20);
    xform = new AffineTransform();
    theta = 0;
    public void drawdd (Graphics2D g2)
    AffineTransform orig = g2.getTransform();
    if (!xform.isIdentity())
    g2.setTransform(xform);
    g2.draw(r);
    g2.setTransform(orig);
    public void rotateRect()
    double cx = r.getCenterX();
    double cy = r.getCenterY();
    theta = theta + 5;
    xform.setToRotation(Math.toRadians(theta), cx, cy);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    //int w = getWidth();
    //int h = getHeight();
    axel rs;
    for(int i = 0; i < shape.size(); i++)
    rs = (axel) shape.get(i);
    // System.out.println(" rs " + rs + " rsss " + konam);
    if (rs == selectedRect)
    g2.setPaint(Color.yellow);
    else
    g2.setPaint(Color.black);
    rs.drawdd(g2);
    class RectSelector extends MouseInputAdapter
    axel rotationPanel;
    RectangularShape selectedShape;
    axel rs;
    Point start, offset;
    boolean addCircle, addSquare, dragging;
    final int size = 50;
    public RectSelector(axel fp)
    rotationPanel = fp;
    offset = new Point();
    addCircle = false;
    addSquare = false;
    dragging = false;
    public void mousePressed(MouseEvent e)
    RectangularShape rssss = null;
    Point p = e.getPoint();
    rssss = new RoundRectangle2D.Double(p.x - size / 2, p.y - size / 2, size, size, 20, 20);
    for (int i = 0; i < shape.size(); i++)
    rs = (axel) shape.get(i);
    //System.out.println("rs" + rs);
    if (rs.r.contains(p))
    selectedRect = rs;
    repaint();
    break;
    public void mouseReleased(MouseEvent e)
    selectedShape = null;
    dragging = false;
    public void mouseDragged(MouseEvent e)
    if (dragging)
    Point p = e.getPoint();
    if (selectedShape != null)
    // dragging a shape
    Rectangle r = selectedShape.getBounds();
    r.x = p.x - offset.x;
    r.y = p.y - offset.y;
    selectedShape.setFrame(r);
    rotationPanel.repaint();
    public JPanel getUIpanelg()
    final JButton rotateButton = new JButton("Rotate");
    final JButton box = new JButton("Box");
    rotateButton.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    if (e.getSource() == rotateButton)
    selectedRect.rotateRect();
    repaint();
    JPanel panel = new JPanel();
    panel.add(rotateButton);
    panel.add(box);
    return panel;
    public void init()
    axel rp = new axel();
    Container cp = getContentPane();
    cp.setLayout(new BorderLayout());
    cp.add(rp.getUIpanelg(), "South");
    cp.add(rp);
    public static void main(String[] args)
    JApplet applet = new minappli();
    JFrame f = new JFrame("Test");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(applet);
    f.setSize(400,300);
    f.setLocation(200,200);
    applet.init();
    f.setVisible(true);
    The second program that creates new Rectangle2D and drags it around
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.*;
    public class axel extends JApplet
    Vector shape = new Vector();
    int theta;
    RoundRectangle2D r;
    AffineTransform xform;
    class axel1 extends JPanel
    axel1 selectedRect;
    RectSelector action;
    public axel1()
    //shape.addElement(new axel1(40, 50, 50, 60));
    //shapeList.addElement(new FlowPanel(150, 100, 50, 60));
    //shapeList.addElement(new FlowPanel(40, 150, 50, 60));
    setBackground(Color.white);
    action = new RectSelector(this);
    addMouseListener(action);
    addMouseMotionListener(action);
    public void drawdd (Graphics2D g2)
    AffineTransform orig = g2.getTransform();
    if (!xform.isIdentity())
    g2.setTransform(xform);
    g2.draw(r);
    g2.setTransform(orig);
    public axel1 (int x, int y, int w, int h)
    r = new RoundRectangle2D.Double(x, y, w, h, 20, 20);
    xform = new AffineTransform();
    theta = 0;
    public void rotateRect()
    double cx = r.getCenterX();
    double cy = r.getCenterY();
    System.out.println("fffffffffffff");
    theta = theta + 5;
    xform.setToRotation(Math.toRadians(theta), cx, cy);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    RoundRectangle2D rs;
    for (int i = 0; i < shape.size(); i++)
    //rs = (RectangularShape) shape.get(i);
    g2.draw((RectangularShape) shape.get(i));
    //rs = (axel1) shape.get(i);
    //System.out.println("skapar " + i + "hahaaha " + rs);
    //if (rs == selectedRect)
    // g2.setPaint(Color.red);
    //else
    // g2.setPaint(Color.black);
    public void clear()
    shape.clear();
    repaint();
    class RectSelector extends MouseInputAdapter
    axel1 rotationPanel;
    RectangularShape selectedShape;
    final int size = 50;
    Point start, offset;
    boolean addCircle, addSquare, dragging;
    axel1 rs;
    public RectSelector(axel1 fp)
    // lista = (Vector) flowPanel.getShapeList();
    shape.addElement(new RoundRectangle2D.Double(40, 50, 50, 60, 20, 20));
    rotationPanel = fp;
    offset = new Point();
    addCircle = false;
    addSquare = false;
    dragging = false;
    public void mousePressed(MouseEvent e)
    RectangularShape rssss = null;
    Point p = e.getPoint();
    if (addCircle)
    rssss = new Ellipse2D.Double(p.x - size / 2, p.y - size / 2, size, size);
    if (addSquare)
    rssss = new RoundRectangle2D.Double(p.x - size / 2, p.y - size / 2, size, size, 20, 20);
    if (rssss != null)
    shape.addElement(rssss);
    rotationPanel.repaint();
    addCircle = addSquare = false;
    return;
    // or are we selecting an existing shape to drag
    for (int i = 0; i < shape.size(); i++)
    rssss = (RectangularShape) shape.get(i);
    if (rssss.contains(p))
    System.out.println("nu " + i + " " + rssss);
    selectedShape = rssss;
    Rectangle r = rssss.getBounds();
    offset.x = p.x - r.x;
    offset.y = p.y - r.y;
    dragging = true;
    break;
    public void mouseReleased(MouseEvent e)
    selectedShape = null;
    dragging = false;
    public void mouseDragged(MouseEvent e)
    if (dragging)
    Point p = e.getPoint();
    if (selectedShape != null)
    // dragging a shape
    Rectangle r = selectedShape.getBounds();
    r.x = p.x - offset.x;
    r.y = p.y - offset.y;
    selectedShape.setFrame(r);
    rotationPanel.repaint();
    public JToolBar getToolBar()
    JToolBar toolBar = new JToolBar();
    ActionListener l = new ActionListener()
    public void actionPerformed(ActionEvent e)
    JButton button = (JButton) e.getSource();
    String ac = button.getActionCommand();
    if (ac.equals("Single arrow"))
    addCircle = true;
    if (ac.equals("Box"))
    addSquare = true;
    if (ac.equals("Clear"))
    rotationPanel.clear();
    if (ac.equals("Rotate"))
    //double cx = r.getCenterX();
    //double cy = r.getCenterY();
    System.out.println("fffffffffffff");
    //theta = theta + 5;
    //xform.setToRotation(Math.toRadians(theta), cx, cy);
    // repaint();
    JButton button = makeButton("Single arrow", "Add a arrow", l);
    toolBar.add(button);
    button = makeButton("Box", "Add a box", l);
    toolBar.add(button);
    button = makeButton("Clear", "Clears everything", l);
    toolBar.add(button);
    button = makeButton("Rotate", "Rotate a shape", l);
    toolBar.add(button);
    return toolBar;
    private JButton makeButton(String actionCommand, String toolTipText, ActionListener l)
    JButton button = new JButton(actionCommand);
    button.setActionCommand(actionCommand);
    button.setToolTipText(toolTipText);
    button.addActionListener(l);
    return button;
    public void init()
    axel1 flowPanel = new axel1();
    RectSelector action = flowPanel.action;
    Container cp = getContentPane();
    cp.setLayout(new BorderLayout());
    cp.add(action.getToolBar(), "South");
    cp.add(flowPanel);
    public static void main(String[] args)
    JApplet applet = new axel();
    JFrame f = new JFrame("test");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(applet);
    f.setSize(500, 400);
    f.setLocation(200, 200);
    applet.init();
    f.setVisible(true);
    The

    New code:
    Class Arrow
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GraphicArrow  extends JComponent
        GeneralPath arrow   =  new GeneralPath();
        Stroke dashStroke   =  new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10f, new float[] {4f, 4f}, 0f);
        Paint gradientPaint =  new GradientPaint(-30, 0, Color.red, 10, 0, Color.yellow);
        GraphicArrow selectedArrow;
        public void paintComponent(Graphics _g)
            super.paintComponent(_g);
            Graphics2D g2 = (Graphics2D) _g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                               RenderingHints.VALUE_ANTIALIAS_ON);
            AffineTransform graphicsDefaultTransform = g2.getTransform();
            AffineTransform xform = new AffineTransform();
            Rectangle bounds = arrow.getBounds();
            Point startPoint = new Point();
            xform.translate(startPoint.x - bounds.x, startPoint.y - bounds.y);
            //g2.transform(xform);
            //g2.setStroke(dashStroke);
            //g2.draw(arrow);
             //g2.setTransform(graphicsDefaultTransform);
            //g2.transform(xform);
            //g2.setPaint(gradientPaint);
            //g2.fill(arrow);
            xform.translate(bounds.width + 20, 0);
            xform.translate(bounds.width + 20, 0);
            //g2.setTransform(graphicsDefaultTransform);
            g2.setPaint(gradientPaint);
            g2.transform(xform);
            g2.rotate(Math.PI / 1);
            g2.fill(arrow);
        public GraphicArrow (int x, int y)
            //Value before -20, -10
            arrow.moveTo(x, y);
            arrow.lineTo(0, -10);
            arrow.lineTo(0, -20);
            arrow.lineTo(20, 0);
            arrow.lineTo(0, 20);
            arrow.lineTo(0, 10);
            arrow.lineTo(-20, 10);
            arrow.lineTo(-20, -10);
            addMouseListener(new MouseAdapter()
                Rectangle hitRect = new Rectangle(0, 0, 5, 5);
                public void mouseClicked(MouseEvent e)
                    Graphics2D g = (Graphics2D) getGraphics();
                    AffineTransform xform = new AffineTransform();
                    hitRect.x = e.getX();
                    hitRect.y = e.getY();
                    Rectangle bounds = arrow.getBounds();
                    Point startPoint = new Point();
                    //System.out.println("hh " + (bounds.x  ) );
                    xform.setToTranslation(startPoint.x - bounds.x + 2 * bounds.width + 2 * 20, startPoint.y - bounds.y);
                    xform.rotate(Math.PI / 1);
                    g.setTransform(xform);
                    if (g.hit(hitRect, arrow, false))
                        System.out.println("Traff " + xform);
        public static void main(String args[])
            Frame frame = new Frame("Arrow");
            frame.add(new GraphicArrow(0, 0));
            frame.setBackground(Color.white);
            frame.setSize(new Dimension(400, 350));
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }The shape class:
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    import java.awt.*;
    public class Box extends JApplet
        Vector shape      = new Vector();
        Vector arrowArray = new Vector();
        int theta;
        class axel extends JPanel implements KeyListener
            GeneralPath arrow   = new GeneralPath();
            Stroke dashStroke   = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10f, new float[] {10f, 10f}, 5f);
            Paint gradientPaint = new GradientPaint( -30, 0, Color.red, 10, 0, Color.yellow);
            boolean delete_box, addSquare, addArrow, dragging;
            axel selectedRect;
            RectangularShape boxen;
            AffineTransform xform;
            RectSelector action;
            String texten;
            public axel()
                shape.addElement(new axel("Text1", 40, 50, 50, 60));
                shape.addElement(new axel("Text2", 150, 100, 50, 60));
                shape.addElement(new axel("Text3", 40, 150, 50, 60));
                setBackground(Color.white);
                action = new RectSelector(this);
                addMouseListener(action);
                addMouseMotionListener(action);
                addKeyListener(this);
            public axel(String text, int x, int y, int w, int h)
                texten = text;
                boxen  = new RoundRectangle2D.Double(x, y, w, h, 20, 20);
                xform  = new AffineTransform();
                theta  = 5;
            public void rita(Graphics2D g2)
                double cx = boxen.getCenterX();
                double cy = boxen.getCenterY();
                int mus_x =(int) cx;
                int mus_y =(int) cy;
                AffineTransform orig = g2.getTransform();
                if (!xform.isIdentity())
                    g2.setTransform(xform);
                g2.fill(boxen);
                g2.setColor(Color.black);
                g2.setFont(new Font("Helvetica", Font.BOLD, 12));
                g2.drawString(texten, mus_x + -11, mus_y + 5);
                g2.draw(boxen);
                g2.setTransform(orig);
            public void paintComponent(Graphics g)
               super.paintComponent(g);
               Graphics2D g2 = (Graphics2D) g;
               Image bild = getImage(getDocumentBase(), "images.jpg");
               g2.drawImage(bild, 0, 0, this);
               g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                   RenderingHints.VALUE_ANTIALIAS_ON);
               //Draw the Shapes
               for (int i = 0; i < shape.size(); i++)
                   axel rsh = (axel) shape.get(i);
                   if (rsh == selectedRect)
                       g2.setStroke(dashStroke);
                       g2.setPaint(Color.green);
                   else
                       g2.setStroke(new BasicStroke(0));
                       g2.setPaint(Color.yellow);
                   rsh.rita(g2);
               //Draw the Arrows
               for (int i = 0; i < arrowArray.size(); i++)
                   GraphicArrow selectedArrow;
                   GraphicArrow arrowen = (GraphicArrow) arrowArray.get(i);
                   arrowen.paintComponent(g);
            public void resizen()
                Rectangle r      = boxen.getBounds();
                double    width  = boxen.getWidth()+2;
                double    height = boxen.getHeight()+2;
                boxen.setFrame(r.x, r.y, width, height);
            public void rotateRect()
                double cx = boxen.getCenterX();
                double cy = boxen.getCenterY();
                theta = theta - 5;
                xform.setToRotation(Math.toRadians(theta), cx, cy);
            public void rotateRect_right()
                double cx = boxen.getCenterX();
                double cy = boxen.getCenterY();
                theta = theta + 5;
                xform.setToRotation(Math.toRadians(theta), cx, cy);
            public void keyPressed(KeyEvent e) {
                System.out.println("Test1");
                if (e.isShiftDown()) {
                    System.out.println("Test3");
                if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                    System.out.println("Test2");
            public void keyReleased(KeyEvent e) {
            public void keyTyped(KeyEvent e) {
            class RectSelector extends MouseInputAdapter {
                axel rotationPanel;
                RectangularShape selectedShape;
                axel rs;
                Point offset;
                final int size = 50;
                public RectSelector(axel fp)
                    rotationPanel  = fp;
                    offset         = new Point();
                    delete_box     = false;
                    addSquare      = false;
                    addArrow       = false;
                    dragging       = false;
                public void mousePressed(MouseEvent e) {
                    Point p = e.getPoint();
                    //New Box skapas
                    if (addSquare)
                      shape.addElement(new axel("text5", p.x, p.y, 50, 60));
                      rotationPanel.repaint();
                      addSquare = false;
                      return;
                    //New Arrow skapas
                    if (addArrow)
                      arrowArray.addElement(new GraphicArrow(p.x, p.y));
                      rotationPanel.repaint();
                      addArrow = false;
                      return;
                    for (int i = 0; i < shape.size(); i++)
                        rs = (axel) shape.get(i);
                        if (rs.boxen.contains(p))
                            if (delete_box) {
                                shape.removeElementAt(i);
                                delete_box = false;
                                repaint();
                            Rectangle r = rs.boxen.getBounds();
                            offset.x = p.x - r.x;
                            offset.y = p.y - r.y;
                            selectedRect = rs;
                            selectedShape = rs.boxen;
                            dragging = true;
                            repaint();
                        //else
                        //    System.out.println("press does not work " + delete_box + i + rs.boxen.contains(p));
                public void mouseReleased(MouseEvent e)
                    int x = e.getX();
                    int y = e.getY();
                    selectedShape = null;
                    dragging = false;
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR) );
                    //Graphics2D g3  = (Graphics2D) getGraphics();
                    //g3.setStroke(new BasicStroke(0));
                    //g3.setPaint(Color.yellow);
                public void mouseDragged(MouseEvent e)
                    if (dragging) {
                        Point p = e.getPoint();
                        if (selectedShape != null) {
                            setCursor(new Cursor(Cursor.MOVE_CURSOR) );
                            Rectangle r = selectedShape.getBounds();
                            System.out.println("dragging " + p + p.x + " " + p.y);
                            r.x = p.x - offset.x;
                            r.y = p.y - offset.y;
                            selectedShape.setFrame(r);
                            repaint();
                public void mouseMoved(MouseEvent e)
            public JPanel panelen()
                final JButton rotate_left  = new JButton("Rotate left");
                final JButton rotate_right = new JButton("Rotate right");
                final JButton arrow        = new JButton("New Arrow");
                final JButton box          = new JButton("New Box");
                final JButton delete       = new JButton("Delete");
                final JButton resize       = new JButton("Resize");
                rotate_left.setCursor(new Cursor(Cursor.HAND_CURSOR) );
                rotate_right.setCursor(new Cursor(Cursor.HAND_CURSOR) );
                arrow.setCursor(new Cursor(Cursor.HAND_CURSOR) );
                box.setCursor(new Cursor(Cursor.HAND_CURSOR) );
                delete.setCursor(new Cursor(Cursor.HAND_CURSOR) );
                resize.setCursor(new Cursor(Cursor.HAND_CURSOR) );
                rotate_left.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      if (e.getSource() == rotate_left && selectedRect != null)
                         selectedRect.rotateRect();
                         repaint();
                rotate_right.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                      if (e.getSource() == rotate_right && selectedRect != null)
                         selectedRect.rotateRect_right();
                         repaint();
                arrow.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      addArrow = (e.getSource() == arrow);
                box.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      addSquare = (e.getSource() == box && selectedRect != null);
                delete.addActionListener(new ActionListener()
                    public void actionPerformed(ActionEvent e)
                       delete_box = (e.getSource() == delete);
                resize.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      if (e.getSource() == resize && selectedRect != null)
                         selectedRect.resizen();
                         repaint();
                JPanel panel = new JPanel();
                panel.setBackground( Color.orange );
                panel.add(rotate_left);
                panel.add(rotate_right);
                panel.add(arrow);
                panel.add(box);
                panel.add(delete);
                panel.add(resize);
                return panel;
        public void init() {
            axel rp = new axel();
            Container cp = getContentPane();
            cp.setLayout(new BorderLayout());
            cp.add(rp.panelen(), "South");
            cp.add(rp);
        public static void main(String[] args)
            JApplet applet = new Box();
            JFrame f = new JFrame("Test");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(600, 400);
            f.setLocationRelativeTo(null);
            applet.init();
            f.setVisible(true);

  • How to Show a Model Dialog box in a JApplet

    I have a JTable in a JApplet.
    I need to display a JDialog box as a Model Dialog. The JDialog expects a Frame as parent. How do I create a Frame and show my own dialog box? without a parent Frame the dialog shows up as a Modeless dialog box.
    Any help would be appreciated.

    I found the answer in
    http://www.jguru.com/faq/view.jsp?EID=27423

  • Is correct? Application (JFrame) to Applet (JApplet)

    I need to convert a java application (JFrame) into an applet (JApplet), and I have seen a few "big steps":
    1�: make the class extends to JApplet instead of a JFrame
    2�: To replace the construction method by init ()
    3�: To comment the main method
    Is correct?, because I have some doubts that later I�ll explain
    Thanks

    I think in the init method (in a JApplet) I cannot call the super method. but my problem is how to change this? if in others files (in Files.java) I have calls to super metod, because thus it constructs a dialog box, asking for a file.
    In file Files.java I have a class called "Abort" (extends to JDialog) in whitch:
    /* class Files.java */
    class Abort extends JDialog
              boolean abort = true;
              JTextArea mensage = null;
              JButton acept = new JButton("Acept");
              JButton cancel = new JButton("Cancel");
              Abort(String nanemFile)
                   super(MainClassFile.mainWindow, " Attention!", true);
    /* clas Files.java */Please help

  • Text input boxes

    How can I make text input boxes in a JApplet so I can specify there location. I want to make input boxes in certain locations on the applet.

    Do you know about layout managers? If not:
    http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
    If you for some reason don't trust a layout manager to do the job for you, you can specify where you want to put things yourself by doing something like this:
    JApplet applet = ...
    applet.getContentPane().setLayout(null);  // Do not use a Layout Manager (generally a Bad Idea)
    JTextField input = new JTextField();
    input.setBounds(50, 75, 25, 100);  // Sets the position and size of your textfield
    applet.getContentPane().add(input);This is generally not recommended though, because different screen resolutions, cross-platform issues, any other things, might screw things up for you.
    ps.
    A little advice: try to be a little more patient the next time. You shouldn't start flaming the forum just because no one happens to answer your question within an hour . The people here are under no obligation whatsoever to help you -- they do it of their own free will in their own spare time.

  • Problem with Thread in JApplet

    Hi,
    I am working on a project on pseudo random functions, and for that matter I have written a problem. Now I am working on a user interface (JApplet) for my program. Because some heavy calculations can occur, I want to keep track of the progress, and show that in my JApplet. To do so, I start a Thread in which the calculations take place. In my JApplet I want to show every second how far the proces is done. The strange thing is, that the status JLabel only appears when the whole proces is done, and the start button keeps pressed during the proces. If I run this in the applet viewer, I can see the status every second in my command box. You can see the applet here : applet
    The code concerning the start button's actionlistener (entire appletcode: [applet code|http://www.josroseboom.nl/PseudoRandomClusteringApplet.java]) :
              if(e.getSource()==start)
                   int[][] randomFuncties = new int[current+1][5];
                   int puntenHuidige, g, q, y, m, f;
                   boolean done;
                   Kern k;
                   for(int i = 0;i<=current;i++)
                        randomFuncties[i] = functies.getValues();
                   invoer.remove(knopjes);
                   startTijd = System.currentTimeMillis();
                   proces.setBounds(25,(current+4)*25, 2*this.getWidth()/3,75);
                   invoer.add(proces);
                   this.validate();
                   this.repaint();
                   for(int i = 0;i<=current;i++)
                        puntenHuidige = 0;
                        f = randomFuncties[i][0]; // important for instantiation of k, which is cut out here
                        done = false;
                        k.start();     // k is a Thread where heavy calculations are done
                        ((JLabel)(proces.getComponent(2))).setText("points done of current (" + q + ")");
                        this.repaint();
                        while(!done)
                             ((JLabel)(proces.getComponent(1))).setText("" + convertTime(System.currentTimeMillis() - startTijd));
                             ((JLabel)(proces.getComponent(3))).setText("" + k.getPuntenGehad()); // get the point done so far
                             ((JLabel)(proces.getComponent(5))).setText("" + ((100*k.getPuntenGehad())/q) + "%");
                             debug("q: " + q);
                             debug("point done: " + k.getPuntenGehad());
                             if(k.getPuntenGehad()==q)     //if all points are considered
                                  done=true;
                             this.validate();
                             this.repaint();
                             try
                                  Thread.sleep(1000);
                             catch(InterruptedException exception)
                                  debug("foutje met slapen: InterruptedException");
                             catch(IllegalMonitorStateException exception)
                                  debug("foutje met wachten: IllegalMonitorStateException");
                             debug("IN APPLET: yet another loop walk");
                        stringResultaten.add(k.geefResultaat());
                   klaarLabel.setBounds(this.getWidth()/4,(current+8)*25, this.getWidth()/2,25);
                   naarResultaat.setBounds(25+this.getWidth()/4,(current+9)*25, this.getWidth()/4,25);
                   invoer.add(klaarLabel);
                   invoer.add(naarResultaat);
                   this.validate();
                   this.repaint();
    Edited by: Jos on Sep 19, 2007 1:22 AM

    Never do anything that takes more than a fraction of a second in an actionPerformed method or similar GUI callback.
    The GUI stuff is all handled by a single thread called the "AWT Dispatcher" thread. That includes code in such callbacks. While it's executing your callback it can't do any kind of screen updating or response to other user events.
    Instead your actionPerformed should work with a separater "worker" thread, either it should launch a new thread, or release one you create (using wait and notify). Then, it returns without waiting. When the worker thread wants to update the GUI it uses EventQueue.invokeLater() or invokeAndWait() to run some (fast) code on the Dispatcher thread.

  • Copy in sand-boxed app. in 1.6.0_24+

    <ul>
    <li>Problem Summary
    <li>Question
    <li>Typical Output
    <li>See Also
    <li>Accumulated Results
    <ul>
    <li>Not grabbing focus
    <li>Grabbing focus
    </ul>
    <li>Source
    <ul>
    <li>PropertyProbe.java
    <li>propertyprobe.jnlp
    <li>js.html
    <li>Java Scripts
    </ul>
    <li>Post Revisions
    </ul>
    <h2><a name="summary"></a>Problem Summary</h2>
    A security bug was fixed recently in the JRE (1.6.0_24 in Sun's JRE). The result of the fix is that sand-boxed apps. no longer provide 'Ctrl-c' copy (or cut/paste) functionality by default on text output controls like JTextArea & JTable.
    While Ctrl-c copy no longer works by default, it is possible to add the functionality back in for any applet run in a 'Next Generation' Java Plug-In. Since Java Web Start existed, JWS provided sand-boxed copy via. the JNLP API's javax.jnlp.ClipboardService, & since Sun 1.6.0_10, & the next gen. plug-in, embedded applets can be deployed using JWS & can access the JNLP API.
    I have redesigned an applet that relied on the old functionality, to now use the JNLP API Services if available.
    <h2><a name="question"></a>Question</h2>
    Does it work for you?
    To answer that question:
    <ol>
    <li>Surf on over to the applet at http://pscode.org/prop/js.html and attempt to copy the data. See the instructions in the page for details of how to copy using the old and new forms of the applet. If the button appears, you should be prompted as to whether to allow the copy.
    <li>Paste the data here (assuming the copy is successful). Or report if it fails to copy or the applet fails to appear.
    </ol>
    <h2><a name="egoutput"></a>Typical Output</h2>
    This is what you might see at the applet.
    ||Property||Value||
    |java.version|1.6.0_24|
    |java.vendor|Sun Microsystems Inc.|
    |os.name|Windows 7|
    |os.version|6.1|
    <h2><a name="related"></a>See Also</h2>
    This relates to the thread Copy & Paste Function in Java JDK 6 Update 24. That thread contains some interesting comments, including:
    <ul>
    <li>A link to Sami Koivu's blog entry that explains the security bug.
    <li>My Re: Copy & Paste Function in Java JDK 6 Update 24 table.
    </ul>
    <h2><a name="results"></a>Accumulated Results</h2>
    <p>The first form of the applet showed a variety of problems with 'post copy focus', if the security prompt appeared in the JWS form of the applet.
    <h3><a name="nograbfocus"></a>Not grabbing focus</h3>
    ||Reporter||Browser||Version||OS name||OS version||Java Vendor||Java version||Focus post dialog||Comments||
    |Andrew Thompson|IE|8.0.7600.16385|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|applet|(1)|
    |Andrew Thompson|Chrome|10.0.648.151|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|page|(2)|
    |Andrew Thompson|FF|3.6.16|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|*nothing*|(3)|
    |Walter Laan|FF|3.6.16|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_20|*locked*|(4)|
    |almightywiz|FF|3.6.16|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|?|(5)|
    |camickr|IE|8|Windows XP|5.1|Sun Microsystems Inc.|1.6.0_07|N/A|(6)|
    |Christian|FF|3.6.15|Windows XP|5.1|Sun Microsystems Inc.|1.6.0_24|no problems|(7)|
    |Walter Laan|?|?|Windows XP|5.1|Sun Microsystems Inc.|1.7.0-ea|page?|(8)|
    |abillconsl|FF|3.6.13|Windows XP|5.1|Sun Microsystems Inc.|1.6.0_12|?|(9)|
    <ol>
    <li>Makes 'Ding' sound when copying the alert is dismissed (who said MS was not security conscious?).
    <li>The only way to refocus the applet in Chrome is to click in it with the mouse.
    <li>'Alt space' allowed me to minimize/restore FF, but no key combo. I could think of would restore focus to controls in the browser or applet.
    <li>Reported serious problems with focus for FF on 1st start-up using 1.6.0_20 JRE. Unable to reproduce on the 1.6.0_24 JRE. Ref. {message:id=9470476}, {message:id=9470587}
    <li>Reported no problems with focus. Ref. {message:id=9470371}
    <li>1st report for a pre plug-in2 JRE. IE 8 produced no prompts (as expected), so the 'Focus post dialog' does not apply. No auditory warnings. Ref. {message:id=9470761}
    <li>'No problems with focus.'. Ref. {message:id=9474121}
    <li>Focus returned to page, presumably. Ref. {message:id=9474513}
    <li>Ctrl-a seemed to do nothing. No mention of focus. Ref. {message:id=9477829}
    </ol>
    <h3><a name="grabfocus"></a>Grabbing focus</h3>
    <p>The second form of the applet has a provision to grab the focus immediately after the copy (and presumably after the trust dialog).
    ||Reporter||Browser||Version||OS name||OS version||Java Vendor||Java version||Focus post dialog||Comments||
    |camickr|IE|8|Windows XP|5.1|Sun Microsystems Inc.|1.6.0_07|N/A|(1)|
    |Andrew Thompson|IE|8.0.7600.16385|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|applet|-|
    |Andrew Thompson|Chrome|10.0.648.151|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|applet|-|
    |Andrew Thompson|FF|3.6.16|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|applet|-|
    |Paŭlo Ebermann|FF?|?|Linux2.6.34.7-0.7-desktop|2.6.34.7-0.7-desktop|Sun Microsystems Inc.|1.6.0_20|?|(2)|
    |bogdana|IE|9.0.8112.16421|Windows 7 |6.1|Sun Microsystems Inc.|1.6.0_22 |applet|(3)|
    <ol>
    <li>The first result for camickr can be inferred from the fact that a pre plug-in2 applet should behave the same in both forms of the applet. Ref. {message:id=9470761}
    <li>There are further updates on that thread that have not yet been reflected here. See the thread for details. Ref. P.E. comments at SO
    <li>Also reported the auditory warning in IE when dialog disappears. Ref. {message:id=9488352}
    </ol>
    <h3><a name="java"></a>PropertyProbe.java</h3>
    package org.pscode.tool.property;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.StringSelection;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.EmptyBorder;
    import java.util.Locale;
    import java.security.AccessControlException;
    import javax.jnlp.*;
    /** Adds a comma delimited list of property names defined in the
    props param, to the constructor of a new PropertiesPanel and
    displays it. */
    public class PropertyProbe extends JApplet {
        static String[] defaultProps = {
            "os.name",
            "os.version",
            "os.arch",
            "java.vendor",
            "java.version",
            "java.vm.version",
            "default_locale",
            "display_mode",
            "win.highContrast.on",
            "win.text.fontSmoothingOn",
            "win.defaultGUI.font",
            "awt.font.desktophints",
            "awt.mouse.numButtons",
            "awt.multiClickInterval"
        public void init() {
            String propertyNames = getParameter("prop");
            String[] props;
            if (propertyNames==null) {
                //getContentPane().add( new JLabel("Must specify 'prop' to query!") );
                props = defaultProps;
            } else {
                props = propertyNames.split(",");
            boolean grabFocus = getParameter("jnlp.grab.focus")!=null;
            System.out.println("jnlp.grab.focus: " + grabFocus);
            boolean jnlpServicesAvailable = getParameter("jnlp.launched")!=null;
            PropertyPanel pp = new PropertyPanel(props, jnlpServicesAvailable, grabFocus);
            pp.setPreferredSize(new Dimension(200,140));
            getContentPane().add( pp );
            validate();
        public static void main(final String[] args) {
            Runnable r = new Runnable() {
                public void run() {
                    String[] props = defaultProps;
                    if (args.length>0) {
                        props = args;
                    boolean jnlpServicesAvailable = false;
                    try {
                        Class.forName("javax.jnlp.ServiceManager");
                        jnlpServicesAvailable = true;
                        System.out.println("JNLP services available!");
                    } catch(Throwable t) {
                        t.printStackTrace();
                        System.out.println("JNLP services ***NOT*** available!");
                    PropertyPanel pp = new PropertyPanel(props, jnlpServicesAvailable, false);
                    pp.setPreferredSize(new Dimension(200,200));
                    JPanel mainPanel = new JPanel(new BorderLayout());
                    mainPanel.setPreferredSize(new Dimension(400,200));
                    mainPanel.add( pp );
                    JFrame f = new JFrame("Property Probe");
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.setContentPane(mainPanel);
                    f.pack();
                    try {
                        f.setLocation(50,50);
                        f.setLocationRelativeTo(null);
                        f.setLocationByPlatform(true);
                        f.setMinimumSize( f.getSize() );
                    } catch(Exception e) {
                    f.setVisible(true);
            EventQueue.invokeLater(r);
    class PropertyPanel extends JPanel {
        /** The JNLP API service used for copy in apps. deployed using JWS. */
        private ClipboardService clipboardService;
        private boolean grabFocus = false;
        private JTable table;
        /** A widget (JTable) of values for properties specified in the
        array of property names.  The properties are sourced from the
        system, environment and AWT toolkit properties.If there is no
        value defined in one of those three, 'null' is displayed. */
        PropertyPanel(String[] props, boolean jnlpServicesAvailable, boolean grabFocus) {
            super(new BorderLayout());
            this.grabFocus = grabFocus;
            setBorder( new EmptyBorder(5,5,5,5) );
            String[][] propValuePairs = new String[props.length][2];
            for ( int ii=0; ii<props.length; ii++ ) {
                propValuePairs[ii][0] = props[ii];
                propValuePairs[ii][1] = getProperty( props[ii] );
            String[] header = {"Property","Value"};
            table = new JTable( propValuePairs, header );
            try {
                table.setAutoCreateRowSorter(true);
            } catch (Exception e) {
                // pre 1.6 JRE, go with an unsorted table
            this.add( new JScrollPane( table ) );
            if (jnlpServicesAvailable) {
                try {
                    clipboardService =
                        (ClipboardService)ServiceManager.
                            lookup("javax.jnlp.ClipboardService");
                    Action action = new CopyAction(
                        "Copy",
                        null,
                        "Copy data",
                        new Integer(KeyEvent.VK_CONTROL+KeyEvent.VK_C));
                    table.getActionMap().put( "copy", action );;
                    final JButton copy = new JButton("Copy to clipboard");
                    copy.setMnemonic('c');
                    copy.addActionListener( action );
                    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                    bottomPanel.add(copy);
                    add(bottomPanel, BorderLayout.SOUTH);
                // Expecting only javax.jnlp.UnavailableServiceException.  But if we
                // try to catch it, we get a NoClassDefFoundError in non JWS apps.!
                } catch(Throwable use) {
                    use.printStackTrace();
                    System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        /** Check for properties in the order of the toolkit, system
        then environment, on the basis that all the toolkit properties
        are    available to sandboxed apps., as well as some of the system
        properties, but none of the environment properties. */
        public String getProperty(String prop) {
            String value = null;
            if ( prop.equals("default_locale") ) {
                return Locale.getDefault().toString();
            if ( prop.equals("display_mode") ) {
                return getDisplayModeString();
            value = getDesktopProperty(prop);
            if (value!=null) {
                return value;
            value = getSystemProperty(prop);
            if (value!=null) {
                return value;
            value = getEnvironmentProperty(prop);
            if (value!=null) {
                return value;
            return "null";
        public String getSystemProperty( String prop ) {
            try {
                return System.getProperty( prop );
            } catch(AccessControlException ace) {
                // this property is either restricted, /or/ 'null'
                // the plug-in will not reveal which, for a sandboxed
                // app.
                return "unknown";
        public String getEnvironmentProperty(String prop) {
            try {
                Object value = System.getenv().get(prop);
                if (value==null) {
                    return null;
                } else {
                    return value.toString();
            } catch(AccessControlException ace) {
                return null;
        public String getDesktopProperty(String prop) {
            Object value = Toolkit.
                getDefaultToolkit().
                getDesktopProperty(prop);
            if (value==null) {
                return null;
            } else {
                return value.toString();
        public String getDisplayModeString() {
            DisplayMode dm = GraphicsEnvironment.
                getLocalGraphicsEnvironment().
                getDefaultScreenDevice().
                getDisplayMode();
            String value =
                dm.getWidth()
                +
                "x"
                +
                dm.getHeight()
                +
                +
                dm.getRefreshRate()
                +
                "Hz "
                +
                dm.getBitDepth()
                +
                "bit"
            return value;
        public void copyData(Component source) {
            TableModel model = table.getModel();
            StringBuilder sb = null;
            if (true) {
                sb = new StringBuilder();
                for (int ii=0; ii<model.getRowCount(); ii++) {
                    for (int jj=0; jj<model.getColumnCount(); jj++) {
                        sb.append( model.getValueAt(ii,jj).toString() );
                        sb.append( "\t" );
                    sb.append( "\n" );
            String s = sb.toString();
            if (s==null || s.trim().length()==0) {
                JOptionPane.showMessageDialog(this,
                    "There is no data in the table!");
            } else {
                StringSelection selection =
                    new StringSelection(s);
                clipboardService.setContents( selection );
            if (grabFocus) {
                source.requestFocus();
        class CopyAction extends AbstractAction {
            public CopyAction(String text, ImageIcon icon,
                String desc, Integer mnemonic) {
                super(text, icon);
                putValue(SHORT_DESCRIPTION, desc);
                putValue(MNEMONIC_KEY, mnemonic);
            public void actionPerformed(ActionEvent e) {
                copyData((Component)e.getSource());
    }<h3><a name="jnlp"></a>propertyprobe.jnlp</h3>
    <?xml version='1.0' encoding='UTF-8' ?>
    <jnlp spec='1.0'
        href='propertyprobe.jnlp'>
        <information>
            <title>Property Probe</title>
            <vendor>PSCode.org - Andrew Thompson</vendor>
            <description kind='one-line'>
                Table for common Java properties.
            </description>
            <shortcut online='false'>
                <desktop/>
            </shortcut>
        </information>
        <resources>
            <j2se version='1.2+' />
            <jar href='propprobe.jar' main='true' />
        </resources>
        <applet-desc
            main-class='org.pscode.tool.property.PropertyProbe'
            name='applet'
            width='600'
            height='300' >
            <param name='jnlp.launched' value='true' />
        </applet-desc>
    </jnlp><h3><a name="html"></a>js.html</h3>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <HTML>
    <HEAD>
    <title>
    Property Probe - applet
    </title>
    <script type='text/javascript' src="http://www.java.com/js/deployJava.js"></script>
    <script type='text/javascript' src='http://pscode.org/file/urlcode.js'></script>
    <script type='text/javascript' src='http://pscode.org/file/queryprm.js'></script>
    <script type='text/javascript' src='http://pscode.org/file/urlquery.js'></script>
    <script type='text/javascript' src='http://pscode.org/file/appletparams.js'></script>
    <script type='text/javascript'>
    archiveName = "";
    if (true) {
        archiveName = 'propprobe.jar';
    } else {
        archiveName = 'propprobe-trusted.jar';
    var attributes = {
        code:'org.pscode.tool.property.PropertyProbe',
        codebase:'../lib',
        archive:archiveName,
        width:'600',
        height:'400'
    var version = '1.2';
    var params;
    params.jnlp_href='../lib/propertyprobe.jnlp';
    </script>
    </HEAD>
    <BODY>
    <H1>Property Probe</H1>
    <script type='text/javascript'>
    deployJava.runApplet( attributes, params, version );
    </script>
    <P>.. (text & instructions)
    </BODY>
    </HTML><h3><a name="scripts"></a>JavaScripts linked in the HTML</h3>
    'Sold separately' - pull them by direct fetch into your browser window, if you're that interested.
    <h2><a name="revisions"></a>Post Revisions</h2>
    Edited by: Andrew Thompson on Mar 26, 2011 5:32 AM
    Changed subject.
    Edited by: Andrew Thompson on Mar 26, 2011 5:19 PM
    Added accumulated results and index, other tweaks.
    Edited by: Andrew Thompson on Mar 31, 2011 11:08 AM
    Removed 'how output appears in code tags'. Added latest results, 'grab focus' results. Changed URL to invoke 'grab focus'.
    Edited by: Andrew Thompson on Apr 2, 2011 4:20 AM
    Added 1st result from SO - on Linux system.
    Edited by: Andrew Thompson on Apr 2, 2011 6:15 AM
    Added latest result.

    Walter Laan wrote:
    almightywiz wrote:
    Walter Laan wrote:
    The security popup really messes with the focus in Firefox (3.6.16) though.Not saying you're wrong, but I'm using FireFox 3.6.16, as well, and I have none of the focus troubles you've described.Cannot reproduce it now either. Weird.I got the impression you were referring to keyboard focus, so I did some further tests on focus behavior. The test results are listed in the Accumulated Results table on the 1st post.
    The only browser so far that works as I'd expect, or at least as I'd like, is IE.
    Applets and keyboard navigation have always been a PITA. Some time ago I vaguely recall seeing an update involving a new parameter to regulate initial focus (applet or page, ..or another applet), but for the life of me I cannot locate it now. Given that it was a parameter for initial focus, I doubt it would help in this case.
    Edited by: Andrew Thompson on Mar 26, 2011 6:18 PM
    Removed table which has now been expanded & added to 1st post.

  • JButtons in JToolbar don't work with JApplet- why?

    I made a JApplet which has a toolbar, populated with burrons that manipulate data from text files. The programs works perfectly when it is not a JApplet. However, once I converted it to a JApplet it does nothing. The code was exactly the same, but, pressing buttons does nothing when it is an applet. here is the complete code;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class CSE extends JApplet implements ActionListener, ItemListener
    //GUI COMPONENTS
    //ToolBar components
    JToolBar mainSelect = new JToolBar("Materials");
    JButton materials;
    String materialNames[] = {"Fur Square", "Bolt of Linen", "Bolt of Damask", "Bolt of Silk", "Glob of Ectoplasm", "Steel Ingot", "Deldrimor Steel Ingot", "Monstrous Claw", "Monstrous Eye", "Monstrous Fang", "Ruby", "Lump of Charcoal", "Obsidian Shard", "Tempered Glass Vial", "Leather Square", "Elonian Leather Square", "Vial of Ink", "Roll of Parchment", "Roll of Vellum", "Spiritwood Plank", "Amber Chunk", "Jadeite Shard"};
    ImageIcon materialIcons;
    //Graphic components
    JDesktopPane mainGraph = new JDesktopPane();
    JPanel dailyGraph = new JPanel();
    JPanel weeklyGraph = new JPanel();
    JPanel finalPrices = new JPanel();
    Box graphs = Box.createHorizontalBox();
    //The Console
    JFrame CSEFrame = new JFrame();
    JSplitPane mainConsoleBackdrop = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    JSplitPane dataOut = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    JTextArea prediction = new JTextArea(10,10);
    JScrollPane predictionScroll;
    Box finalPricesLabels = Box.createVerticalBox();
    Box finalPricesLay = Box.createVerticalBox();
    JLabel finalBuy = new JLabel("Net Buy Price Change: 0.00");
    JLabel finalSell = new JLabel("Net Sell Price Change: 0.00");
    JLabel buySell = new JLabel("We recommend you: N/A");
    JTextArea priceUpdate = new JTextArea(10, 10);
    JTextArea priceUpdateWeekly = new JTextArea(10, 10);
    JScrollPane priceUScrollW;
    JScrollPane priceUScroll;
    JCheckBox weeklySelect = new JCheckBox("To show weekly price changes.", false);
    JCheckBox dailySelect = new JCheckBox("To show daily price changes.", true);
    ButtonGroup dataToShow = new ButtonGroup();
    //COMPONENTS FOR DATE; OBTAINING CORRECT FOLDER
    String days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    Calendar calSource = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    int day = calSource.get(Calendar.DAY_OF_MONTH);
    int month = calSource.get(Calendar.MONTH);
    int year = calSource.get(Calendar.YEAR);
    int monthCheck [] = {Calendar.JANUARY, Calendar.FEBRUARY, Calendar.MARCH, Calendar.APRIL, Calendar.MAY, Calendar.JUNE, Calendar.JULY, Calendar.AUGUST, Calendar.SEPTEMBER, Calendar.OCTOBER, Calendar.NOVEMBER, Calendar.DECEMBER};
    int dayS = day;
    int monthS = month;
    int yearS = year;
    //if there is file found
    boolean proceed = false;
    //int data for analysis
    int buyPrice;
    int currentBuyPrice;
    int sellPrice;
    int currentSellPrice;
    boolean weekly = false;
    //tools for parsing and decoding input
    String inputS = null;
    String s = null;
    Scanner [] week = new Scanner[7];
    Scanner scanner;
    int position = 0;
    //weekly tools
    String weekPos[] = {"Seventh", "Sixth", "Fifth", "Fourth", "Third", "Second", "First"};
    int dayOfWeek = 0; //0 = 7    1 = 6...
                    public JButton getToolBarButton(String s)
                        String imgLoc = "TBar Icons/" +s +".gif";
                        java.net.URL imgURL = CSE.class.getResource(imgLoc);
                        JButton button = new JButton();
                        button.setActionCommand(s);
                        button.setToolTipText(s);
                        button.addActionListener(this);
                        if(imgURL != null)
                            button.setIcon(new ImageIcon(imgURL, s));
                        else
                            button.setText(s);
                            System.err.println("Couldn't find; " +imgLoc);
                        return button;
                        public CSE()
                                   // super("Test CSE");
                                    //CSEFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                    for(int x=0; x<materialNames.length; x++)
                                        materials = getToolBarButton(materialNames[x]);
                                        mainSelect.add(materials);
                                    //checkBoxes
                                    dataToShow.add(weeklySelect);
                                    dataToShow.add(dailySelect);
                                    weeklySelect.addItemListener(this);
                                    dailySelect.addItemListener(this);
                                    // sizes
                                    setSize(850, 850);
                                    //colors and fonts
                                    weeklyGraph.setBackground(new Color(250, 30, 40));
                                    dailyGraph.setBackground(new Color(100, 40, 200));
                                    //text Manip.
                                    prediction.setLineWrap(true);
                                    priceUpdate.setLineWrap(true);
                                    //scrolling
                                    predictionScroll = new JScrollPane(prediction, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                                    priceUScroll = new JScrollPane(priceUpdate, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                                    priceUScrollW = new JScrollPane(priceUpdateWeekly, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                                    //main splitpane config.
                                    mainConsoleBackdrop.setOneTouchExpandable(true);
                                    mainConsoleBackdrop.setResizeWeight(.85);
                                    //placement and Layout
                                    //GraphLayout
                                    graphs.add(Box.createHorizontalStrut(10));
                                    graphs.add(dailyGraph);
                                    graphs.add(Box.createHorizontalStrut(10));
                                    graphs.add(weeklyGraph);
                                    graphs.add(Box.createHorizontalStrut(10));
                                    dataOut.setRightComponent(predictionScroll);
                                    //consoleData layout
                                    finalPricesLabels.add(Box.createVerticalStrut(10));
                                    finalPricesLabels.add(finalBuy);
                                    finalPricesLabels.add(Box.createVerticalStrut(10));
                                    finalPricesLabels.add(finalSell);
                                    finalPricesLabels.add(Box.createVerticalStrut(10));
                                    finalPricesLabels.add(buySell);
                                    finalPricesLay.add(finalPricesLabels);
                                    finalPricesLay.add(Box.createVerticalStrut(10));
                                    finalPricesLay.add(weeklySelect);
                                    finalPricesLay.add(dailySelect);
                                    finalPricesLay.add(priceUScroll);
                                    dataOut.setLeftComponent(finalPricesLay);
                                    mainConsoleBackdrop.setTopComponent(graphs);
                                    mainConsoleBackdrop.setBottomComponent(dataOut);
                                    getContentPane().add(mainConsoleBackdrop);
                                    getContentPane().add(mainSelect, BorderLayout.NORTH);
                                    //visibility
                                   // CSEFrame.setVisible(true);
                                    //return(CSEFrame);
                                        public void actionPerformed(ActionEvent e)
                                            getMonth();
                                            inputS = e.getActionCommand();
                                            FileReader newRead = null;
                                                    try {
                                                           newRead = new FileReader(monthS +"-" +dayS +"-" +yearS +"/" +inputS +".dat");
                                                           proceed = true;
                                                        catch(FileNotFoundException f)
                                                           System.out.println("File not found");
                                                           proceed = false;
                                          if(proceed)
                                          BufferedReader bufferedReader = new BufferedReader(newRead);
                                          scanner  = new Scanner(bufferedReader);
                                          scanner.useDelimiter("\n");
                                         //starts daily analysis
                                          getPrice(scanner);
                                        //starts weekly analysis
                                          weekly(inputS);
                                    public void itemStateChanged(ItemEvent e)
                                        if(weeklySelect.isSelected())
                                        priceUpdateWeekly.setText("");
                                        finalPricesLay.remove(priceUScroll);
                                        finalPricesLay.add(priceUScrollW);
                                        finalPrices.updateUI();
                                        else
                                            priceUpdate.setText("");
                                            finalPricesLay.remove(priceUScrollW);
                                            finalPricesLay.add(priceUScroll);
                                            finalPrices.updateUI();
                                    public void weekly(String inputS)
                                        weekly = true;
                                        for(int x = 0; x < 7; x++)
                                           dateToUse(month, day, year, (x+1));
                                            try
                                                    FileReader weeklySource = new FileReader(monthS +"-" +dayS +"-" +year +"/" +inputS +".dat");
                                                    BufferedReader weeklyBuffer = new BufferedReader(weeklySource);
                                                    week[x] = new Scanner(weeklyBuffer);
                                                    week[x].useDelimiter("\n");
                                                    getPrice(week[x]);
                                             catch(FileNotFoundException f)
                                                JOptionPane.showMessageDialog(this, "No such weekly files- going back;" +(x+1) +"days");
                                        weekly = false;
                                        dateReset();
                                    public void getPrice(Scanner scanner)
                                        while(scanner.hasNextLine())
                                            //puts into string the next scan token
                                            String s = scanner.next();
                                            //takes the scan toke above and puts it into an editable enviroment
                                            String [] data = s.split("\\s");
                                            for(position = 0; position < data.length; position++)
                                                        //Scanner test to make sure loop can finish, otherwise "no such line" error
                                                        if(scanner.hasNextLine()==false)
                                                        scanner.close();
                                                        break;
                                                           /*Starts data orignazation by reading from each perspective field
                                                            * 1 = day
                                                            * 2 = day of month
                                                            * 3 = month
                                                            * 4 = year
                                                           if(position == 0 && weekly == false)
                                                               String dayFromFile = data[position];
                                                                int dayNum = Integer.parseInt(dayFromFile);
                                                              priceUpdate.append(days[dayNum-1] +" ");
                                                           else if(position == 1  && weekly == false )
                                                              priceUpdate.append(data[position] + "/");
                                                           else if(position == 2 && weekly == false)
                                                              priceUpdate.append(data[position] + "/");
                                                            else if(position == 3 && weekly == false)
                                                                priceUpdate.append(data[position] +"\n");
                                                           //if it is in [buy] area, it prints and computes
                                                            else if(position == 7)
                                                                //obtains string for buy price and stores it, then prints it
                                                                String buy = data[position];
                                                            if(weekly == false)
                                                            priceUpdate.append("Buy: " +buy +"\n" );
                                                             //converts buy to string
                                                            currentBuyPrice = Integer.parseInt(buy);
                                                            //eliminates problems caused by no data from server- makes the price 0
                                                            if(currentBuyPrice < 0)
                                                                currentBuyPrice = 0;
                                                            //if it is greater it adds
                                                            if(currentBuyPrice > buyPrice)
                                                                     buyPrice += currentBuyPrice;
                                                            //if it is equal [there is no change] then it does nothing    
                                                            if(currentBuyPrice == buyPrice)
                                                                buyPrice +=0;
                                                            //if there is a drop, it subtracts
                                                               else
                                                                   buyPrice -= currentBuyPrice;
                                                            //if it is in [sell] area, it prints, and resets the position to zero because line is over
                                                            else if(position == 8)
                                                                //puts sell data into string and prints it
                                                                String sell = data[position];
                                                                if(weekly == false)
                                                                priceUpdate.append("Sell: " + sell +"\n");
                                                                //turns sell data into int.
                                                              currentSellPrice = Integer.valueOf(sell).intValue();;
                                                            //gets rid of problems caused by no data on server side- makes it 0 
                                                            if(currentSellPrice < 0)
                                                                currentSellPrice = 0;
                                                            //adds if there is an increase
                                                            if(currentSellPrice > sellPrice)
                                                                     sellPrice += currentSellPrice;
                                                            //does nothing if it is the same    
                                                            if(currentSellPrice == sellPrice)
                                                                sellPrice +=0;
                                                            //subtracts if there is drop
                                                               else
                                                                   sellPrice -= currentSellPrice;
                                                                //further protection against "No such line" and moves it down
                                                               if(scanner.hasNextLine() == true)
                                                                scanner.nextLine();
                                                                //if scanner is finished, prints out all lines
                                                               if(scanner.hasNextLine() == false && weekly == false)
                                                                finalBuy.setText("Net Buy Price Change: "+buyPrice);
                                                                finalSell.setText("Net Sell Price Change: " +sellPrice);
                                                                buyPrice = 0;
                                                                sellPrice = 0;
                                                                position = data.length;
                                                               else if(scanner.hasNextLine() == false && weekly == true)
                                                                   priceUpdateWeekly.append("\n" +weekPos[dayOfWeek] +" day of the week ended with; \nBuy Price;" +buyPrice +"\nSell Price;" +sellPrice);
                                                                   buyPrice = 0;
                                                                   sellPrice = 0;
                                                                   position = data.length;
                                                                   dayOfWeek++;
                                                                   if(dayOfWeek > 6)
                                                                   dayOfWeek = 0;
                                public void getMonth()
                                    for(int x=0; x < monthCheck.length; x++)
                                        if(month == monthCheck[x])
                                              monthS = (x+1);
                                              x = monthCheck.length;
                                 public void dateToUse(int month, int day, int year, int increment)
                                 //set day of source
                                  dayS = (day - increment);
                                //if day of source is less then O then we have moved to another month 
                                if(dayS <= 0)
                                        //checks the difference between how much we have incremented and the day we have started; this tells us how far into the new month we are
                                        int incrementDay = increment - day;
                                        //decrements month
                                        monthS--;
                                        //if month is less then zero, then we have moved into another year and month has become 12
                                        if(monthS <= 0)
                                            yearS--;
                                            monthS = 12;
                                        //the following looks at the current month and if it goes below it assigns the day to the proper ammount of days of the month before minus the days into the month
                                           if(month == 3)
                                               dayS = 28 - incrementDay;
                                           else if(month == 5 || month == 7)
                                               dayS = 29 - incrementDay;
                                           else if(month == 2 || month == 4 || month == 6 || month == 9 || month == 11)
                                               dayS = 31 - incrementDay;
                                            else
                                                dayS = 30 - incrementDay;
                               //resets the source date to the current date once data from the week has been reached
                                public void dateReset()
                                    dayS = day;
                                    monthS = month;
                                    yearS = year;
                     public void init()
                         //JFrame frame = new CSEFrameSet();
                        // this.setContentPane(CSEFrameSet());
                        CSE aCSE = new CSE();
    public static void main(String [] args)
    CSE cs = new CSE();
    }I have tried uploading it to a server, running it from appletviewer, and locally using the .HTML file. The GUI works fine, everything is there, however, pressing the buttons does nothing.
    Can you not use the Scanners and such with JApplets?
    Yes, the directories are good.
    EDIT EDIT EDIT; OK, it works with appletviewer, but still doesn't work when it is published.
    Message wa

    I can't seem to edit the post anymore, here it is again;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class CSE extends JApplet implements ActionListener, ItemListener
    //GUI COMPONENTS
    //ToolBar components
    JToolBar mainSelect = new JToolBar("Materials");
    JButton materials;
    String materialNames[] = {"Fur Square", "Bolt of Linen", "Bolt of Damask", "Bolt of Silk", "Glob of Ectoplasm", "Steel Ingot", "Deldrimor Steel Ingot", "Monstrous Claw", "Monstrous Eye", "Monstrous Fang", "Ruby", "Lump of Charcoal", "Obsidian Shard", "Tempered Glass Vial", "Leather Square", "Elonian Leather Square", "Vial of Ink", "Roll of Parchment", "Roll of Vellum", "Spiritwood Plank", "Amber Chunk", "Jadeite Shard"};
    ImageIcon materialIcons;
    //Graphic components
    JDesktopPane mainGraph = new JDesktopPane();
    JPanel dailyGraph = new JPanel();
    JPanel weeklyGraph = new JPanel();
    JPanel finalPrices = new JPanel();
    Box graphs = Box.createHorizontalBox();
    //The Console
    JFrame CSEFrame = new JFrame();
    JSplitPane mainConsoleBackdrop = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    JSplitPane dataOut = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    JTextArea prediction = new JTextArea(10,10);
    JScrollPane predictionScroll;
    Box finalPricesLabels = Box.createVerticalBox();
    Box finalPricesLay = Box.createVerticalBox();
    JLabel finalBuy = new JLabel("Net Buy Price Change: 0.00");
    JLabel finalSell = new JLabel("Net Sell Price Change: 0.00");
    JLabel buySell = new JLabel("We recommend you: N/A");
    JTextArea priceUpdate = new JTextArea(10, 10);
    JTextArea priceUpdateWeekly = new JTextArea(10, 10);
    JScrollPane priceUScrollW;
    JScrollPane priceUScroll;
    JCheckBox weeklySelect = new JCheckBox("To show weekly price changes.", false);
    JCheckBox dailySelect = new JCheckBox("To show daily price changes.", true);
    ButtonGroup dataToShow = new ButtonGroup();
    //COMPONENTS FOR DATE; OBTAINING CORRECT FOLDER
    String days[] = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
    Calendar calSource = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    int day = calSource.get(Calendar.DAY_OF_MONTH);
    int month = calSource.get(Calendar.MONTH);
    int year = calSource.get(Calendar.YEAR);
    int monthCheck [] = {Calendar.JANUARY, Calendar.FEBRUARY, Calendar.MARCH, Calendar.APRIL, Calendar.MAY, Calendar.JUNE, Calendar.JULY, Calendar.AUGUST, Calendar.SEPTEMBER, Calendar.OCTOBER, Calendar.NOVEMBER, Calendar.DECEMBER};
    int dayS = day;
    int monthS = month;
    int yearS = year;
    //if there is file found
    boolean proceed = false;
    //int data for analysis
    int buyPrice;
    int currentBuyPrice;
    int sellPrice;
    int currentSellPrice;
    boolean weekly = false;
    //tools for parsing and decoding input
    String inputS = null;
    String s = null;
    Scanner [] week = new Scanner[7];
    Scanner scanner;
    int position = 0;
    //weekly tools
    String weekPos[] = {"Seventh", "Sixth", "Fifth", "Fourth", "Third", "Second", "First"};
    int dayOfWeek = 0; //0 = 7 1 = 6...
    public JButton getToolBarButton(String s)
    String imgLoc = "TBar Icons/" +s +".gif";
    java.net.URL imgURL = CSE.class.getResource(imgLoc);
    JButton button = new JButton();
    button.setActionCommand(s);
    button.setToolTipText(s);
    button.addActionListener(this);
    if(imgURL != null)
    button.setIcon(new ImageIcon(imgURL, s));
    else
    button.setText(s);
    System.err.println("Couldn't find; " +imgLoc);
    return button;
    public CSE()
    // super("Test CSE");
    //CSEFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    for(int x=0; x<materialNames.length; x++)
    materials = getToolBarButton(materialNames[x]);
    mainSelect.add(materials);
    //checkBoxes
    dataToShow.add(weeklySelect);
    dataToShow.add(dailySelect);
    weeklySelect.addItemListener(this);
    dailySelect.addItemListener(this);
    // sizes
    setSize(850, 850);
    //colors and fonts
    weeklyGraph.setBackground(new Color(250, 30, 40));
    dailyGraph.setBackground(new Color(100, 40, 200));
    //text Manip.
    prediction.setLineWrap(true);
    priceUpdate.setLineWrap(true);
    //scrolling
    predictionScroll = new JScrollPane(prediction, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    priceUScroll = new JScrollPane(priceUpdate, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    priceUScrollW = new JScrollPane(priceUpdateWeekly, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    //main splitpane config.
    mainConsoleBackdrop.setOneTouchExpandable(true);
    mainConsoleBackdrop.setResizeWeight(.85);
    //placement and Layout
    //GraphLayout
    graphs.add(Box.createHorizontalStrut(10));
    graphs.add(dailyGraph);
    graphs.add(Box.createHorizontalStrut(10));
    graphs.add(weeklyGraph);
    graphs.add(Box.createHorizontalStrut(10));
    dataOut.setRightComponent(predictionScroll);
    //consoleData layout
    finalPricesLabels.add(Box.createVerticalStrut(10));
    finalPricesLabels.add(finalBuy);
    finalPricesLabels.add(Box.createVerticalStrut(10));
    finalPricesLabels.add(finalSell);
    finalPricesLabels.add(Box.createVerticalStrut(10));
    finalPricesLabels.add(buySell);
    finalPricesLay.add(finalPricesLabels);
    finalPricesLay.add(Box.createVerticalStrut(10));
    finalPricesLay.add(weeklySelect);
    finalPricesLay.add(dailySelect);
    finalPricesLay.add(priceUScroll);
    dataOut.setLeftComponent(finalPricesLay);
    mainConsoleBackdrop.setTopComponent(graphs);
    mainConsoleBackdrop.setBottomComponent(dataOut);
    getContentPane().add(mainConsoleBackdrop);
    getContentPane().add(mainSelect, BorderLayout.NORTH);
    //visibility
    // CSEFrame.setVisible(true);
    //return(CSEFrame);
    public void actionPerformed(ActionEvent e)
    getMonth();
    inputS = e.getActionCommand();
    FileReader newRead = null;
    try {
    newRead = new FileReader(monthS +"-" +dayS +"-" +yearS +"/" +inputS +".dat");
    proceed = true;
    catch(FileNotFoundException f)
    System.out.println("File not found");
    proceed = false;
    if(proceed)
    BufferedReader bufferedReader = new BufferedReader(newRead);
    scanner = new Scanner(bufferedReader);
    scanner.useDelimiter("\n");
    //starts daily analysis
    getPrice(scanner);
    //starts weekly analysis
    weekly(inputS);
    public void itemStateChanged(ItemEvent e)
    if(weeklySelect.isSelected())
    priceUpdateWeekly.setText("");
    finalPricesLay.remove(priceUScroll);
    finalPricesLay.add(priceUScrollW);
    finalPrices.updateUI();
    else
    priceUpdate.setText("");
    finalPricesLay.remove(priceUScrollW);
    finalPricesLay.add(priceUScroll);
    finalPrices.updateUI();
    public void weekly(String inputS)
    weekly = true;
    for(int x = 0; x >< 7; x++)
    dateToUse(month, day, year, (x+1));
    try
    FileReader weeklySource = new FileReader(monthS +"-" +dayS +"-" +year +"/" +inputS +".dat");
    BufferedReader weeklyBuffer = new BufferedReader(weeklySource);
    week[x] = new Scanner(weeklyBuffer);
    week[x].useDelimiter("\n");
    getPrice(week[x]);
    catch(FileNotFoundException f)
    JOptionPane.showMessageDialog(this, "No such weekly files- going back;" +(x+1) +"days");
    weekly = false;
    dateReset();
    public void getPrice(Scanner scanner)
    while(scanner.hasNextLine())
    //puts into string the next scan token
    String s = scanner.next();
    //takes the scan toke above and puts it into an editable enviroment
    String [] data = s.split("\\s");
    for(position = 0; position < data.length; position++)
    //Scanner test to make sure loop can finish, otherwise "no such line" error
    if(scanner.hasNextLine()==false)
    scanner.close();
    break;
    /*Starts data orignazation by reading from each perspective field
    * 1 = day
    * 2 = day of month
    * 3 = month
    * 4 = year
    if(position == 0 && weekly == false)
    String dayFromFile = data[position];
    int dayNum = Integer.parseInt(dayFromFile);
    priceUpdate.append(days[dayNum-1] +" ");
    else if(position == 1 && weekly == false )
    priceUpdate.append(data[position] + "/");
    else if(position == 2 && weekly == false)
    priceUpdate.append(data[position] + "/");
    else if(position == 3 && weekly == false)
    priceUpdate.append(data[position] +"\n");
    //if it is in [buy] area, it prints and computes
    else if(position == 7)
    //obtains string for buy price and stores it, then prints it
    String buy = data[position];
    if(weekly == false)
    priceUpdate.append("Buy: " +buy +"\n" );
    //converts buy to string
    currentBuyPrice = Integer.parseInt(buy);
    //eliminates problems caused by no data from server- makes the price 0
    if(currentBuyPrice < 0)
    currentBuyPrice = 0;
    //if it is greater it adds
    if(currentBuyPrice > buyPrice)
    buyPrice += currentBuyPrice;
    //if it is equal [there is no change] then it does nothing
    if(currentBuyPrice == buyPrice)
    buyPrice +=0;
    //if there is a drop, it subtracts
    else
    buyPrice -= currentBuyPrice;
    //if it is in [sell] area, it prints, and resets the position to zero because line is over
    else if(position == 8)
    //puts sell data into string and prints it
    String sell = data[position];
    if(weekly == false)
    priceUpdate.append("Sell: " + sell +"\n");
    //turns sell data into int.
    currentSellPrice = Integer.valueOf(sell).intValue();;
    //gets rid of problems caused by no data on server side- makes it 0
    if(currentSellPrice < 0)
    currentSellPrice = 0;
    //adds if there is an increase
    if(currentSellPrice > sellPrice)
    sellPrice += currentSellPrice;
    //does nothing if it is the same
    if(currentSellPrice == sellPrice)
    sellPrice +=0;
    //subtracts if there is drop
    else
    sellPrice -= currentSellPrice;
    //further protection against "No such line" and moves it down
    if(scanner.hasNextLine() == true)
    scanner.nextLine();
    //if scanner is finished, prints out all lines
    if(scanner.hasNextLine() == false && weekly == false)
    finalBuy.setText("Net Buy Price Change: "+buyPrice);
    finalSell.setText("Net Sell Price Change: " +sellPrice);
    buyPrice = 0;
    sellPrice = 0;
    position = data.length;
    else if(scanner.hasNextLine() == false && weekly == true)
    priceUpdateWeekly.append("\n" +weekPos[dayOfWeek] +" day of the week ended with; \nBuy Price;" +buyPrice +"\nSell Price;" +sellPrice);
    buyPrice = 0;
    sellPrice = 0;
    position = data.length;
    dayOfWeek++;
    if(dayOfWeek > 6)
    dayOfWeek = 0;
    public void getMonth()
    for(int x=0; x < monthCheck.length; x++)
    if(month == monthCheck[x])
    monthS = (x+1);
    x = monthCheck.length;
    public void dateToUse(int month, int day, int year, int increment)
    //set day of source
    dayS = (day - increment);
    //if day of source is less then O then we have moved to another month
    if(dayS <= 0)
    //checks the difference between how much we have incremented and the day we have started; this tells us how far into the new month we are
    int incrementDay = increment - day;
    //decrements month
    monthS--;
    //if month is less then zero, then we have moved into another year and month has become 12
    if(monthS <= 0)
    yearS--;
    monthS = 12;
    //the following looks at the current month and if it goes below it assigns the day to the proper ammount of days of the month before minus the days into the month
    if(month == 3)
    dayS = 28 - incrementDay;
    else if(month == 5 || month == 7)
    dayS = 29 - incrementDay;
    else if(month == 2 || month == 4 || month == 6 || month == 9 || month == 11)
    dayS = 31 - incrementDay;
    else
    dayS = 30 - incrementDay;
    //resets the source date to the current date once data from the week has been reached
    public void dateReset()
    dayS = day;
    monthS = month;
    yearS = year;
    public void init()
    //JFrame frame = new CSEFrameSet();
    // this.setContentPane(CSEFrameSet());
    CSE aCSE = new CSE();
    public static void main(String [] args)
    CSE cs = new CSE();
    }Message was edited by:
    Cybergasm

  • How can i get the value of an jcombobox in a japplet into my html/jsp page

    hii
    i hav a japplet which contains an editable jcombobox
    which i have embedded into my jsp page .Now i want to get the value of jcombobox in my japplet into a taxt box in my .jsp page which will change as the value of jcombobox changes .Now in doing this i guess i will have to writer some public event in my japplet which will return the value into my web page .
    Now in doing so my first problem is to refer the japplet from my jsp page .In case of ordinary applets which does nt use swing i hav used id attribute in my applet tag and the document recognize it as its object just like any other html controls.
    but here although my japplet is running after installing plug -in the document is not regognizing the japplet .I hav tried with both <object > and <applet> tag .
    The name attribute in object tag is only changing the name of the class into that name given in the name attribute in the browser .
    I need to solve this out .Any help will be greatly appreciated

    Please help me .Its very urgent

  • Can a JApplet access a file to be read?

    I think I recall reading or hearing somewhere that a JApplet cannot, for "security reasons", access any files on the computer it is running on unless it is the 'original' or the one where the code is stored. What I would like to do is have a file that will be only read (not written to) by a JApplet and use the information for the applet. If I always run the JApplet with a browser on the computer where I have the code stored, will it allow me to access this file or will it still prevent me? Or can I just have the file stored in the same folder as the applet in my webpage directory so that it will be able to access it there and display it for all others on different computers?
    Thanks in advance for any insights!

    Hello forum,
    Lot of confusion's on this topic.
    Here is my understanding.The question is "Can a JApplet access a file to be read?". Answer is "No". But workaround is there.Then where the confusion is.
    I have seen kartik181 mentioned about using digital signature from verisign/similar to grant access to your local file system!
    The question asked by aachi is " ........Is it so? What is the purpose of digital signatures then?"
    Also aachi mentioned about policy file. That means to get an access to local file is something you have to do with policy file.
    bharthy explained the same in detail with some example.
    Now look at the original question posted by the author littleB.
    The answer I got from jdk 1.2 sand box model..
    "There is no longer a built-in concept that all local code is trusted. Instead, local code (e.g., non-system code, application packages installed on the local file system) is subjected to the same security control as applets, although it is possible, if desired, to declare that the policy on local code (or remote code) be the most liberal, thus enabling such code to effectively run as totally trusted. The same principle applies to signed applets and any Java application."
    So if you want to do your applet (whether you store locally or remotely in the path of webserver) you would end up an easy way of changing policy file by allowing more easily to do the specific job.
    Hope it gives a bit clear picture of it.

  • Help needed: Creating web link in JDialog Box

    I'm in need of this urgently, any help would be much appreciated. I'm currently display some information in a JDialog box when an item is clicked in a JApplet.
    I need to display a weblink within the dialog box.
    Thanks anyone

    I am using JDeveloper 10.1.3.3.0. Thanks Heaps

  • Netbeans nightmare Converting a JFrame  class to a JApplet Class

    Hello im not exactly new to java but im having problems getting my applets to work when i try other peoples example applets they always work but mine never seem to. here is what i am doing i wrote a card game in VB6 long story short i completely rewrote it in java because only ie supports ActiveX.
    It works awesome as a stand alone App whilst in Jframe and with a main() sub.
    I tried about 15 tutorials on how to convert a jframe to a applet with no success i always got errors and applet never loaded in browser.
    then i found these tips on how to do it "really easy" of course when my applet loads and im not sure it even really does i get nothing but a grey box i never seem my components a bunch of jlabels with icons loaded that look like card images it all looks great in the design tab of NetBeans. I never see any of the controls in browser. These are the links to the two tutorials that spawned my trying this. http://forums.java.net/jive/thread.jspa?threadID=57965&tstart=0 http://forums.java.net/jive/thread.jspa?threadID=57965&tstart=0
    well to quote this guy it feels like its going to take 100 years to figure this out google has a million links to junk when i try searches and sun has no great help for searching either on their documentation. my program is rediculously low tech and i cant seem to get it to do anything or work at all as an applet.
    my class looks like this: i removed all the constructor code as it was making post too long my applet shows up normal in the preview window of Netbenas but just a grey square of browser not sure whats wrong please someone help me.. Thanks You
    import java.util.Random;
    public class AcesKingsJApplet extends javax.swing.JApplet {
    /** Initializes the applet AcesKingsJApplet */
    public void init() {
    try {
    java.awt.EventQueue.invokeAndWait(new Runnable() {
    public void run() {
    initComponents();
    System.out.println("InitCOmpleted");
    // NewGame(1);
    } catch (Exception ex) {
    ex.printStackTrace();
    public void TableCardClick(int arg1){
    public void DiscardPileClick(int arg1){
    public void PerformUndoAction(){
    public void NewGame(int arg1){
    //new game code here
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel26;
    private javax.swing.JLabel jLabel27;
    private javax.swing.JLabel jLabel28;
    private javax.swing.JLabel jLabel29;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel30;
    private javax.swing.JLabel jLabel31;
    private javax.swing.JLabel jLabel32;
    private javax.swing.JLabel jLabel33;
    private javax.swing.JLabel jLabel34;
    private javax.swing.JLabel jLabel35;
    private javax.swing.JLabel jLabel36;
    private javax.swing.JLabel jLabel37;
    private javax.swing.JLabel jLabel38;
    private javax.swing.JLabel jLabel39;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel40;
    private javax.swing.JLabel jLabel41;
    private javax.swing.JLabel jLabel42;
    private javax.swing.JLabel jLabel43;
    private javax.swing.JLabel jLabel44;
    private javax.swing.JLabel jLabel45;
    private javax.swing.JLabel jLabel46;
    private javax.swing.JLabel jLabel47;
    private javax.swing.JLabel jLabel48;
    private javax.swing.JLabel jLabel49;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel50;
    private javax.swing.JLabel jLabel51;
    private javax.swing.JLabel jLabel52;
    private javax.swing.JLabel jLabel53;
    private javax.swing.JLabel jLabel54;
    private javax.swing.JLabel jLabel55;
    private javax.swing.JLabel jLabel56;
    private javax.swing.JLabel jLabel58;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel60;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration
    int tableCardIndex = 99; //array only cause it has to be or game fails
    int discardPileIndex = 99;
    int[] cardDeckArray = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54};
    int[] cardDeckArrayPlayed = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
    //int[] precheckarg1;
    boolean GoAheadWithPlay;
    int gameUndoCount;
    int gamePlayCount;
    int gameCurrentRound = 1;
    int cardPointValue;
    int discardCardValue;
    int tableCardValue;
    int tableCardsRemaining = 35;
    int discardPileCards;
    int currentDiscardPileCard;
    int playerScore;
    // loss checking variables
    int badPlaysCount = 0;
    // variables for undo related activity below
    int[] undogamePlayCount = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int[] undodiscardPileCards = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int[] undocurrentDiscardPileCard = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int[] undoMethod = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int[] undoTableCard ={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int[] undoDiscardCard ={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    //end undo variable collection
    }

    You shouldn't start a new thread when you've already created a recent one with the exact same subject matter:
    [http://forums.sun.com/thread.jspa?threadID=5447497|http://forums.sun.com/thread.jspa?threadID=5447497]
    And my advice in the previous thread still stands. Put your program in a JPanel so it's environment-agnostic, then create two wrappers for standalone apps and applets.
    (or just use Java Web Start)
    Also your program has all sorts of other problems. This is terrible coding:
    private javax.swing.JLabel jLabel37;If you need lots of labels that all have the same meaning, put them in a collection. Give things meaningful names. etc.
    If that code was generated by Netbeans....then this is an example why you shouldn't use code generation tools...

  • JOption box wont go away

    I read input from aninputdialog box inside a loop which is in a constructor for a simple graphical clock face program
    the clock is displayed in the applet, but the dialog box doesn't go away, therre is no main method for an applet, so where do i put the system.exit() or whatever so that the boxes dissappear??
    also
    is this sort of topic too newbie for this site??

    I cant really shorten it much and i understand if Its too much to help with
    thanks
    <applet code="ClockApplet.class" width="1000" height="1000" ></applet>
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JApplet;
      Draws a clock
    public class ClockApplet extends JApplet
         public void paint(Graphics g)
              Graphics2D g2 = (Graphics2D) g;
              Clock clockFace = new Clock(150, 150, 400);
              clockFace.draw(g2);
          a clock face with a minute and an hour hand
         Time is specified by the user
    import javax.swing.JOptionPane;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Line2D;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Point2D;
    public class Clock
         private double xLeft;
         private double yTop;
         private double size;
         private double hr;
         private double min;
              constructs a clock face starting at coordinate(x, y)
              and with a given size(diameter)
              @param the x coordinate of the starting point of the circle
              @param the y coordinate of the starting point of the circle
              @param the diameter of circle
         public Clock(double x, double y, double size)
              boolean validTime = false;
              xLeft = x;
              yTop = y;
              this.size = size;
              while(!validTime)
                   validTime = true;
                   String input = JOptionPane.showInputDialog("enter the time ie.(5:30) : ");
                   if(input.length() != 5 && input.length() !=4)
                        validTime = false;
                   if(validTime)
                        //checks to see if there is a colon in the right place
                        String colonString = input.substring(input.length() - 3, input.length() - 2);
                        if((colonString.equals(":") == false))
                             validTime = false;
                   if(validTime)
                        String[] time = input.split(":");
                        hr = Double.parseDouble(time[0]);
                        min = Double.parseDouble(time[1]);
                        if(min >= 60 || min < 0 || hr > 12 || hr < 1)
                             validTime = false;
                   if(!validTime)
                        JOptionPane.showMessageDialog(null, "Invalid time", "ATTENTION",
                                                      JOptionPane.INFORMATION_MESSAGE);
              draws the clock face with an hour and a minute hand
              @param Graphics2D g2
         public void draw(Graphics2D g2)
              Ellipse2D.Double circle = new Ellipse2D.Double(xLeft, yTop, size, size);
              Point2D.Double p1 = new Point2D.Double((xLeft+ size/2), (yTop + size/2));
              Line2D.Double hourHand = new Line2D.Double(p1, getHourHandCoordinate(p1));
              Line2D.Double minuteHand = new Line2D.Double(p1, getMinuteHandCoordinate(p1));
              g2.draw(circle);
              g2.draw(hourHand);
              g2.draw(minuteHand);
              returns the end point of the hour hand
              @param Point2D.Double the middle of the clock face
              @return Point2D.Double end point of the hour hand line
         public Point2D.Double getHourHandCoordinate(Point2D.Double p1)
              //centre coordinates of the clock face
              double xCentre = p1.getX();
              double yCentre = p1.getY();
              //here i make the fraction smaller so that the end points will be closer to the centre
              double smallerSize = size/2;
              //amount x, and y axies change with each minute difference
              final double INCREMENT = smallerSize/30.0;
              //fraction of an hour more that the hand needs to move
              //amount x, and y axis change with each second difference
              double fraction;
              if(min!=0)
                   fraction = min/60;
              else fraction = 0;
              //x and y of the end point of the hour hand
              double x = 0, y = 0;
              //calculates end point depending on the hour entered and the minute entered
              if(hr <= 3)
                   x = xCentre + 5 * (hr + fraction) * INCREMENT;
                   y = yCentre - 5 * (3 - hr - fraction) * INCREMENT;
              else if(hr <= 6)
                   x = xCentre + 5 * ( 6 - hr - fraction) * INCREMENT;
                   y = yCentre + 5 * (hr - 3 + fraction) * INCREMENT;
              else if(hr <=9)
                   x = xCentre - 5 * (hr - 6 - fraction) * INCREMENT;
                   y = yCentre + 5 * (9 - hr - fraction) * INCREMENT;
              else if(hr < 12)
                   x = xCentre - 5 * (12 - hr + fraction) * INCREMENT;
                   y = yCentre - 5 * (hr - 9 - fraction) * INCREMENT;
              else
                   x = xCentre + 5*fraction * INCREMENT;
                   y = yCentre - 5*( 2 + 1 - fraction) * INCREMENT;
              //creates a point object and returns it
              Point2D.Double p2 = new Point2D.Double(x, y);
              return p2;
              returns the end point of the minute hand
              @param Point2D.Double centre of clock face
              @return Point2D.Double end point of the minute hand line
         public Point2D.Double getMinuteHandCoordinate(Point2D.Double p1)
              //amount x, and y axis change with each second difference
              final double INCREMENT = size/30.0;
              //centre coordinates of the clock face
              double xCentre = p1.getX();
              double yCentre = p1.getY();
              double x = 0, y = 0;
              //calculates the end point depending on how many minutes were entered
              if(min <= 15)
                   x = xCentre + min*INCREMENT;
                   y = yCentre - (15 - min)*INCREMENT;
              else if(min <= 30)
                   x = xCentre + (30 - min)*INCREMENT;
                   y = yCentre + (min - 15)*INCREMENT;
              else if(min <= 45)
                   x = xCentre - (min - 30)*INCREMENT;
                   y = yCentre + (45 - min)*INCREMENT;
              else
                   x = xCentre - (60 - min)*INCREMENT;
                   y = yCentre - (min - 45)*INCREMENT;
              //creates a point object, and returns it
              Point2D.Double p3 = new  Point2D.Double(x, y);
              return p3;
    }Edited by: rubiconTwist on May 27, 2008 4:34 AM

  • JApplet is not working properly...

    Hi there...
    I am having a problem with my applet. Here is the code:
    package click;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    public class click1 extends JApplet implements MouseListener{
         JPanel jp;
         JButton b;
         StringBuffer buffer;
         String message;
         public void init(){
              jp = new JPanel();
              jp.setBackground(Color.white);
                        b = new JButton("click");
              b.addMouseListener(this);
              jp.add(b);
              getContentPane().add(jp, BorderLayout.WEST);
              buffer = new StringBuffer();
         public void paint(Graphics g){
              g.drawString(buffer.toString(), 80, 30);
         public void mouseClicked(MouseEvent arg0) {
              buffer.append("Click");
              repaint();
    the problem is, when I start the applet, it appears as a blank white applet and the button does not appear untill I move my mouse over it. Also when i add this applet to a html page it appears as a box with red cross in the upper left corner. Any Ideas?
    regards

    This is what the consol shows:
    java.lang.NoClassDefFoundError: click1 (wrong name: click/click1)
         at java.lang.ClassLoader.defineClass1(Native Method)
         at java.lang.ClassLoader.defineClass(Unknown Source)
         at java.security.SecureClassLoader.defineClass(Unknown Source)
         at sun.applet.AppletClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.applet.AppletClassLoader.loadCode(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    but I still didn't get it :S

  • JOptionPane in JApplet

    If I display a JOptionPane through a JApplet, it has "Applet Window" written on its status bar.
    How do I get rid of the "Applet window" status bar on the message boxes using JOptionPane?
    From practical experience of applets on the net I'm not used to
    seeing this text at the bottom - this doesn't happen in the "real world"
    does it?

    Yes, that is a part of the Java platform security mechanism - a feature that warns users so that they do not mistake it for a native application so they do not type in sensitive info which is sent back to the host.
    Getting rid of it is possible but you will need to know about security and permissions - if you grant your applet the correct AWT permission, that warning banner will disappear (for all windows that applet spawns).
    A good place to start is http://java.sun.com/docs/books/tutorial/security1.2/tour1/index.html.
    And a little bit of history: every version of the SDK watered down the warning a bit (the top one is SDK 1.0):
    "Untrusted Java Applet Window"
    "Unauthenticated Java Applet Window"
    "Warning: Java Applet Window"
    And now it is: "Java Applet Window"

Maybe you are looking for

  • OIM11gR2 - How to migrate an Application Instance Form

    Hello, I'm trying to migrate an Application Instance Form from my Dev env to my QA env. My target system is SAP I performed the following steps in Dev: 1. Installed and configured the SAP Connector (no problem here) 2. Created a sandbox 3. Created an

  • Imessage not working in dubai or apple server is down ?

    i have ipad2 and  i am facing problems with my imessage it worked for sometime then it stopped working suddenly , i dunno wether its blocked in uae or apple server for imessage or something like that is down !!!  everything is correct and i tried goo

  • Very Poor Quality Device Multiple Issues

    I have Purchased this Slate 7 Tab with Great Hope and Trust that HP is a trusted Brand...but Very soon i realised that this is the worst product HP have Launched...Immediately after it started giving problem and since last 1 Year my TAB was in HP Ser

  • HT4972 IN GPS my location does not show exactly, how can i make it exact location showing by my iphone

    In GPS my location does not show exactly, how can i make it exact location showing by my iphone

  • How to disable filter

    Hi there, I'm currently writing my first filter plugin for Photoshop (win 32 CS5 SDK) and I'm facing a problem to disable (unreachable and greyed in menu) my plugin on undesired image modes. My intention is to only enable my filter when document is i