Hot questions for Using Applets in button

Question:

I have been trying to get my JApplet to show all the buttons needed for a calculator applet in an orderly fashion, but I can't seem to get them to all be the same size and display right under each other. Should I use different a different layout or change the entire design? Thanks in advance.

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MyCalc extends JApplet implements ActionListener{

/**
 * 
 */
protected static final long serialVersionUID = 3169756252830354073L;

private JMenuBar menuBar = new JMenuBar();
private JMenu edit = new JMenu("Edit");
private JMenu view = new JMenu("View");
private JMenu help = new JMenu("Help");

//Instantiated all JPanels used in this Applet
private JPanel[] rows = {new JPanel(), new JPanel(), new JPanel(), 
        new JPanel(), new JPanel(), new JPanel(), new JPanel()};

JTextField calc = new JTextField(1);

private JButton[] buttons = {new JButton("Backspace"), new JButton("CE"), new JButton("C"), 
        new JButton("MC"), new JButton("7"), new JButton("8"), new JButton("9"), 
        new JButton("/"), new JButton("sqrt"), new JButton("MR"), new JButton("4"), 
        new JButton("5"), new JButton("6"), new JButton("*"), new JButton("%"), 
        new JButton("MS"), new JButton("1"), new JButton("2"), new JButton("3"), 
        new JButton("-"), new JButton("1/x"), new JButton("M+"), new JButton("0"), 
        new JButton("+/-"), new JButton("."), new JButton("+"), new JButton("=")};

public void actionPerformed(ActionEvent e) {

    if(e.getSource() == buttons[0])
    {

    }

}

public void init()
{
    setName("Calculator Applet");
    menuBar.add(edit);
    menuBar.add(view);
    menuBar.add(help);
    setJMenuBar(menuBar);

    rows[0].setLayout(new BoxLayout(rows[0], BoxLayout.Y_AXIS));
    getContentPane();
    add(rows[0]);
    setSize(300, 200);

    calc.setText("0.");
    calc.setHorizontalAlignment(JTextField.RIGHT);

    for(int i = 0; i < 3; i++)
    {
        rows[2].add(buttons[i]);
    }

    for(int i = 3; i < 9; i++)
    {
        rows[3].add(buttons[i]);
    }

    for(int i = 9; i < 15; i++)
    {
        rows[4].add(buttons[i]);
    }

    for(int i = 15; i < 21; i++)
    {
        rows[5].add(buttons[i]);
    }

    for(int i = 21; i < 26; i++)
    {
        rows[6].add(buttons[i]);
    }

    rows[1].add(calc);
    rows[1].setLayout(new GridLayout());
    rows[2].setLayout(new GridLayout());
    rows[0].add(rows[1]);
    rows[0].add(rows[2]);

    for(int i = 3; i < 7; i++)
    {
        rows[0].add(rows[i]);
        rows[i].setLayout(new FlowLayout(FlowLayout.CENTER));
    }

}

Answer:

"but I can't seem to get them to all be the same size and display right under each other."

Generally this screams out GridLayout. Instead of using two BoxLayout (one vertical and one horizinal) just use a GridLayout(4, 6) (for the number buttons). Keep in mind though that the size of the buttons will be the size of the largest button (which is sqrt).

Also I'd recommend staying away from keeping your panels in an array like you are doing. It's difficult to follow the flow of how you want to add everything. Give your panels (and all components for that matter) meaningful names that are self-documenting.

For general knowledge on layout managers, check out Laying out Component Within a Container

I refactored your code to be able to run it as an applet or as a standalone frame. I also wrapped all the components in a panel and set the layout manager of the content pane to GridBagLayout, so everything does get screwed up if you resize the frame

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class MyCalc extends JApplet implements ActionListener {

    /**
 * 
 */
    protected static final long serialVersionUID = 3169756252830354073L;

    private JMenuBar menuBar = new JMenuBar();
    private JMenu edit = new JMenu("Edit");
    private JMenu view = new JMenu("View");
    private JMenu help = new JMenu("Help");

    // Instantiated all JPanels used in this Applet
    //private JPanel[] rows = { new JPanel(), new JPanel(), new JPanel(),
    //      new JPanel(), new JPanel(), new JPanel(), new JPanel() };

    JTextField calc = new JTextField(1);

    private JButton[] buttons = { new JButton("Backspace"), new JButton("CE"),
            new JButton("C"), new JButton("MC"), new JButton("7"),
            new JButton("8"), new JButton("9"), new JButton("/"),
            new JButton("sqrt"), new JButton("MR"), new JButton("4"),
            new JButton("5"), new JButton("6"), new JButton("*"),
            new JButton("%"), new JButton("MS"), new JButton("1"),
            new JButton("2"), new JButton("3"), new JButton("-"),
            new JButton("1/x"), new JButton("M+"), new JButton("0"),
            new JButton("+/-"), new JButton("."), new JButton("+"),
            new JButton("=") };

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == buttons[0]) {

        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                JFrame frame = new JFrame();
                MyCalc calc = new MyCalc();
                calc.init();
                frame.add(calc);
                frame.pack();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public void init() {
        setName("Calculator Applet");
        menuBar.add(edit);
        menuBar.add(view);
        menuBar.add(help);
        setJMenuBar(menuBar);

        Container contentPane = getContentPane();

        calc.setText("0.");
        calc.setHorizontalAlignment(JTextField.RIGHT);
        JPanel topButtonPanel = new JPanel(new GridLayout(1, 0));
        for (int i = 0; i < 3; i++) {
            topButtonPanel.add(buttons[i]);
        }

        JPanel numberButtonPanel = new JPanel(new GridLayout(4, 6));
        for (int i = 3; i < 26; i++) {
            numberButtonPanel.add(buttons[i]);
        }

        JPanel centerWrapper = new JPanel(new BorderLayout());
        centerWrapper.add(calc, BorderLayout.PAGE_START);
        centerWrapper.add(topButtonPanel);
        centerWrapper.add(numberButtonPanel, BorderLayout.PAGE_END);

        contentPane.setLayout(new GridBagLayout());
        contentPane.add(centerWrapper);
    }
}

Question:

Using this code I would like to add a button to the page that displays when the gamestate is either Dead or Win. This button will let the user either start over or go on to the next level. My action listener is not yet fully coded because I can't even get the button to be visible on the page. I have tried coding in a button using

setLayout(new FlowLayout());
this.add(sOver);
sOver = new Button("Start Over");
sOver.addActionListener(this);

But that results in a an error when the game changes state.

 package androidGame;

import java.applet.Applet;
import java.awt.event.*;
import java.applet.AudioClip;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.net.*;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;




import androidGame.framework.Animation;

import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;

public class StartingClass extends Applet implements Runnable, KeyListener, ActionListener {

    enum GameState {
        Running, Dead, Win
    }

    GameState state = GameState.Running;

    private static Robot robot;
    public static Heliboy hb, hb2, hb3, hb4, hb5, hb6, hb7, hb8, hb9, hb10, hb11, hb12, hb13, hb14, hb15, hb16;
    public static int score = 0;
    public static int rHealth = 120;
    private Font font = new Font(null, Font.BOLD, 30);

    private Image image, currentSprite, character, character2, character3,
            characterDown, characterJumped, background, heliboy, heliboy2,
            heliboy3, heliboy4, heliboy5;

    public static Image tilegrassTop, tilegrassBot, tilegrassLeft,
            tilegrassRight, tiledirt, tilefire, tiledoor;

    private Graphics second;
    private URL base;
    private static Background bg1, bg2;
    private Animation anim, hanim;
    int level = 1;
    AudioClip clip;
    Button next, sOver;

    private ArrayList<Tile> tilearray = new ArrayList<Tile>();

    @Override

    public void init() {

        setSize(800, 480);
        setBackground(Color.BLACK);
        setFocusable(true);
        addKeyListener(this);
        Frame frame = (Frame) this.getParent().getParent();
        frame.setTitle("Robot Mania");
        try {
            base = getDocumentBase();
        } catch (Exception e) {
            // TODO: handle exception
        }

        // Image Setups
        character = getImage(base, "data/character.png");
        character2 = getImage(base, "data/character2.png");
        character3 = getImage(base, "data/character3.png");

        characterDown = getImage(base, "data/down.png");
        characterJumped = getImage(base, "data/jumped.png");

        heliboy = getImage(base, "data/heliboy.png");
        heliboy2 = getImage(base, "data/heliboy2.png");
        heliboy3 = getImage(base, "data/heliboy3.png");
        heliboy4 = getImage(base, "data/heliboy4.png");
        heliboy5 = getImage(base, "data/heliboy5.png");

        background = getImage(base, "data/spacebackground.png");

        tiledirt = getImage(base, "data/tiledirt.png");
        tilegrassTop = getImage(base, "data/tilegrasstop.png");
        tilegrassBot = getImage(base, "data/tilegrassbot.png");
        tilegrassLeft = getImage(base, "data/tilegrassleft.png");
        tilegrassRight = getImage(base, "data/tilegrassright.png");
        tilefire = getImage(base, "data/tilefire.png");
        tiledoor = getImage(base, "data/tiledoor.png");

        anim = new Animation();
        anim.addFrame(character, 1250);
        anim.addFrame(character2, 50);
        anim.addFrame(character3, 50);
        anim.addFrame(character2, 50);

        hanim = new Animation();
        hanim.addFrame(heliboy, 100);
        hanim.addFrame(heliboy2, 100);
        hanim.addFrame(heliboy3, 100);
        hanim.addFrame(heliboy4, 100);
        hanim.addFrame(heliboy5, 100);
        hanim.addFrame(heliboy4, 100);
        hanim.addFrame(heliboy3, 100);
        hanim.addFrame(heliboy2, 100);




        currentSprite = anim.getImage();
    }

    @Override
    public void start() {
        //Sound.MAIN.loop();
        bg1 = new Background(0, 0);
        bg2 = new Background(2160, 0);
        robot = new Robot();
        // Initialize Tiles
        try {
            loadMap("data/map"+ level +".txt");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Random random = new Random();
        int randomInt = random.nextInt(500);

        hb = new Heliboy(700, 360);
        hb2 = new Heliboy(900 + randomInt, 360);
        hb3 = new Heliboy(2300 + randomInt, 360);
        hb4 = new Heliboy(2900 + randomInt, 360);
        hb5 = new Heliboy(3400 + randomInt, 360);
        hb6 = new Heliboy(3900 + randomInt, 360);
        hb7 = new Heliboy(4300 + randomInt, 360);
        hb8 = new Heliboy(4700 + randomInt, 360);
        hb9 = new Heliboy(5000 + randomInt, 360);
        hb10 = new Heliboy(5300 + randomInt, 360);
        hb11 = new Heliboy(5700 + randomInt, 360);
        hb12 = new Heliboy(6000 + randomInt, 360);
        hb13 = new Heliboy(6300 + randomInt, 360);
        hb14 = new Heliboy(6700 + randomInt, 360);
        hb15 = new Heliboy(7000 + randomInt, 360);
        hb16 = new Heliboy(7200 + randomInt, 360);



        Thread thread = new Thread(this);
        thread.start();
    }



    private void loadMap(String filename) throws IOException {
        ArrayList lines = new ArrayList();
        int width = 0;
        int height = 0;

        BufferedReader reader = new BufferedReader(new FileReader(filename));
        while (true) {
            String line = reader.readLine();
            // no more lines to read
            if (line == null) {
                reader.close();
                break;
            }

            if (!line.startsWith("!")) {
                lines.add(line);
                width = Math.max(width, line.length());

            }
        }
        height = lines.size();

        for (int j = 0; j < 12; j++) {
            String line = (String) lines.get(j);
            for (int i = 0; i < width; i++) {

                if (i < line.length()) {
                    char ch = line.charAt(i);
                    Tile t = new Tile(i, j, Character.getNumericValue(ch));
                    tilearray.add(t);
                }

            }
        }

    }



    @Override
    public void run() {
        if (state == GameState.Running) {


            while (true) {  

                robot.update();
                if (robot.isJumped()) {
                    currentSprite = characterJumped;
                } else if (robot.isJumped() == false
                        && robot.isDucked() == false) {

                    currentSprite = anim.getImage();
                }

                ArrayList projectiles = robot.getProjectiles();
                for (int i = 0; i < projectiles.size(); i++) {
                    Projectile p = (Projectile) projectiles.get(i);
                    if (p.isVisible() == true) {
                        p.update();

                    } else {
                        projectiles.remove(i);
                    }
                }

                updateTiles();
                hb.update();
                hb2.update();
                hb3.update();
                hb4.update();
                hb5.update();
                hb6.update();
                hb7.update();
                hb8.update();
                hb9.update();
                hb10.update();
                hb11.update();
                hb12.update();
                hb13.update();
                hb14.update();
                hb15.update();
                hb16.update();
                bg1.update();
                bg2.update();
                animate();
                repaint();
                try {
                    Thread.sleep(17);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (rHealth == 0) {
                    state = GameState.Dead;                 
                    Sound.MAIN.stop();
                    //Sound.DIE.play();

                    sOver = new Button("Start Over");
                    this.add(sOver);
                    sOver.addActionListener(this);
                    sOver.setVisible(true);                 
                    revalidate();
                    repaint();
                }
                if (robot.getCenterY() > 500) {
                    state = GameState.Dead;
                    Sound.MAIN.stop();
                    //Sound.DIE.play();

                    sOver = new Button("Start Over");
                    this.add(sOver);
                    sOver.addActionListener(this);
                    sOver.setVisible(true);                 
                    revalidate();
                    repaint();

                }

                if (score == 5){
                    state = GameState.Win;
                    Sound.MAIN.stop();
                    //Sound.WIN.play();

                    next = new Button("Next Level");
                    this.add(next);
                    next.addActionListener(this);
                    next.setVisible(true);  
                    revalidate();
                    repaint();

                }
            }
        }
    }

    public void animate() {
        anim.update(10);
        hanim.update(50);
    }

    @Override
    public void update(Graphics g) {
        if (image == null) {
            image = createImage(this.getWidth(), this.getHeight());
            second = image.getGraphics();
        }

        second.setColor(getBackground());
        second.fillRect(0, 0, getWidth(), getHeight());
        second.setColor(getForeground());
        paint(second);

        g.drawImage(image, 0, 0, this);

    }



    @Override
    public void paint(Graphics g) {

        if (state == GameState.Running) {

            g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);
            g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
            paintTiles(g);

            ArrayList projectiles = robot.getProjectiles();
            for (int i = 0; i < projectiles.size(); i++) {
                Projectile p = (Projectile) projectiles.get(i);
                g.setColor(Color.BLUE);
                g.fillRect(p.getX(), p.getY(), 10, 5);
            }

            g.drawImage(currentSprite, robot.getCenterX() - 61,
                    robot.getCenterY() - 63, this);
            g.drawImage(hanim.getImage(), hb.getCenterX() - 48,
                    hb.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb2.getCenterX() - 48,
                    hb2.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb3.getCenterX() - 48,
                    hb3.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb4.getCenterX() - 48,
                    hb4.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb5.getCenterX() - 48,
                    hb5.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb6.getCenterX() - 48,
                    hb6.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb7.getCenterX() - 48,
                    hb7.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb8.getCenterX() - 48,
                    hb8.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb9.getCenterX() - 48,
                    hb9.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb10.getCenterX() - 48,
                    hb10.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb11.getCenterX() - 48,
                    hb11.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb12.getCenterX() - 48,
                    hb12.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb13.getCenterX() - 48,
                    hb13.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb14.getCenterX() - 48,
                    hb14.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb15.getCenterX() - 48,
                    hb15.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb16.getCenterX() - 48,
                    hb16.getCenterY() - 48, this);

            g.setFont(font);
            g.setColor(Color.WHITE);
            g.drawString("Health: " + Integer.toString(rHealth), 5, 30);
            g.drawString("Score: " + Integer.toString(score), 650, 30);

        } else if (state == GameState.Dead) {

            //setLayout(new FlowLayout());


            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 800, 480);
            g.setColor(Color.WHITE);
            g.drawString("You're Dead!", 300, 200);
            g.drawString("Score: " + score, 300, 250);

        }
        else if (state == GameState.Win) {
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 800, 480);
            g.setColor(Color.WHITE);
            g.drawString("You Beat this level!", 300, 200);
            g.drawString("Score: " + score, 300, 250);
            level++;

        }
    }

    private void updateTiles() {

        for (int i = 0; i < tilearray.size(); i++) {
            Tile t = (Tile) tilearray.get(i);
            t.update();
        }

    }

    private void paintTiles(Graphics g) {
        for (int i = 0; i < tilearray.size(); i++) {
            Tile t = (Tile) tilearray.get(i);
            g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {

        switch (e.getKeyCode()) {
        case KeyEvent.VK_UP:
            break;

        case KeyEvent.VK_DOWN:
            currentSprite = characterDown;
            if (robot.isJumped() == false) {
                robot.setDucked(true);
                robot.setSpeedX(0);
            }
            break;

        case KeyEvent.VK_LEFT:
            robot.moveLeft();
            robot.setMovingLeft(true);
            break;

        case KeyEvent.VK_RIGHT:
            robot.moveRight();
            robot.setMovingRight(true);
            break;

        case KeyEvent.VK_SPACE:
            robot.jump();
            break;

        case KeyEvent.VK_CONTROL:
            if (robot.isDucked() == false && robot.isJumped() == false
                    && robot.isReadyToFire()) {
                robot.shoot();  
                robot.setReadyToFire(false);

            }
            break;

        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        switch (e.getKeyCode()) {
        case KeyEvent.VK_UP:
            break;

        case KeyEvent.VK_DOWN:
            currentSprite = anim.getImage();
            robot.setDucked(false);
            break;

        case KeyEvent.VK_LEFT:
            robot.stopLeft();
            break;

        case KeyEvent.VK_RIGHT:
            robot.stopRight();
            break;

        case KeyEvent.VK_SPACE:
            break;

        case KeyEvent.VK_CONTROL:
            robot.setReadyToFire(true);
            Sound.GUN.play();
            break;

        }

    }

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

    }


    public static Background getBg1() {
        return bg1;
    }

    public static Background getBg2() {
        return bg2;
    }

    public static Robot getRobot() {
        return robot;
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
        if (evt.getSource() == next)
            level ++;

        {


        }
        if (evt.getSource() == sOver)

            level = 1;      

        {

        }
    }


}

The error message that I was getting is:

Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
    at java.awt.Container.addImpl(Unknown Source)
    at java.awt.Container.add(Unknown Source)
    at androidGame.StartingClass.paint(StartingClass.java:372)
    at androidGame.StartingClass.update(StartingClass.java:305)
    at sun.awt.RepaintArea.updateComponent(Unknown Source)
    at sun.awt.RepaintArea.paint(Unknown Source)
    at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$300(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Answer:

this.add(sOver);
sOver = new Button("Start Over");

I guess the error is here. You gotta initialize sOver before adding it to the applet. So put it like this :

sOver = new Button("Start Over");
this.add(sOver);

Let's see whether it works or not.

Question:

I want to call another applet by clicking a button; the old applet will then be closed or reloaded to the new applet.

My Action Listener doesn't have anything yet.

public class ConImage extends JApplet implements ActionListener {
    Button btn;
    Applet second;

    public void init()
    {
        setSize(1600,900);
        setLayout(null);
        btn=new Button("Replace with other applet");

        add(btn);
        btn.addActionListener(this);
    }


    public void paint(Graphics g)
    {
        super.paint(g);

        btn.setLocation(100, 100);
        btn.setSize(100, 50);            
    }

    public void actionPerformed(ActionEvent e)
    {   second=null;
        second= getAppletContext().getApplet("SecondClass");
        if (second!=null)
        {
            if(e.getSource()==Time)
            {
                SecondClass ma= (SecondClass) second;

            }
        }
    }
}

Answer:

I'm pretty sure this isn't possible because of Java's security system. The best way to so it is to have a master class, which has an array of JApplet. On that master applet I would create a method that sets the visible applet from the array, calls init() and when a render is requested call paint() of that applet.

Like so:

public class MasterApplet extends JApplet {

private int index = 0;
private JApplet[] applets;

public void init(){
    JApplet appletA = new AppletA();
    JApplet appletB = new AppletB();
    applets = new JApplet[]{appletA, appletB};
    setViewing(index);
}

public void paint(Graphics g){
    applets[index].paint(g);
}

public void setViewing(int idex){
    index = idex;
    applets[idex].init();
    revalidate();
    repaint();
}

Pretty much if you want to change the applet add it to the array of applets, and then call setViewing() with the index of that applet.

Question:

I want to execute an animation in an applet every time I click a button. The first time I click the button everything works fine. But the second time, the speed of the animation increases. The third time the speed of the animation increases a little bit more, and the fourth, and the fifth,...

I donĀ“t know what is happening with the timer. How can i fix it?

In the applet I use this code:

JButton btnIniciar = new JButton("Iniciar");
    btnIniciar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {     
            Timer timer = new Timer(50, new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    //I have a list of packages to animate
                    for (Package p: listaPaquetes){
                        p.animate();
                        panel.repaint();
                    }                             
                }
            });

            timer.start();
        }

And this is the code of repaint in the panel:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);     
    //I use the same list of the applet   
    for (Package p: listaPaquetes){
        //Paint the package
        p.paintPackage(g);
    }

}

