cherryduck 22 Newbie Poster

Thanks a lot for your help, I'll see if I can apply it like that, cheers again.

cherryduck 22 Newbie Poster

Yes they are indeed JLabels. I have managed to do it as such:

private void cardAction(int cardClicked) {
        JLabel cardNum = null;
        BufferedImage cardNumImage = null;
        String cardNumName = null;
        switch(cardClicked) {
            case 0: cardNum = CardOne;
                    cardNumImage = cardOneImage;
                    cardNumName = cardOneName;
                    break;
            case 1: cardNum = CardTwo;
                    cardNumImage = cardTwoImage;
                    cardNumName = cardTwoName;
                    break;
            case 2: cardNum = CardThree;
                    cardNumImage = cardThreeImage;
                    cardNumName = cardThreeName;
                    break;
            case 3: cardNum = CardFour;
                    cardNumImage = cardFourImage;
                    cardNumName = cardFourName;
                    break;
            case 4: cardNum = CardFive;
                    cardNumImage = cardFiveImage;
                    cardNumName = cardFiveName;
                    break;
            case 5: cardNum = CardSix;
                    cardNumImage = cardSixImage;
                    cardNumName = cardSixName;
                    break;
        }
        cardNum.setIcon(new ImageIcon(cardNumImage));
        if(currentCardName == null) {
            currentCardName = cardNumName;
        } else {
            newCardName = cardNumName;
        }

etc etc which works just as I expect it to, so theoretically I have what I need, but feel free to suggest a better way if you wish, thanks for your replies and help regardless.

cherryduck 22 Newbie Poster

Okay thank you very much, I'm Googling as we speak, could you possibly show how that might be used with some generic code?

cherryduck 22 Newbie Poster

Hey guys and guyettes, I'm trying to make a game, when you click on a card, a certain set of things happen to that particular card. As the set of actions that occur are the same for each and every card, putting everything in the MouseClicked event for each and every card would result in a lot of duplicate code with only the parameter names changed, so I am trying to simplify this down. The code for when a card is clicked is such:

private void CardOneMouseClicked(java.awt.event.MouseEvent evt) {                                     
        int cardClicked = 0;
        cardAction(cardClicked);
    }

cardAction then uses a switch on cardClicked to determine which card called the method and change the parameters accordingly.

private void cardAction(int cardClicked) {
        String cardNum = null;
        String cardNumImage = null;
        String cardNumName = null;
        switch(cardClicked) {
            case 0: cardNum = "CardOne";
                    cardNumImage = "cardOneImage";
                    cardNumName = "cardOneName";
            case 1: cardNum = "CardTwo";
                    cardNumImage = "cardTwoImage";
                    cardNumName = "cardTwoName";
            case 2: cardNum = "CardThree";
                    cardNumImage = "cardThreeImage";
                    cardNumName = "cardThreeName";
            case 3: cardNum = "CardFour";
                    cardNumImage = "cardFourImage";
                    cardNumName = "cardFourName";
            case 4: cardNum = "CardFive";
                    cardNumImage = "cardFiveImage";
                    cardNumName = "cardFiveName";
            case 5: cardNum = "CardSix";
                    cardNumImage = "cardSixImage";
                    cardNumName = "cardSixName";
        }

I then use the same code for each card, but tailored via the switch to each specific card:

cardNum.setIcon(new ImageIcon(cardNumImage));
        if(currentCardName == null) {
            currentCardName = cardNumName;
        } else {
            newCardName = cardNumName;
        }

and some other code which isn't really important right now, although in the …

cherryduck 22 Newbie Poster

Thank you VERY much for your help, it was a case of changing my mean code to

for (int i = 0; i < threshold; i++){
m1 += hist[i]*i;
count += hist[i];
}

And of course re-initialising my count. Once you told me the logic, I sat down with a good old pen and paper and figured out what I was trying to do. Thanks!

cherryduck 22 Newbie Poster

Thanks, I understand what you're saying there, I just have to figure out how to implement that in my current code...and I'm not very good at coding...this will be fun! Haha, cheers for your help.

cherryduck 22 Newbie Poster

The values in hist can get arbitrarily large, based on the size of the image, so m1 and m2 can get arbitrarily large, so tnew and thus threashold ditto, thus array index error when threashold is upper bound of loop.

Pants, any idea how to overcome this?

cherryduck 22 Newbie Poster

Suggests threashold has got > 255 - tho I can't see how (especially with the wrong value of count being used to divide m2). Try printing it to confirm?

My threshold is 264 on one of my test images, and 734 on another, and I have no idea how or why this is happening.

cherryduck 22 Newbie Poster

I've removed the initialisation of the array values to 0 and that still works, thanks, might as well prune out unnecessary code. My array index exception is occuring at line 37. Oh, and re-initialising count just makes it crash for EVERY image instead of just some.

cherryduck 22 Newbie Poster

Hey, this is a continuation of my image editing program, I am trying to perform intensity thresholding with an intelligent threshold. My code thus far:

private void thresholdMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                                  
        BufferedImage inputImage = getImage();
        setUndoImage(inputImage);
        BufferedImage thresholdImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), inputImage.getType());
        int threshold = 0;
        int tnew = 128;
        int count = 0;
        double m1, m2;

        for (int x = 0; x < inputImage.getWidth(); x++) {
            for (int y = 0; y < inputImage.getHeight(); y++) {
                int red = (inputImage.getRGB(x,y) & 0x00ff0000) >> 16;
                int green = (inputImage.getRGB(x,y) & 0x0000ff00) >> 8;
                int blue = (inputImage.getRGB(x,y) & 0x000000ff);
                int grey = (int) ((0.30 * red) + (0.59 * green) + (0.11 * blue));
                thresholdImage.setRGB(x,y, 0xff000000 | grey << 16 | grey << 8 | grey);
            }
        }

        int[] hist = new int[256];

        for (int h = 0; h < 255; h++) {
        hist[h] = 0;
        }

        for (int x = 0; x < thresholdImage.getWidth(); x++) {
            for(int y = 0; y < thresholdImage.getHeight(); y++) {
                int i = (thresholdImage.getRGB(x, y) & 0x000000ff);
                hist[i]++;
            }
        }

        do {
            threshold = tnew;
            m1 = m2 = 0.0;
            for (int i = 0; i < threshold; i++){
                m1 += hist[i];
                count++;
            }

            m1 /= count;

            for (int i = threshold; i < 255; i++){
                m2 += hist[i];
                count++;
            }

            m2 /= count;

            tnew = (int)((m1 + m2) / 2.0);
        } while (tnew != threshold);

        for (int x = 0; x < thresholdImage.getWidth(); x++) {
            for (int y = 0; y < …
cherryduck 22 Newbie Poster

Turns out I just had my brackets in the wrong place when I was getting the red, green and blue values, oh dear! Works now though :)

cherryduck 22 Newbie Poster

Hi everyone, I'm trying to write an image editor in Java, one of the functions is histogram equalisation, but my code is producing a greyscale image instead :(

Here is my code, any help would be greatly appreciated, ta.

private void histEqMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                               
        BufferedImage inputImage = getImage();
        BufferedImage histEqImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(), inputImage.getType());
        int maxIntensity = 255;

        int[] red = new int[256];

        for (int h = 0; h < 255; h++) {
            red[h] = 0;
        }

        for (int x = 0; x < inputImage.getWidth(); x++) {
            for(int y = 0; y < inputImage.getHeight(); y++) {
                int i = inputImage.getRGB(x,y) & 0x00ff0000 >> 16;
                red[i]++;
            }
        }

        int sumr = 0;

        for (int x = 0; x < red.length; x++) {
            sumr += red[x];
            red[x] = sumr * maxIntensity /(inputImage.getWidth() * inputImage.getHeight());
        }

        for (int x = 0; x < inputImage.getWidth(); x++) {
            for(int y = 0; y < inputImage.getHeight(); y++) {
                int i = inputImage.getRGB(x,y) & 0x00ff0000 >> 16;
				i = red[i];
				histEqImage.setRGB(x, y, (histEqImage.getRGB(x, y) & 0xff00ffff) | (i << 16));
            }
        }

        int[] green = new int[256];

        for (int h = 0; h < 255; h++) {
            green[h] = 0;
        }

        for (int x = 0; x < inputImage.getWidth(); x++) {
            for(int y = 0; y < inputImage.getHeight(); y++) {
                int i = inputImage.getRGB(x,y) & 0x0000ff00 >> 8;
                green[i]++;
            }
        }

        int sumg = 0;

        for (int x = 0; x < green.length; x++) {
            sumg += green[x];
            green[x] = sumg * maxIntensity /(inputImage.getWidth() …
cherryduck 22 Newbie Poster

Thanks a lot, easier than anticipated :-)

cherryduck 22 Newbie Poster

Hi everyone, I'm making a program to store library books details, my constructor is such:

public Book(String author, String title, String publisher, int year)

and I'm using an array to store and number the books and details, as such:

for(int i = 0; i <= 100; i++)
{
	String book[i] = author + "-" + title + "-" + publisher + "-" + year;
}

The problem is, later on I need to print out the seperate details, each on different lines ie:

Judith Bishop
Java Gently
Addison-Wesley, 2001
Library number 345

so I wish to split the string at each "-" and put them on a new line. The question is how do I go about splitting the strings? I know there is a split method but I'm not sure how to use it.

cherryduck 22 Newbie Poster

Ok fair enough, my main is as follows:

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

public class SpaceFrame{
	
 	public static void main(String[] args){
		JFrame jf = new JFrame("The Last Space Invader");
		AlienLandingPanel alp = new AlienLandingPanel();
		jf.add(alp);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.setSize(256, 512);
		jf.setVisible(true);
	}
}

The actual code which initiates everything else is in AlienLandingPanel, as below:

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

public class AlienLandingPanel extends JPanel implements Runnable{
	
	private Thread t;
	private Invader inv;
	private Tank tank;
	//private Missile miss;
	private Image backImg;
	boolean changed = true;
	String score;
	String lives;
	int livesRem = 10; 
	
	public AlienLandingPanel() {
		
        inv = new Invader();
        add(inv);
        tank = new Tank();
        try{
            backImg = ImageIO.read(new File("back.jpg"));
        }
        catch(Exception e)
        {
            System.out.println("Not found");
        }
        t = new Thread(this);
        t.start();
    }
        
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(backImg, 0, 0, this);
        inv.paintComponent(g);
        tank.paintComponent(g);
    }    public void run()
    {
        try{
            while(!inv.dead())
            {
                Thread.sleep(50);          
                Point p = inv.where();
                tank.moveTank(p.x);
                repaint();
            }
        }
    

        catch(InterruptedException inter)
        {
            
        }
    }

}

