Hot questions for Using Applets in actionlistener

Top Java Programmings / Applets / actionlistener

Question:

Is there a way to make all of these actionlisteners into one statement?

    jbtn0.addActionListener(this);
    jbtn1.addActionListener(this);
    jbtn2.addActionListener(this);
    jbtn3.addActionListener(this);
    jbtn4.addActionListener(this);
    jbtn5.addActionListener(this);
    jbtn6.addActionListener(this);
    jbtn7.addActionListener(this);
    jbtn8.addActionListener(this);
    jbtn9.addActionListener(this);
    jbtnAdd.addActionListener(this);


    jfrm.add(jbtn0);
    jfrm.add(jbtn1);
    jfrm.add(jbtn2);
    jfrm.add(jbtn3);
    jfrm.add(jbtn4);
    jfrm.add(jbtn5);
    jfrm.add(jbtn6);
    jfrm.add(jbtn7);
    jfrm.add(jbtn8);
    jfrm.add(jbtn9);

I am rather new to java, and I am using eclipse.


Answer:

Yes, in a way. I do this sometimes:

for(JButton btn : new JButton[] {
    jbtn0, jbtn1, jbtn2, ... , jbtn9
}) {
    jbtn.addActionListener(this);
    jfrm.add(jbtn);
}

I do that even when my components do not start out in an array, for example if I am filling a JToolBar and need to refer to the components by name somewhere else.

Judging by your naming scheme, it may also be advantageous for you to use an array from the beginning.

Question:

This is my code for a game im making. At the moment im not worried about how the game functions I've been more so worried about the fact that each time I hit the UP button the panels disappear and sometimes when i hit the LEFT button as well. Is there an explanation to this can anyone help me understand why this happens?? I have a feeling it has something to do with my if statements but im not really sure. also, im messing around with the key listener and if you could give me some advice on key listeners like some dos and donts I really appreciate the help!!

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


  public class Game extends Applet implements ActionListener,KeyListener {
     Image image;
     MediaTracker tr;
     JLabel label,computerLabel;
     JPanel panel,computerPanel;
     Button start,up,down;
     Label result;
     Dimension SIZE = new Dimension(50,50);

     int x = 0;
     int y = 0;
     int w = 100;
     int q = 100;
     int WIDTH = 50;
     int HEIGHT = 50;
     //Player Integers
     int zeroPosX,zeroPosY,xLeft,xUp;
     //Computer integers
     int compZeroPosX,compZeroPosY,compXLeft,compXUp;

     //--------------------------------------
     public void init()   {
        setLayout(new FlowLayout());

        start = new Button("Start");
        up = new Button("UP");
        down = new Button("LEFT");
     //PlayerPiece stuff    
        ImageIcon icon = new ImageIcon("playerpiece.png");      
        label = new JLabel(icon);
        panel = new JPanel();

        label.setVisible(true);
        panel.add(label);
        panel.setPreferredSize(SIZE);
     //ComputerPiece Stuff
        ImageIcon computerIcon = new ImageIcon("computerPiece.png");
        computerPanel = new JPanel();
        computerLabel = new JLabel(computerIcon);

        computerLabel.setVisible(true);
        computerPanel.add(computerLabel);
        computerPanel.setPreferredSize(SIZE);

     //===============================================     

        result = new Label("=========");
        addKeyListener(this);

        setSize(650,650);

        up.addActionListener(this);
        down.addActionListener(this);
        start.addActionListener(this);

        label.setSize(WIDTH,HEIGHT);
        label.setLocation(0,0);

        add(computerPanel);
        add(panel);
        add(start);
        add(up);
        add(down);
        add(result);


        }

     //--------------------------------------  
        public void paint(Graphics g)  {


           Graphics2D firstLayer = (Graphics2D)g;
           Graphics2D secondLayer = (Graphics2D)g;
           Graphics2D thirdLayer = (Graphics2D)g;


        secondLayer.setColor(Color.BLACK);


           for(x=100; x<=500; x+=100) 
               for(y=100; y <=500; y+=100)
               {

               firstLayer.fillRect(x,y,WIDTH,HEIGHT);


               }
           for(w=150; w<=500; w+=100) 
               for(q=150; q <=500; q+=100)
                  {

               secondLayer.fillRect(w,q,WIDTH,HEIGHT);


               }





           }
        //--------------------------------------
           public void actionPerformed(ActionEvent ae)   {

           int [] range = {50,0,0,0,0};
           int selection = (int)Math.random()*5 ;


        //~~~~~~~~~~~~~~~~~~~~~~~~~

        //PlayerPositioning
            zeroPosX = panel.getX();
            zeroPosY = panel.getY();
            xLeft = zeroPosX - 50;
            xUp = zeroPosY - 50;  
        //ComputerPositioning
            compZeroPosX = computerPanel.getX();
            compZeroPosY = computerPanel.getY();
            compXLeft = compZeroPosX - range[selection];
            compXUp = compZeroPosY - range[selection];
        //~~~~~~~~~~~~~~~~~~~~~~~~~~    


            Button user = (Button)ae.getSource();




        //Starting the game
        if(user.getLabel() == "Start")   {
            result.setText("=========");
        //playersetup
            label.setLocation(0,0);
            panel.setLocation(300,500);
        //============================
        //npc setup
            computerLabel.setLocation(0,0);
            computerPanel.setLocation(500,300);


         }



           if(compZeroPosX >= 150)    {
              if(compZeroPosY >= 150)    {
                 if(zeroPosX >= 150)       {
                   if(zeroPosY >=150)         {  


                      if(user.getLabel() == "UP")   {
                        panel.setLocation(zeroPosX,xUp);

                        }
                        else     
                          computerPanel.setLocation(compZeroPosX,compXUp);




                      if(user.getLabel() == "LEFT") {
                         panel.setLocation(xLeft,zeroPosY);

                      }

                      else      
                         computerPanel.setLocation(compXLeft,compZeroPosY);

                       if(panel.getX() < 150) 
                          result.setText("GAME-OVER");


                       if(panel.getY() < 150)
                          result.setText("GAME-OVER");

                       }
                 }      
                 }
              }  
           }
        @Override
        public void keyPressed(KeyEvent kp) {
           int keycode = kp.getKeyCode();

              switch (keycode)  {
                 case KeyEvent.VK_W:
                 panel.setLocation(xLeft,zeroPosY);
                 break;
                 }





        }
        @Override
        public void keyReleased(KeyEvent kr)   {

        }
        @Override
        public void keyTyped(KeyEvent kt)   {

        }

       }

