How to fix the position of the button in applet
Posted
by
user1609804
on Stack Overflow
See other posts from Stack Overflow
or by user1609804
Published on 2012-09-02T03:02:53Z
Indexed on
2012/09/02
3:38 UTC
Read the original article
Hit count: 261
I'm trying to make an applet that has a buttons in the right, where each button is corresponding to a certain pokemon. I already did it, but the buttons isn't fixed.they keep following the mouse. please help. This is my code:
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class choosePokemon extends Applet implements ActionListener
{
private int countPokemon;
private int[] storePokemon;
private int x,y; //this will be the x and y coordinate of the button
BufferedImage Picture;
public int getCountPokemon(){ //for other class that needs how many pokemon
return countPokemon;
}
public int[] getStoredPokemon(){ //for other class that needs the pokemon
return storePokemon;
}
public void init(){
x=0;y=0;
try{
Picture = ImageIO.read(new File("pokeball.png"));
}
catch( IOException ex ){
}
}
public void paint( Graphics g ){
pokemon display = new pokemon(); // to access the pokemon attributes in class pokemon
ButtonGroup group = new ButtonGroup(); //create a button group
for( int a=0;a<16;a++ ){ // for loop in displaying the buttons of every pokemon(one pokemon, one button)
display.choose( a ); //calls the method choose in which accepts an integer from 0-15 and saves the attributes of the pokemon corresponding to the integer
JButton pokemonButton = new JButton( display.getName() ); // creates the button
pokemonButton.setActionCommand( display.getName() ); // isasave sa actioncommand yung name ng kung ano mang pokemon
pokemonButton.addActionListener(this); //isasama yung bagong gawang button sa listener para malaman kung na-click yung button
pokemonButton.setBounds( x,y,50,23 );
group.add( pokemonButton ); //eto naman yung mag-aadd sa bagong gawang button sa isang group na puro buttons(button ng mga pokemon)
y+=23;
if( a==7 ){
x+=50;
y=0;
}
add( pokemonButton ); //will add the button to the applet
}
g.drawImage( Picture, 120, 20, null );
}
public void actionPerformed(ActionEvent e) {
try{ //displays the picture of the selected pokemon
Picture = ImageIO.read(new File( "pokemon/" + e.getActionCommand() + ".png" ));
}
catch( IOException ex ){
}
}
public boolean chosen( int PChoice ){ //this will check if the chosen pokemon is already the player's pokemon
boolean flag = false;
for( int x=0; x<countPokemon && !flag ;x++ ){
if( storePokemon[x]==PChoice ){
flag = true;
}
}
return flag;
}
© Stack Overflow or respective owner