The program as a whole is by no means complete and most likely needs bits adding to it. My other main problem at the moment is that I am entirely unable to get my missiles to work, if I use miss.paintComponent(g); in the AlienLandingPanel the whole thing crashes :-S but I guess that's another problem altogether for another day.

cherryduck 22 Newbie Poster

This is just one class file of many, so the main is contained elsewhere.

cherryduck 22 Newbie Poster

Hi everyone, I'm trying to create a simple Java game, The Last Space Invader, where you control the last space invader and the tank automatically tracks and shoots at you. The code for my invader is as follows:

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

public class Invader extends JPanel{
	
    private Image sprite;
    private int spriteW;
    private int spriteH;
    private int speedX = 5;
    private int speedY = 8;
    private Point invPos;
    private boolean alive = true;
    private boolean hitright = false;
    private boolean hitleft = false;
	private boolean landed = false;
	static final int RIGHT = 1;
	static final int LEFT = 0;
	private int rightEdge;
	private int leftEdge;
	private int top;
	private int bottom;
	private int lives = 5;
	private int spriteCount = 1;
	
    public Invader()
    {
        this.addKeyListener(new KeyboardListener());
        this.setFocusable(true);
        invPos = new Point(110, 20);
        rightEdge = 256 - getSpriteW();
        setBoundaries(0, 208, 224, 395);
        start();
    }
        