This is how it works, the animation sends packages from left to right


Answer:

When you press the button you are creating new javax.swing.Timer and invoking timer.start() which in this case is scheduled to run 50ms after the button press and repeat each 50ms.

When you press the button second time, you create and start another timer (a new one) which again works each 50ms with 50ms initial delay. You are now essentially doubling the number of repaint calls.

With third press you are tripling the number of repaint calls because you have 3 timers running.

If your button presses were timed properly it will look as if the speed has tripled (with 3 button presses).

If you do not want this behavior you can prevent the timer to run if it is already running like this:

private Timer timer = null;

// ...

JButton btnIniciar = new JButton("Iniciar");
btnIniciar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) { 
        // prevent the timer from running again if it is already running
        if ( timer != null && timer.isRunning() ) return;

        timer = new Timer(50, new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                //I have a list of packages to animate
                for (Package p: listaPaquetes){
                    p.animate();
                    panel.repaint();
                }                             
            }
        });

        timer.start();
    }

Please note that you need to make timer into an instance variable. Also you can replace the line:

if ( timer != null && timer.isRunning() ) return;

with

if ( timer != null ) return;

I simply wanted to show you that Timer has isRunning() method.

You can also stop the timer by invoking timer.stop() method.

Question:

I am trying to compile example 1-2 from the Java In A Nutshell Book that deals with Java 1.0. I get an error saying that choice cannot be converted to Button. Now, I don't know whether this is an issue of current Java not supporting the libraries that I am calling, or the something is off.

