This site requires JavaScript, please enable it in your browser!
Greenfoot back
mobileash66
mobileash66 wrote ...

2014/9/2

How would I make buttons spawn in the world and play sounds when clicked?

mobileash66 mobileash66

2014/9/2

#
This is what I have so far. import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class background here. * * @author (your name) * @version (a version number or a date) */ public class background extends World { private String bassButtons = {"a","S","d","f","g","h","j","k","l",";","'","\\"}; private String bassSounds = {"3c","3d","3e","3f","3g","3a","3b","4c","4d","4e","4f","4g"}; //private Button textButton=null; /** * Constructor for objects of class background. * */ public background() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(600, 400, 1); bassButtons(); // creating the button //Button textButton= new Button("Click here to run method"); //addObject(textButton, 500, 30); // in the act to catch button click //if(textButton.getWorld() != null && textButton.gotClicked()) methodName(); } private void bassButtons() { int i = 0; while (i < bassButtons.length) { button key = new button (bassButtons, bassSounds+".wav"); addObject(key,i*key.getImage().getWidth() + 54,140); i++; } } }
danpost danpost

2014/9/2

#
You first need to change this line:
Button textButton= new Button("Click here to run method");
to this:
textButton= new Button("Click here to run method");
so that your reference will hold the object. Then, you need to move these lines:
// in the act to catch button click  
if (textButton.getWorld() != null && textButton.gotClicked()) methodName();
into an 'act' method in the class (as the first line instructs -- or attempts to). But this code needs to be adjusted a bit. First, it only needs to be this:
if (Greenfoot.mouseClicked(textButton)) new GreenfootSound(/* sound filename */).play();
supplying the appropriate name of the sound file.
danpost danpost

2014/9/2

#
I must say, however, that this has nothing to do with the piano or its keys. That is, it looks like you previously asked for help on getting a clicked button to play a sound or execute a method, and this code is what you got out of it. Where, if you had asked the question differently, you might have gotten help related to the piano and its keys.
davmac davmac

2014/9/2

#
mobileash66, please use 'code' tags when posting code. (Click the link that says "Posting code? read this!" under the text entry area). Your code above looks wrong because it contains:
 [i]
... which creates italic text.
You need to login to post a reply.