what button is pressed java - java

there is possible to recognize whst btn is pressed with a unique eventListener?
i tried this code, but didn't work
ActionListener one = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (gr1.getCounter1() < 5) {
gr1.setCounter1(gr1.getCounter1() + 1);
if (arraybtn[1].isSelected())
test1.setIcon(play1a);
if (arraybtn[2].isSelected())
test1.setIcon(play1b);
if (arraybtn[3].isSelected())
test1.setIcon(play1c);
if (arraybtn[4].isSelected())
test1.setIcon(play1d);
if (arraybtn[5].isSelected())
test1.setIcon(play1e);
} else {
pn5.setText("No more cards");
}
}
};
thanks, !

use the getSource method from the ActionEvent object.
Your code would look like:
if (e.getSource() == arraybtn[1])
test1.setIcon(play1a);
if (e.getSource() == arraybtn[2])
test1.setIcon(play1b);
if (e.getSource() == arraybtn[3])
test1.setIcon(play1c);
if (e.getSource() == arraybtn[4])
test1.setIcon(play1d);
if (e.getSource() == arraybtn[5])
test1.setIcon(play1e);
to get the source of the event (i.e. the button that was pressed).
http://download.oracle.com/javase/1.4.2/docs/api/java/util/EventObject.html#getSource()

Your code above is in great need of being refactored. For instance you have an array of JButtons, why not a similar array of ImageIcons, then you could get rid of all those if blocks.
For instance:
ActionListener one = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (gr1.getCounter1() < 5) {
gr1.setCounter1(gr1.getCounter1() + 1);
for (int i = 0; i < arraybtn.length; i++) {
if (arraybtn[i] == e.getSource()) {
test1.setIcon(play1Icons[i]);
}
}
} else {
pn5.setText("No more cards");
}
}
};
And don't forget my recommendation in your other thread about further refactoring including creating a Player class, a Card class, a Deck class, a GameManager and so forth.
Regarding your question, "in this script i have play1a = hand.get(1).getImage(); if i do with another array like test1.setIcon(play1Icons[i]);, how i can define the variable?"
Is hand an ArrayList? One way to solve it is to do something like
test1.setIcon(hand.get(i).getImage());
or some variant on that.

Related

Why does my converted string continue to append

I'm currently trying to create a randomly generated string. Problem is, with the way I have it setup it continues to add on to itself.
My code ( I'm calling a lot of static variables from another class so don't worry about that portion)
class Generate1 extends Thread{
#Override
public void run() {
while(RUNNING == true){
generate();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void generate(){
for(int i=0;i<length;i++){
int decider = rando.nextInt(6)+1;
if(decider == 1){
sb1.append("A");
}
if(decider == 2){
sb1.append("B");
}
if(decider == 3){
sb1.append("C");
}
if(decider == 4){
sb1.append("D");
}
if(decider == 5){
sb1.append("E");
}
if(decider == 6){
sb1.append("F");
}
}
Log.d("PSS",sb1.toString()); // this here is the stringbuilder being outputted
}
}
if I set length to 2, in my log it would look something like:
DF
DFCA
DFCAEF
instead of my desired output:
DF
CA
EF
how do I fix this? ( I know this is probably a stupid question but it's late and pondering through code hurts my eyes and brain )
edit - shmosel brought light to what was wrong. It was a really simple fix to me overlooking something
You're using the same StringBuilder instance for each call to generate(). Use a fresh one instead:
private void generate(){
StringBuilder sb1 = new StringBuilder(length);
// ...
}

A JButtonGrid created with an Arry, and with actionlistener in an Arry, get the info of the Button?

for (int b = 0; b < Hsize; b++) {
for (int c = 0; c < Lsize; c++) {
System.out.println(Hsize + Lsize);
Button[b][c] = new JButton("b:" + b + "c:" + c);
Button[b][c].setBounds(l, h, 40, 40);
Button[b][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(e.getSource());
}
});
}
}
The output if one of the buttons is pressed:
javax.swing.JButton[0 2,95,105,40x40,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#53c0c322,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=D:/Users/Max/workspace/Battleship/images/Unbenannt.png,disabledIcon=D:/Users/Max/workspace/Battleship/images/Unbenannt.png,disabledSelectedIcon=D:/Users/Max/workspace/Battleship/images/Unbenannt.png,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=,defaultCapable=true]
How can I filter out only the {0 2, or anything different for example the b/c coordinate ?
Since you've attached the listener to the button, you know that the triggering object is a Button. You can cast it into a button and then use the get methods to access the information you need. Right now you're just printing everything about the object.
public void actionPerformed(ActionEvent e) {
Button b = (Button)e.getSource();
System.out.println(b.getAlignmnetX()); //get whatever you need
}
Button inherits from a bunch of classes, so you'll have to look up the documentation to figure out which get methods are available for you to use.
http://docs.oracle.com/javase/7/docs/api/java/awt/Button.html

Java JButtons doesnt appear on the JFrame

Here's the significant fragment of JFrame HidingOperationView:
hideBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0){
currentPixelInImageToHide.setVisible(true);
pixelOfToHideTable.setVisible(true);
nextStep.setVisible(true);
doAll.setVisible(true);
SteganographyOperationsUtil.hidingOperation(
getSelectedFirstImageModel(), copyOfToHide, posterisation);
}
});
nextStep.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0){
SteganographyOperationsUtil.key=1;
}
});
doAll.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0){
SteganographyOperationsUtil.key2=1;
}
});
key and key2 are my controlers in the class SteganographyOperationsUtil, when to wait within the loop:
int key = 1
int key2 = 0
Key controled by the button 'next step', so the loop would go only once forward, show the results in the JTables and wait for another click.
Key2 controled by the button 'doAll', which allows the loop run till the end without stopping.
in the hiding operation:
for (int x = 0; x < hiding.getWidth(); ++x) {
for (int y = 0; y < hiding.getHeight(); ++y) {
if(temp < header.length()){
...
}else{
while (key!=1){
sleep(100);
}
key=key2;
...
if (key2 == 0){
throwToTable(HidingOperationView.pixelOfToHideTable,
colorOfToHideBinary);
}
}
}
}
The problem is that the buttons that control the loop doesn't appear at all,
they only do, when i comment the line:
SteganographyOperationsUtil.hidingOperation( getSelectedFirstImageModel(), copyOfToHide, posterisation);
Maybe it's not best way to control the loop, but i have no clue, how to do it otherwise.