The applet is supposed to be a sort of drawing pad, and the error is at line 14 / clear_button = new Choice();

import java.applet.*;
import java.awt.*;

public class Scribble extends Applet {
    private int last_x = 0;
    private int last_y = 0;
    private Color current_color = Color.black;
    private Button clear_button;
    private Choice color_choices;

public void init(){
    this.setBackground(Color.white);

    clear_button = new Choice();
    clear_button.setForeground(Color.black);
    clear_button.setBackground(Color.lightGray);
    this.add(clear_button);

    color_choices = new Choice();
    color_choices.addItem("black");
    color_choices.addItem("red");
    color_choices.addItem("yellow");
    color_choices.addItem("green");
    color_choices.setForeground(Color.black);
    color_choices.setBackground(Color.lightGray);
    this.add(new Label("Color: "));
    this.add(color_choices);
}

public boolean mouseDown(Event e, int x, int y){
    last_x = x; last_y = y;
    return true;
}

public boolean mouseDrag(Event e, int x, int y){
    Graphics g = this.setGraphics();
    g.setColor(current_color);
    g.drawline(last_x, last_y, x, y);
    last_x = x;
    last_y = y;
    return true;
}

public boolean action(Event event, Object arg) {
    if (event.target == clear_button) {
        Graphics g = this.getGraphics();
        Rectangle r = this.bounds();
        g.setColor(this.getBackground());
        g.fillRect(r.x, r.y, r.width, r.height);
        return true;
    }

    else if (event.target == color.choices) {
        if (arg.equals("black")) current_color = color.black;
        else if (arg.equals("red")) current_color = color.red;
        else if (arg.equals("yellow")) current_color = color.yellow;
        else if (arg.equals("green")) current_color = color.green;
        return true;
    }

    else return super.action(event, arg);

 }
}