Answer:

Issues and suggestions:

  1. You're mixing AWT (e.g., Applet, Button, Label) with Swing (e.g., JPanel, JLabel) dangerously and without need. Stick with Swing and get rid of all vestiges of AWT.
  2. You're painting directly in a top-level window, here the Applet, a dangerous thing to do. Don't. Follow the Swing graphics tutorials and do your drawing in a JPanel's paintComponent method.
  3. You're not calling the super method within your painting method override, another dangerous thing to do, and another indication that you're trying to do this without reading the important relevant tutorials.
  4. Don't compare Strings using == or !=. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two object references are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here.
  5. You're trying to directly set the location of a component such as a JPanel without regard for the layout managers. Don't do this. Instead move logical (non-component) entities and display the movement in your graphics.

You can find links to the Swing tutorials and to other Swing resources here: Swing Info

Later we can talk why you should avoid applets of all flavors...

Myself, I'd move ImageIcons around a grid of JLabels and not directly use a painting method at all. For example,

To see, run the following code:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class Game2 extends JPanel {
    private static final String CPU_PATH = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/"
            + "Gorilla-thinclient.svg/50px-Gorilla-thinclient.svg.png";
    private static final String PERSON_PATH = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d8/"
            + "Emblem-person-blue.svg/50px-Emblem-person-blue.svg.png";
    private static final int SQR_WIDTH = 50;
    private static final int SIDES = 10;
    private static final Dimension SQR_SIZE = new Dimension(SQR_WIDTH, SQR_WIDTH);
    private static final Color DARK = new Color(149, 69, 53);
    private static final Color LIGHT = new Color(240, 220, 130);
    private JLabel[][] labelGrid = new JLabel[SIDES][SIDES];
    private Icon playerIcon;
    private Icon computerIcon;

    public Game2() throws IOException {
        // would use images instead
        playerIcon = createIcon(PERSON_PATH);
        computerIcon = createIcon(CPU_PATH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(new JButton(new StartAction("Start", KeyEvent.VK_S)));
        buttonPanel.add(new JButton(new UpAction("Up", KeyEvent.VK_U)));
        buttonPanel.add(new JButton(new LeftAction("Left", KeyEvent.VK_L)));

        JPanel gameBrd = new JPanel(new GridLayout(SIDES, SIDES));
        gameBrd.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        for (int i = 0; i < labelGrid.length; i++) {
            for (int j = 0; j < labelGrid[i].length; j++) {
                JLabel label = new JLabel();
                label.setPreferredSize(SQR_SIZE);
                label.setOpaque(true);
                Color c = i % 2 == j % 2 ? DARK : LIGHT;
                label.setBackground(c);
                gameBrd.add(label);
                labelGrid[i][j] = label;
            }
        }

        setLayout(new BorderLayout());
        add(buttonPanel, BorderLayout.PAGE_START);
        add(gameBrd);

        // random placement, just for example
        labelGrid[4][4].setIcon(computerIcon);
        labelGrid[5][5].setIcon(playerIcon);
    }

    private Icon createIcon(String path) throws IOException {
        URL url = new URL(path);
        BufferedImage img = ImageIO.read(url);
        return new ImageIcon(img);        
    }

    private abstract class MyAction extends AbstractAction {
        public MyAction(String name, int mnemonic) {
            super(name);
            putValue(MNEMONIC_KEY, mnemonic);
        }
    }

    private class StartAction extends MyAction {
        public StartAction(String name, int mnemonic) {
            super(name, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO start game code

        }
    }

    // move all icons up
    private class UpAction extends MyAction {
        public UpAction(String name, int mnemonic) {
            super(name, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // collection to hold label that needs to be moved
            Map<JLabel, Icon> labelMap = new HashMap<>();
            for (int i = 0; i < labelGrid.length; i++) {
                for (int j = 0; j < labelGrid[i].length; j++) {
                    Icon icon = labelGrid[i][j].getIcon();
                    if (icon != null) {
                        int newI = i == 0 ? labelGrid.length - 1 : i - 1;
                        labelGrid[i][j].setIcon(null);
                        labelMap.put(labelGrid[newI][j], icon);
                    }
                }
            }

            // move the icon after the iteration complete so as not to move it twice
            for (JLabel label : labelMap.keySet()) {
                label.setIcon(labelMap.get(label));
            }
        }
    }

    // move all icons left
    private class LeftAction extends MyAction {
        public LeftAction(String name, int mnemonic) {
            super(name, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Map<JLabel, Icon> labelMap = new HashMap<>();
            for (int i = 0; i < labelGrid.length; i++) {
                for (int j = 0; j < labelGrid[i].length; j++) {
                    Icon icon = labelGrid[i][j].getIcon();
                    if (icon != null) {
                        int newJ = j == 0 ? labelGrid[i].length - 1 : j - 1;
                        labelGrid[i][j].setIcon(null);
                        labelMap.put(labelGrid[i][newJ], icon);
                    }
                }
            }
            for (JLabel label : labelMap.keySet()) {
                label.setIcon(labelMap.get(label));
            }
        }

    }

    private static void createAndShowGui() {
        Game2 mainPanel = null;
        try {
            mainPanel = new Game2();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        JFrame frame = new JFrame("Game2");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }
}

Question:

I'm trying to make an applet that will count how many times you have clicked a button, but it seems ActionListener isn't working properly. This code looks like it would work, but for some reason when I click the button in the applet, nothing is printed in the console or updated on the interface as it should.

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

public class Test extends Applet implements ActionListener
{
    Button Clicker;
    Button Upgrade;
    int currentClicks = 0;

    public void init()
    {
        this.setSize(600,400);

        Button Clicker = new Button("Click");
        add(Clicker);
        Clicker.addActionListener(this);

        Button Upgrade = new Button("Autoclick Upgrade");
        add(Upgrade);
        Upgrade.addActionListener(this);
    }
    public void paint (Graphics g)
    {
        g.drawString("Test",300,50);
        g.drawString(String.valueOf(currentClicks), 300, 100);
    }
    public void actionPerformed(ActionEvent ae) 
    {
        String sString = ae.getActionCommand();
        if (sString.equals(Clicker))
        {
            System.out.println("Clicker was pressed");
            currentClicks++;
            System.out.println("Total Clicks: "+currentClicks);
            repaint();
        }
        else if (sString.equals(Upgrade))
        {
            System.out.println("Upgrade was pressed");
            if (currentClicks >= 25)
            {
                System.out.println("Upgrade was successfully purchased!");
                currentClicks = currentClicks - 25;
                repaint();
            }
            else
            {
                System.out.println("Upgrade was not successfully purchased!");
                repaint();
            }
        }
    }
}

Answer:

Set an action command to the Button :

Button Clicker = new Button("Click");
Clicker.setActionCommand("Click");

Then use that to determine what was clicked :

if (sString.equals("Click"))

OR

Compare the source button :

if(ae.getSource() == Clicker)

Question:

Hello everyone I am trying to make a game where the user plays as some kind of character, and trys to collect coins while avoiding monsters that spawn. My program compiles with no error, but nothing is showing up when I run the applet. This could be because of the order of extension I have everything in but I am not sure. Any help would be greatly appreciated (this is for a final school project for my intro to Java class). Here is the code, I know it is long but it all pertains to the question at hand:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Sprite extends JApplet
{
   Image image;
   int x, y;
   boolean isVisible;
   public Sprite()
   {
       isVisible = false;
       image = null;
   }
   public Sprite(Image i)
   {
       isVisible = true;
       image = i;
       x = 10;
       y = 10;
   }
   public void setImage(Image img)
   {
       image = img;
       isVisible = true;
   }
   public void setLocation(int _x, int _y)
   {
       x = _x;
       y = _y;
   }
   public Rectangle getDimensions()
   {
       return new Rectangle(x, y, image.getWidth(null), image.getHeight(null));
   }
public boolean intersects(Sprite s)
{
    return getDimensions().intersects(s.getDimensions());
}
public void setVisible(boolean vis)
{
    isVisible = vis;
}
public void paintComponent(Graphics g)
{
    if(isVisible)
    {
        g.drawImage(image, x, y, null);
    }
}
}
class Coins extends Sprite
{
int amount;
public Coins(int amt)
{
    amount = amt;
}
public int getAmount()
{
    return amount;
}
public void setAmount(int amt)
{
    amount = amt;
}
}
class AnimateSprite extends Sprite
{
int speed = 5;
int directionX = 1, directionY = 1;
int healthPoints = 100;
final boolean DEAD = false;
final boolean ALIVE = true;
public void moveUp()
{
    y -= speed;
}
public void moveDown()
{
    y += speed;
}
public void moveLeft()
{
    x -= speed;
}
public void moveRight()
{
    x += speed;
}
public int getHealthPoints()
{
    return healthPoints;
}
public void setHealthPoints(int hp)
{
    healthPoints = hp;
}
public boolean hit(int amt)
{
    healthPoints -= amt;
    if(healthPoints < 0)
    return DEAD;
    else
    return ALIVE;
 }
}
class Game extends AnimateSprite implements Runnable, KeyListener
{
 AnimateSprite user;
 AnimateSprite monster, troll;
 Coins ten, twenty;
 Thread thread;
 Random r;
 public void init()
 {
    r = new Random();
    user = new AnimateSprite();
    user.setImage(getImage(getCodeBase(), "player.gif"));
    monster = new AnimateSprite();
    monster.setImage(getImage(getCodeBase(), "monster.gif"));
    troll = new AnimateSprite();
    troll.setImage(getImage(getCodeBase(), "monster.gif"));
    troll.setLocation(350, 350);
    setupCoins();
    setFocusable(true);
    addKeyListener(this);
    thread = new Thread(this);
    thread.start();
 }
 public void setupCoins()
 {
    ten = new Coins(10);
    twenty = new Coins(20);
    ten.setLocation(400, 350);
    twenty.setLocation(450, 50);
    ten.setImage(getImage(getCodeBase(), "coins.gif"));
    twenty.setImage(getImage(getCodeBase(), "coins.gif"));
 }
 public void keyPressed(KeyEvent ke) //Event handling
 {
    int key = ke.getKeyCode();
    if(key == KeyEvent.VK_UP)
    user.moveUp();
    else if(key == KeyEvent.VK_DOWN)
    user.moveDown();
    else if(key == KeyEvent.VK_LEFT)
    user.moveLeft();
    else if(key == KeyEvent.VK_RIGHT)
    user.moveRight();
 }
 public void keyReleased(KeyEvent ke) {}
 public void keyTyped(KeyEvent ke) {}
 public void update(Graphics g) {paint(g);}
 public void paint(Graphics g)
 {
    g.clearRect(0, 0, this.getWidth(), this.getHeight());
    ten.paintComponent(g);
    twenty.paintComponent(g);
    monster.setLocation(r.nextInt(10) - 5 + monster.x, r.nextInt(10 - 5 + monster.y));
    monster.paintComponent(g);
    user.paintComponent(g);
    if(user.intersects(monster))
    {
            g.setFont(new Font("Serif", Font.BOLD, 26));
            g.drawString("YOU HAVE DIED, YOU LOSE!", 20, 100); //Prints this when you lose
            thread.interrupt(); //Stopping the thread if you die
        }
 }
 public void run()
 {
    try //Try catch
    {
        while(true) //Only does this while when the boolean is true
        {
            repaint();
            Thread.sleep(10); //Thread sleeps
        }
    } catch(Exception e) {} //Exception handling
 }
 }

Answer:

Your order of inheritance seems odd, but its not whats causing the problem. Take a look at this website: http://www.dreamincode.net/forums/topic/28410-application-to-japplet-and-reverse/

Java Applets need to have init(), start(), stop(), and destroy(). You will need to put these methods in your Sprite class for the Applet to function.

Question:

I am coding one applet that will show the number of mouse clicks on a button, and another that will show the coordinates of a mouse click and change the background color to a random color.

In both cases, I encountered the "is not abstract and does not override abstract method" error in BlueJ, and I need help understanding what I am doing wrong. I'm very new to this, so any tips/proofreadings are welcome as well :)

here's the first applet:

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

public class Option1 extends Frame implements ActionListener {
public void main (String[] args) {
int click = 0;

JFrame base = new JFrame ("Button Click Counter");
base.getContentPane().setLayout(null);
base.setSize(500,500);
base.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed (ActionEvent e) {
        click++; }
    }); 

    JTextField count = new JTextField(click);

        this.add(button);
        this.add(count);

    }}    

and the coordinates one:

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

public class Option2 extends Frame implements MouseListener {
double x;
double y;
public void init() {
addMouseListener(this);


JFrame base = new JFrame("Mouse Coordinates");
base.getContentPane().setLayout(null);
base.setSize(500,500);
base.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JTextField answer = new JTextField(x + "," + y);
}
public void mouseClicked( MouseEvent e ) {
    x = e.getX();
    y = e.getY();

    this.setBackground(new Color((int)(Math.random() * 0x1000000)));
}}

Thanks in advance!


Answer:

Option1 declares to implement the ActionListener interface:

public class Option1 extends Frame implements ActionListener {

If a class does so, it must be either abstract (which Option1 is not) or it must implement the methods declared in the interface. When you take a look at the API for ActionListener, you'll find one method there:

void actionPerformed(ActionEvent e)

You need to implement this method in Option1, e.g.

@Override
public void actionPerformed(ActionEvent e) {
    click++;
}

and then register Option1 as ActionListener:

button.addActionListener(this);

The thing you tried is to implement the ClickListener in an anonymous inner class, which is also ok, but in this case Option1 must not implement ActionListener.

Your main method in Option1 is not declared properly, a main method usually is

public static void main(String[] args)

But the initialization you do in the main method should be done in the constructor or (as with Option2) in a separate method

public class Option1 extends Frame implements ActionListener {

    private int click = 0;

    public Option1() {

        JFrame base = new JFrame("Button Click Counter");
        base.getContentPane().setLayout(null);
        base.setSize(500, 500);
        base.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton button = new JButton("Click Me!");
        button.addActionListener(this);
        JTextField count = new JTextField(click);
        this.add(button);
        this.add(count);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        click++;
    }
}

The problem with Option2 is that you only implement the method mouseClicked from the interface MouseListener. There are a couple others that need to be implemented:

void mouseEntered(MouseEvent e)
void mouseExited(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)

Even if you do not want to handle these events, you need to have the empty methods.

A final tip: I don't know your IDE, but many IDEs (Eclipse, Netbeans, IntelliJ) have an option to generate the required methods for an interface for you, which saves a lot of typing ;)