For loop display numbers in label [duplicate]

The idea of my program is to select one name from a list that saved before in other JFrame. I'd like to print in the label all names one after the other with small delay between them, and after that stop at one of them. The problem is that lbl.setText("String"); doesn't work if there is more than one setText code.
Here is the part of my code :
public void actionPerformed(ActionEvent e)
{
if (RandomNames.size != 0)
{
for (int i = 0; i < 30; i++)
{
int rand = (int)(Math.random() * RandomNames.size);
stars.setText(RandomNames.list.get(rand));
try
{
Thread.sleep(100);
}
catch (InterruptedException err)
{
err.printStackTrace();
}
}
int rand2 = (int)(Math.random() * RandomNames.size);
stars.setText(RandomNames.list.get(rand2));
RandomNames.list.remove(rand2);
RandomNames.size = RandomNames.list.size();
}
if (RandomNames.list.size() == 0)
{
last.setText("\u062A\u0645 \u0638\u0647\u0648\u0631 \u062C\u0645\u064A\u0639 \u0627\u0644\u0623\u0633\u0645\u0627\u0621 \u0627\u0644\u062A\u064A \u0641\u064A \u0627\u0644\u0642\u0627\u0626\u0645\u0629 !");
}
}
Don't use a loop or Thread.sleep. Just use a javax.swing.Timer. The following will cause 30 iterations occurring every 1000 milliseconds. You can adjust the code in the actionPerformed accordingly to what you wish to happen every so many milliseconds.
int count = 0;
...
Timer timer = new Timer(1000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if (count == 30) {
((Timer)e.getSource()).stop();
} else {
int rand = (int) (Math.random()* RandomNames.size);
stars.setText(RandomNames.list.get(rand));
count++;
}
}
});
timer.start();
If you want you can just set up the Timer in the constructor, and start() it in the actionPerformed of another button's listener.
See more at How to use Swing Timers

New to JButtons, how to make them preform an event?

Basically, what I have are 2 arrays. One array of JButtons 26 long, one array of Strings with each letter of the alphabet, and a for loop to create a button for each letter of the alphabet and insert it into the JButton array:
JButton[] buttons = new JButton[26];
String letters[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(letters[i]);
panel.add(buttons[i]);
}
What I want to do is create an event for all the buttons. Whenever a button is pressed, whatever letter it coincides with will be set as the value for a String called guess.
So far I understand that I need to do something like this:
x.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Insert what I want to happen
}
});
My problem is with where I wrote x. I am not sure what to put there. I need this to work for all 26 buttons in the array...
Sorry if this seems obvious/simple. I am obviously new to java and I just don't understand how JButtons work and how to do this.
Define an ActionListener like shown below.
ActionListener aListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event){
//find the actioncommand and do what is required.
}
};
Associate this ActionListener to every button.
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(letters[i]);
buttons[i].setActionCommand(letters[i]);
buttons[i].addActionListener(aListener);
panel.add(buttons[i]);
}
Just test the actionCommand which is a String value and compare it with a the letter, and do something.
x.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals("A")
// do something
else if (e.getActionCommand().equals("B")
// do soemthing
...
...
}
});
I prefer to use a switch though for cases like this.
public void actionPerformed(ActionEvent e){
String letter = e.getActionCommand();
switch(letter) {
case "A" : do something; break;
case "B" : do something; break;
case "C" : do something; break;
...
...
}
}

Categories

Resources