Answer:

This is because Choice does not extend from Button. The type is incompatible.

https://docs.oracle.com/javase/7/docs/api/java/awt/Choice.html

In order to fix this you need to change the type of clear_button to Choice like this:

private Choice clear_button;

I just checked the old java 1.0.2 documentation and there Choice is also not extending from Button:

http://web.mit.edu/java_v1.0.2/www/javadoc/java.awt.Choice.html#top

Based on your comment this.setGraphics() does not exist neither in Java 1.0.2 neither in modern Java.

Judging from your code you should replace it with this.getGraphics().

Another way to obtain a handler to Graphics would be to override the:

public void paint(Graphics g)

You can override this method in your class.

Question:

I would like to send with a click of the button an applet any parameters to the browser. (Html). I know there are some methods button object but do not know which to use. How can I do this? ps .: I'm using jnlp protocol.

Something like:

 key_button = new Button("Click"); 
 key_button.setBounds(150,50,100,20); 
 add(key_button);

I have an applet code The following code:

package applet;

import java.awt.*; 
import java.applet.*; 
import java.awt.event.*;
import java.io.File;
 import java.net.URL;
import java.util.ArrayList; 
//import java.io.BufferedWriter; 
//import java.io.FileWriter; 

public class UserInput extends Applet implements ActionListener{ 