    public void paintInv()
    {
        try{            
            sprite = ImageIO.read(new File("Invader" + spriteCount + ".png"));
            spriteW = sprite.getWidth(this);
            spriteH = sprite.getHeight(this);
        }
        catch(Exception e){
            System.out.println("File not found");
        }
    }
    
    public boolean dead()
    {
        return !alive;
    }
    
    public Point where()
    {
        return invPos;
    }
    
	public void checkPosition()
	{
		if (invPos.x < leftEdge )
		{
			invPos.x = leftEdge;
			if (!hitleft)
			{
				hitleft = true;
				hitright = false;
				invPos.y += speedY;
			}
		}
		
		if (invPos.x > rightEdge )
		{
			invPos.x = rightEdge;
			if (!hitright)
			{
				hitright = true;
				hitleft = false;
				invPos.y += speedY;
			}
		}
		
		if (invPos.y > bottom)
		{
			invPos.y = …
cherryduck 22 Newbie Poster

I've done it now, took too long lol, we haven't been taught about Scanner so I don't know if we're meant to use it, thanks.

cherryduck 22 Newbie Poster

Hey everyone, I'm writing a program as follows:

CourseMarker course Java u4 exercise sunflower: Sunflower Growth part 2 (Weight: 3)
===================================================================================


Introduction
============

This is a continuation of last weeks exercise on the growth of sunflowers, but

the problem is now more complex. It now involves loops and makes sure that you

can keep track of your variables.


Problem
=======

Last week you had to read in details of sunflowers that grow at different
speeds. This week we shall be dealing with more than one sunflower.

Therefore you are to write a program to repeatedly read
a rate of growth in cm per day (double)
the number of days growth (int)
and compute and print the height of the sunflower at the end of the time in both
centimetres, and metres and centimetres (see typical output)
This week you will also have to keep track of the number of sunflowers planted,

and also print out the average height of the sunflowers at the end.

Also, our friendly sunflower gardener has realised there is money to be made
from his venture. He is able to sell his sunflowers but only when they are
at least 120cm tall, but less than 160cm. So he would be very grateful if you
could tell him on which days he is able to sell his plants. This will

cherryduck 22 Newbie Poster

Well, it turns out we're not supposed to learn to do that yet, we were supposed to be learning to use mul so I've done it correctly for this particular piece of coursework. Thanks.

Salem commented: ok :) looks like you're golden then for this one. +22
cherryduck 22 Newbie Poster

Just call mul several times in a row.

Thanks, that's what I ended up doing although it was hardly efficient...oh well I'm sure I will learn.

cherryduck 22 Newbie Poster

Sorry i'm an absolute beginner and I've not yet covered loops or jumps, any chance you could expand on that answer?

cherryduck 22 Newbie Poster

"Write a program in MIPS assembly language which reads two integers a, b,
calculates a^3 + 3ab^2 + 3a^2b + b^3 and outputs the result."

My question is, how do I calculate powers of things in MIPS? Also I think I probably need to simplify that equation first...does anyone know how I should begin?