  TextField key_text1;
  static TextField key_text2;
  TextField key_output; 
  Label key_label1,key_label2,key_label3; 
  Button key_button;

  public void init(){ 
      setLayout(null);

    // Add different components to the layout. 


    key_label1 = new Label("Enterpassword1: "); 
    key_label1.setBounds(20,20,100,20);
    add(key_label1); 

    key_text1 = new TextField(5);
    key_text1.setBounds(150,20,100,20); 
    add(key_text1);       


    key_button = new Button("Click"); 
    key_button.setBounds(150,50,100,20); 


     /*******************Here I need to create a method that clicking key_button sends the data entered in the TextField field to the website (html) and html would appear the argument entered the applet TextFiel.**************************/


  // key_button.event();

    add(key_button);

    } 

Answer:

..send with a click of the button an applet any parameters to the browser.

String value = textField.getText();
String path = "the.html";
URL url = new URL(getDocumentBase(), path + "?param=" + value);
getAppletContext().showDocument(url);

Question:

What I am trying to do is an Appled which throws 2 threads, each running a counter which increases itself via an infinite loop I then use a while(true) in the Applet's paint() method, which continuously paints the counters, the problem is that I have also 2 buttons, each intended to stop each thread, but the infinite loop in the paint() method doesn't let me neither click none of them nor close the Applet's window nor anything

Here a screenshot followed by the code

btw I'm certain the problem is the paint() loop as if I disable the loop I can interact with the buttons, but the counters are obviously not updated, and weird thing is that I put the mouse cursor over the buttons to show it took the form like when you want to resize a windows but the imprpant didn't capture it :/

http://i.imgur.com/PJnDI4u.png

public class MainApplet extends Applet implements ActionListener {

private static final long serialVersionUID = -2500043816999861110L;
private Font fuente;
private Button bUno, bDos;
private HiloContador hUno, hDos;

public void init() {
    setBackground(Color.LIGHT_GRAY);
    fuente = new Font("Verdana",Font.BOLD,26);
    bUno = new Button("Parar");
    bUno.addActionListener(this);
    bDos = new Button("Parar");
    bDos.addActionListener(this);   
    bUno.setSize(40,20);
    add(bUno);
    bDos.setSize(40,20);
    add(bDos);
    hUno = new HiloContador(20);
    hUno.start();
    hDos = new HiloContador(40);    
    hDos.start();

}

@SuppressWarnings({ "deprecation", "static-access" })
public void actionPerformed(ActionEvent e) {
    if(e.getSource().equals(bUno)){
        hUno.parar();
        bUno.setLabel("1 parado");
    }else if (e.getSource().equals(bDos)){
        hDos.parar();
        bDos.setLabel("2 parado");
    }               
}

public void paint(Graphics g) {
    while (true){
        g.clearRect(1,1,getSize().width,getSize().height); //dibuja la ventana
        g.setFont(fuente);
        g.drawString(hUno.getContador()+"",40,60); 
        g.drawString(hDos.getContador()+"",100,60); 
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

}


Answer:

in case it helps anyone, solved deleting the infinite loop and adding this method

Timer timer = new Timer();
timer.schedule( new TimerTask() {
public void run() {
repaint();}
}, 0, 1000);

Question:

I am very new to Java and programming in general, so I tried to write a simple program whose only job is to make a ball moving around with the arrow keys and jumping with the space button. The program compiles but the ball doesn't move.

I probably didn't fully understood the Applet principles, could you explain to me the mistake I made?

Applet:

package test_game;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Starting_Point extends Applet implements Runnable, KeyListener {

    private static final long serialVersionUID = 1L;
    private static final int WIDTH = 700;
    private static final int HEIGHT = 300;
    Character Phil;
    Thread thread;

    @Override
    public void init() {
        setSize(WIDTH,HEIGHT);
        Phil = new Character(50, 200);
    }

    @Override
    public void start() {
        thread = new Thread(this);
        thread.start();
    }

    public void run() {
        while (true) {
            repaint();  
        }
    }

    @Override
    public void paint(Graphics arg0) {
        Phil.paint(arg0);
    }

    @Override
    public void keyPressed(KeyEvent arg0) {
        switch (arg0.getKeyCode()) {
            case (KeyEvent.VK_LEFT): Phil.setX(Phil.getX() - Phil.getDx());
                break;
            case (KeyEvent.VK_RIGHT): Phil.setX(Phil.getX() + Phil.getDx());
                break;
            case (KeyEvent.VK_SPACE): Phil.setDy(Character.gravity * Character.dt);
                Phil.setY(Phil.getY() + .5*Character.gravity*Character.dt*Character.dt + Phil.getDy()*Character.dt + Character.jump);
                break;
        }
    }

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

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

Character class:

package test_game;

import java.awt.Color;
import java.awt.Graphics;

public class Character {

    private int x;
    private int y;
    private int radius = 10;
    Graphics g;
    public static final int gravity = 15;
    private static final double dx = 4;
    public double dy;
    public static final double dt = .2;
    public static final int jump = 30;

    public Character(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void setX(double d) {
        this.x = (int) d;
    }

    public void setY(double d) {
        this.y = (int) d;
    }

    public double getDx() {
        return dx;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void setDy(double dy) {
        this.dy = dy;
    }

    public double getDy() {
        return dy;
    }

    public void paint(Graphics g) {
        g.setColor(Color.black);
        g.fillOval(x, y, radius, radius);   
    }
}

Answer:

You have defined a KeyListener inside you code. However, you forgot to register this event listener to a component, so its never called.

How to register your KeyListener:

Place the following code inside your start():

this.addKeyListener(this);

This fixes the problem with the character from moving to the left or right, however the jumping isn't fixed, fixing the jumping requires more code that calculates the correct y+ that you require, the current code always add 0 (rounded to 0 using the (int) you use) to the y coordinate when you press space.

Question:

I am completing a past paper exam question and it asks to create an applet that displays a green square in the center, with three buttons + , - and reset, however, I am trying to make it that when any button is clicked the program should essentially figure out which button was pressed. I know you would use e.getSource() but I am not sure how to go about this.

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

public class Square extends JApplet {

int size = 100;

public void init() {
    JButton increase = new JButton("+");
    JButton reduce = new JButton("-");
    JButton reset = new JButton("reset");

    SquarePanel panel = new SquarePanel(this);
    JPanel butPanel = new JPanel();

    butPanel.add(increase);
    butPanel.add(reduce);
    butPanel.add(reset);

    add(butPanel, BorderLayout.NORTH);
    add(panel, BorderLayout.CENTER);

    ButtonHandler bh1 = new ButtonHandler(this, 0);
    ButtonHandler bh2 = new ButtonHandler(this, 1);
    ButtonHandler bh3 = new ButtonHandler(this, 2);

    increase.addActionListener(bh1);
    reduce.addActionListener(bh2);
    reset.addActionListener(bh3);
}
}

class SquarePanel extends JPanel {
Square theApplet;

SquarePanel(Square app) {
    theApplet = app;
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.green);
    g.fillRect(10, 10, theApplet.size, theApplet.size);
}
}

class ButtonHandler implements ActionListener {
Square theApplet;
int number;

ButtonHandler(Square app, int num) {
    theApplet = app;
    number = num;
}

public void actionPerformed(ActionEvent e) {
    switch (number) {
        case 0:
            theApplet.size = theApplet.size + 10;
            theApplet.repaint();
            break;
        case 1:
            if (theApplet.size > 10) {
                theApplet.size = theApplet.size - 10;
                theApplet.repaint();
            }
            break;
        case 2:
            theApplet.size = 100;
            theApplet.repaint();
            break;
    }
}

Answer:

Not the best way to do it, but based on your current code, you could simply compare the object references. You'd need to pass in references to the buttons or access them some other way. e.g.

if(e.getSource() == increase) { \\do something on increase}

Another alternative would be to check the string of the button, e.g.

if(((JButton)e.getSource()).getText().equals("+")){ \\do something on increase}

You can use strings in a switch statement in Java 8, but if you're using Java 7 or lower, it has to be an if statement.

Question:

I am attempting to make a menu, which has 3 options. I want to make each of these options a class. And call that class on a button click. I am having a hard time figuring out how to call inner classes. Could you please help me out?

public class menu extends Applet
    {

        public void init(){

        Button playButton = new Button ("Play");
        Button howButton = new Button ("Instructions");
        Button quitButton = new Button ("Quit :(");
        this.add(playButton);
        this.add(howButton);
        this.add(quitButton);

        game gameObject = new game();



        }

        class game extends Applet { 
            //code for this would go here...
        }//game

        }//menu

Answer:

You would instantiate your inner game class from within the menu class like so:

menu.game gameObject = this.new game();

For a more elaborate explanation see here.

And in addition to the comments above: I would advise you add a proper constructor to the menu class and have that call init() (which could then become private). After all you want to do OOP, right?

Question:

i think this is wrong. i want my code to add actionlistener as soon as button is created.Is there a way to do that dynamically. look at the inner for loop i have a problem adding there

import java.awt.*;
import java.applet.*;
import java.util.*;
import java.awt.event.*;

/* <applet code = "Gridl.java" width=300 height=200>
   </applet> */

public class Gridl extends Applet 
{
     TextField t1=new TextField("    ");

     public void init()
     {
         int n = 1;
         setLayout(new GridLayout(4,4));
         add(t1);
         setFont(new Font("Tahoma",Font.BOLD,24));

         for(int i=0;i<4;i++)
         {
             for(int j=0;j<4;j++)
             {
                 add(new Button(""+n));        
                 this.addActionListener(this);       // this didnt work :(
                 n++;
             }
         }  
    }

    public void actionPerformed(ActionEvent ae)
    {
        String str = ae.getActionCommand();
        t1.setText(str);
    }

}

Answer:

I think you have some conceptual misunderstandings reflected in your code here. It's important to consider which component you are adding the ActionListener onto. At the moment, your code adds the ActionListener to the Gridl object extending Applet, rather than the button itself. It won't throw an exception, because that's valid, but it won't give you the behaviour you want

To get you working, I suggest you replace

add(new Button(""+n));

with

Button b = new Button(""+n);
b.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e)
    {
        System.out.println("You clicked button "+e.getSource().toString());
    }
});

this.add(b);

Note that this sets up a new ActionListener for every Button object, with its behaviour determined by what you put in the actionPerformed() method. You can have the same behaviour for all buttons, or different for each.

I would suggest that you might want to read the oracle Java Swing GUI tutorials, in particular the one on actions. There are code samples there too.

EDIT:

I have realised you might want to have your Gridl be the listener for all buttons. In which case - you can achieve this by:

public class Gridl extends Applet implements ActionListener
{
     TextField t1=new TextField("    ");

     public void init()
     {
         int n = 1;
         setLayout(new GridLayout(4,4));
         add(t1);
         setFont(new Font("Tahoma",Font.BOLD,24));

         for(int i=0;i<4;i++)
         {
             for(int j=0;j<4;j++)
             {
                 Button b = new Button(""+n));        
                 b.addActionListener(this);
                 this.add(b);
                 n++;
             }
         }  
    }

    public void actionPerformed(ActionEvent ae)
    {
        String str = ae.getActionCommand();
        t1.setText(str);
    }

}

Question:

I have an applet that draws a grid using drawLine() and then allows user to place and remove .png images by clicking on the grid. Now I want to add some interface buttons to the right of the drawing space, how can I do that? Currently a button refuses to move to the coordinates I want, and surely there is a proper way to do it?

package test2;

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;

public class MainClass extends Applet implements MouseListener{

    final int columnNumber = 10; //Number of columns
    final int rowNumber = 8; //Number of rows

    final int gridSize = 51;

    private URL base;

    //element images
    private Image whiteSquare, resistanceHor, resistanceVer;

    //creating a GridElement array
    GridElement[][] gridElement = new GridElement[columnNumber][rowNumber];

    public void init()  {

        setSize(columnNumber*gridSize + 100, rowNumber*gridSize);
        //Here I try to add a button
        Button resistanceButton = new Button("Button1");
        resistanceButton.setLocation(columnNumber*gridSize, 20);
        this.add(resistanceButton);

        try {
            base = getDocumentBase();
        } catch (Exception e) {
            // TODO: handle exception
        }

        resistanceHor = getImage(base, "data/resistance_hor.png");
        resistanceVer = getImage(base, "data/resistance_ver.png");
        whiteSquare = getImage(base, "data/white_square.png");

        // Add the MouseListener to applet
        addMouseListener(this);

        for(int xcount=0; xcount<columnNumber;xcount++){

            for(int ycount=0; ycount<rowNumber;ycount++){
                //set top left corner  coordinates for all grid elements and declare them empty and non-vertical
                gridElement[xcount][ycount] = new GridElement(gridSize*xcount, gridSize*ycount,true,false);

            }
        }
    }

    public void update(Graphics g) {
        paint(g);
    }

    public void paint(Graphics g){

        //set grid color
        Color gridGrey = new Color(208,195,195);        
        g.setColor(gridGrey); 

        //draw grid
        for(int xcount=0; xcount<columnNumber;xcount++){

            g.drawLine(xcount*gridSize, 0, xcount*gridSize, rowNumber*gridSize);
        }

        for(int ycount=0; ycount<rowNumber;ycount++){

            g.drawLine(0, ycount*gridSize, columnNumber*gridSize, ycount*gridSize);
        }

        //draw png images in non-empty squares
        for(int xcount=0; xcount<columnNumber;xcount++){

            for(int ycount=0; ycount<rowNumber;ycount++){

                if(gridElement[xcount][ycount].isEmpty() == false){
                    g.drawImage(resistanceHor, gridElement[xcount][ycount].getxTopLeftCorner(), gridElement[xcount][ycount].getyTopLeftCorner(), this);
                }
                else{
                    g.setColor( getBackground() );
                    g.fillRect(gridElement[xcount][ycount].getxTopLeftCorner()+1, gridElement[xcount][ycount].getyTopLeftCorner()+1, gridSize-1, gridSize-1);
                }
            }
        }
    }

    public void mouseClicked (MouseEvent me) {

        int col = me.getX() / gridSize;   // Column where user clicked.
        int row = me.getY() / gridSize;   // Row where user clicked.

        //if a square is empty, make it not empty, if it is not empty, make it empty
        if(gridElement[col][row].isEmpty() == true){
            gridElement[col][row].setEmpty(false);
        }
        else{
            gridElement[col][row].setEmpty(true);
        }

        repaint();
    }   
    public void mousePressed (MouseEvent me) {}
    public void mouseReleased (MouseEvent me) {} 
    public void mouseEntered (MouseEvent me) {}
    public void mouseExited (MouseEvent me) {} 
}

package test2;

public class GridElement {

private int xTopLeftCorner;
private int yTopLeftCorner;

private boolean vertical;
private boolean empty;

private boolean isResistor;

GridElement(int xTopLeftCorner, int yTopLeftCorner,  boolean empty, boolean vertical){
    this.xTopLeftCorner = xTopLeftCorner;
    this.yTopLeftCorner = yTopLeftCorner;
    this.empty = empty;
    this.vertical = vertical;

}

public boolean isResistor() {
    return isResistor;
}

public void setResistor(boolean isResistor) {
    this.isResistor = isResistor;
}

public boolean isVertical() {
    return vertical;
}
public boolean isEmpty() {
    return empty;
}
public void setVertical(boolean vertical) {
    this.vertical = vertical;
}
public void setEmpty(boolean empty) {
    this.empty = empty;
}

public int getxTopLeftCorner() {
    return xTopLeftCorner;
}

public int getyTopLeftCorner() {
    return yTopLeftCorner;
}

public void setxTopLeftCorner(int xTopLeftCorner) {
    this.xTopLeftCorner = xTopLeftCorner;
}

public void setyTopLeftCorner(int yTopLeftCorner) {
    this.yTopLeftCorner = yTopLeftCorner;
}

}


Answer:

You need to learn about layout managers.

Basically top-level containers like Applet,JApplet,Frame,JFrame,Dialog,JDialog,etc. have a default layout manager of BorderLayout. When you add(component) to a container with a BorderLayout, the component gets added to the BorderLayout.CENTER position. Not only that, but BorderLayout doesn't respect the preferred sizes of components, meaning that the component will stretch to fit the container. In your case, it will take up entire frame.

Solution.

  • Don't paint on the applet component itself. Paint in a Panel instead. Add the panel to the applet container. (CENTER is ok)

  • Create another Panel and add the button to that panel, then add the panel to BorderLayout.LINE_END, like add(buttonPanel, BorderLayout.LINE_END);


Other important notes:

  • Unless this is a class assignment and the professor explicitly said to use AWT component.. Don't. Use Swing component instead. Swing component are very similar to AWT component. They generally prefix the AWT components with a J, for instance JPanel. See more about Swing

  • Don't explicitly call paint() as you do in your update() method. Instead call repaint()

  • You should call super.paint(g) in the paint method, if you are not going to paint the background yourself. You will see the leftover paint artifacts if you dont.

Question:

This is code I wrote for an applet using swing. The program lets the user enter any extra items (peripherals), which shipping method they want to use, and then allows them to push buttons that calculate their total costs either with or without shipping depending on the button they push. The problem is, when I run it, it freezes and doesn't do anything after I click either of the calculate buttons. Does anyone see anything wrong with my code that could be causing this? Thank you.

 package selling;


public class midtermComputers extends javax.swing.JApplet {
public double calculateCost(int quantity){

     double discountedPrice=getDiscountPercentage(quantity);
       double finalCost=0;
     if (isShipping()&(groundRadioButton.isSelected())&quantity<100){
     finalCost= ((discountedPrice*.05)+discountedPrice)*quantity;
     }
        if (isShipping()&(groundRadioButton.isSelected())&quantity>100){
     finalCost=discountedPrice*quantity;
     }     
         if (isShipping()&(airRadioButton.isSelected())){
     finalCost= discountedPrice*.1*quantity;
     }
         if (isShipping()&(fedExRadioButton.isSelected())){
     finalCost= discountedPrice*.2*quantity;
}
         if (!isShipping()){
     finalCost= discountedPrice*quantity;
 }
         return finalCost;
 }

private void calcWithShippingButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       
    int quantity=1;
    double finalCost=calculateCost(quantity);
outputTextPane.setText(outputTextPane.getText() + quantity + "\t" + finalCost  + "\n" );
     quantity=100;
 while(quantity<=1000){
outputTextPane.setText(outputTextPane.getText() + quantity + "\t" + finalCost  + "\n" );
quantity=quantity+100;
    }

    }                                                      

private void calcWithoutShippingButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                          
   int quantity=1;
    double finalCost=calculateCost(quantity);
outputTextPane.setText(outputTextPane.getText() + quantity + "\t" + finalCost  + "\n" );
 quantity=100;
 while(quantity<=1000){
outputTextPane.setText(outputTextPane.getText() + quantity + "\t" + finalCost  + "\n" );
quantity=quantity+100;
}
}                                                         

public double calculateCost(){
double base=399.00;
double costOneUnit=0.0;
          double speakerPeripheral=0.0;
          double printerPeripheral=0.0;
          double scannerPeripheral=0.0;
          double microphonePeripheral=0.0;
          double projectorPeripheral=0.0;
          double plotterPeripheral=0.0;

while(speakerCheckBox.isSelected()){
   speakerPeripheral=89.00;
}

while(printerCheckBox.isSelected()){
  printerPeripheral=59.00;
}
 while(scannerCheckBox.isSelected()){
  scannerPeripheral=415.00;
 }
 while(microphoneCheckBox.isSelected()){
  microphonePeripheral=39.00;
 }
 while(projectorCheckBox.isSelected()){
  projectorPeripheral=549.00;
 }
 while(plotterCheckBox.isSelected()){
  plotterPeripheral=4883.00;
 }
 return costOneUnit=base+speakerPeripheral+printerPeripheral+scannerPeripheral+microphonePeripheral+projectorPeripheral+plotterPeripheral;

}


public boolean isShipping(){
if(calcWithShippingButton.isSelected()){
    return true;
} else{
    return false;
}
}

public double getDiscountPercentage(int quantity){
    double costOneUnit=calculateCost();
    double discountedPrice=0;

    while (quantity<100){
discountedPrice=costOneUnit;
}
    while (quantity>100&quantity<=199){
     discountedPrice=(costOneUnit-(costOneUnit*.01))*quantity;

}
    while (quantity>200&quantity<=299){
     discountedPrice=(costOneUnit-(costOneUnit*.02))*quantity;
}
    while (quantity>300&quantity<=399){
     discountedPrice=(costOneUnit-(costOneUnit*.03))*quantity;
}
    while (quantity>400&quantity<=499){
     discountedPrice=(costOneUnit-(costOneUnit*.04))*quantity;
}
    while (quantity>500&quantity<=599){
     discountedPrice=(costOneUnit-(costOneUnit*.05))*quantity;
}
    while (quantity>600&quantity<=699){
     discountedPrice=(costOneUnit-(costOneUnit*.06))*quantity;
}
    while (quantity>700&quantity<=799){
     discountedPrice=(costOneUnit-(costOneUnit*.07))*quantity;
}
    while (quantity>800&quantity<=899){
     discountedPrice=(costOneUnit-(costOneUnit*.08))*quantity;
}
    while (quantity>900&quantity<=999){
     discountedPrice=(costOneUnit-(costOneUnit*.09))*quantity;
}
    while(quantity<=1000&quantity>999){
      discountedPrice=(costOneUnit-(costOneUnit*.1))*quantity;  
    }
   return discountedPrice;
}  

Answer:

the "while" in calculateCost() should be "if "

public double calculateCost(){
       ...
       while(speakerCheckBox.isSelected()){
              speakerPeripheral=89.00;
       }

       while(printerCheckBox.isSelected()){
             printerPeripheral=59.00;
       }
       while(scannerCheckBox.isSelected()){
             scannerPeripheral=415.00;
       }
       ....

Like

if(speakerCheckBox.isSelected()){
      speakerPeripheral=89.00;
}