I am trying to make it easier to make buttons by making a method, but when i use the method to make a button nothing happens when i press the button, even though i have a listener for the button
public void assignButton(Button wtf,String text) //program to assign buttons easily
{
wtf = new Button(text);
add(wtf);
wtf.addActionListener(this);
}
i use assignButton(Check,"words"); to make the button
public void actionPerformed(ActionEvent event) //checks if button has been pressed
{
if(event.getSource() == Check)
{
code ++;
}
else
{
code = 2;
}
repaint();
every time i press the button it sets code to 2, anyone know what i am doing wrong?
Edit:
full code
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class PressSafeTemp extends Applet implements ActionListener
{
Button clear,Check;
int code = 0;
public void init() //assigns buttons
{
clear = new Button("C");
add(clear);
clear.addActionListener(this);
assignButton(Check,"words");
}
public void paint(Graphics g)
{
g.drawString(""+code,10,10);
}
public void assignButton(Button wtf,String text) //program to assign buttons easily
{
wtf = new Button(text);
add(wtf);
wtf.addActionListener(this);
}
public void actionPerformed(ActionEvent event) //checks if button has been pressed
{
if(event.getSource() == Check)
{
code ++;
}
else if(event.getSource() == clear)
{
code = 0;
}
else
{
code = 2;
}
repaint();
}
}
The problem is you pass Check to the method (as wtf) but then immediately set it to a new instance; this instance is not Check. It does get added but you can't get at it with Check.
You probably want to do...
Button getButton(String text) {
Button button = new Button(text);
button.addActionListener(this);
return button;
}
and then Check = getButton(someText); followed by add(Check);.
If you don't actually need Check laying around, you could also just add it directly with add(getButton(someText));.
I'm not sure what means for you event.getSource() == Check but that is the key, you need to check the correct comparison in your case. Something like for example:
event.getSource().class.equals(JCheckBox.class)
Related
I am trying to write a class that both listens for actions from buttons and notifies another class when one of the buttons is pressed. I have an ArrayList<ActionListener> and methods addActionListener(ActionListener al), removeActionListener(ActionListener al), and notifyActionListeners(ActionEvent ae). I print to a separate window whenever I add a listener, and print the size of actionListeners as well. It works great and prints that I have 1 actionListener, but then when I try to notify the listeners it says that there are 0 objects in actionListeners. I added a println() to the removeActionListener(al) method to see if it is called, and it never is.
Here's the class:
package state;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import driver.GameDriver;
import ui.Button;
public class MainMenu extends Menu {
private static final long serialVersionUID = -7130241947836998525L;
private ArrayList<ActionListener> actionListeners;
private Button play;
private Button scores;
private Button settings;
private Button help;
private Button exit;
public MainMenu() {
super("Main Menu");
actionListeners = new ArrayList<ActionListener>();
}
#Override
protected void addComponents() {
//Irrelevant to Stackexchange
}
#Override
public void actionPerformed(ActionEvent arg0) {
Object src = arg0.getSource();
if (src == play) {
} else if (src == scores) {
} else if (src == settings) {
} else if (src == help) {
} else if (src == exit) {
ActionEvent ae = new ActionEvent(this, ActionEvent.ACTION_FIRST, "exit");
notifyActionListeners(ae);
}
}
public void addActionListener(ActionListener al) {
GameDriver.println("Added Listener:");
actionListeners.add(al);
GameDriver.println(actionListeners.size());
}
public void removeActionListener(ActionListener al) {
GameDriver.println("Removed al for some reason");
actionListeners.remove(al);
}
private void notifyActionListeners(ActionEvent ae) {
GameDriver.println("Sending exit to " + actionListeners.size() + " listeners.");
for(int i = 0; i < actionListeners.size(); i++) {
GameDriver.println("Exit sent");
actionListeners.get(i).actionPerformed(ae);
}
}
}
Here are the methods that actually reference the instance of MainMenu:
1. Initialization
protected GameDriver() {
mainMenu = new MainMenu();
mainMenu.addActionListener(this);
debugger = new Debugger();
println("Size Loader Test...");
SizeLoader.loadSizes();
println(SizeLoader.getCurrentSize());
println("Complete.");
println("Window Test...");
window = new Window("Asteroids");
windowManager = new WindowManager();
// window.addWindowFocusListener(windowManager);
// window.addWindowListener(windowManager);
// window.addWindowStateListener(windowManager);
window.buildWindow(SizeLoader.getCurrentWidth(), SizeLoader.getCurrentHeight());
window.add(new MainMenu());
println("Complete");
println("Menu Test...");
}
And here's the actionPerformed(ae):
#Override
public void actionPerformed(ActionEvent e) {
println("Event happened");
if (e.getSource() == mainMenu) {
if (e.getActionCommand() == "exit") {
println("Exiting FR this time...");
}
}
}
As per my comment: 3) You're creating more than one MainMenu object, one you add a listener to and the other you add to window. This looks to be a serious bug.
Instead create only one instance, set its state as needed (add listeners) and add it to the gui.
So change
window.add(new MainMenu());
To
window.add(mainMenu);
And again as per my prior comment, don't use == for String equality check but rather the .equals method.
I am trying to do a simple Minesweeper game using JFrame, however I am having troubles with the creation of objects. I am creating 96 buttons, some of which get the property of being wrong ("F") and right ("R"):
public class GUIBase extends JFrame {
private JButton button;
private JButton fButton;
public GUIBase() {
super("Minesweeper");
setLayout(new FlowLayout());
//Fields
int position;
for (int i = 0; i < 96; i++) {
position = (int) (Math.random() * 100);
if (position < 80) {
button = new JButton("R");
button.setToolTipText("Is this the correct one?");
add(button);
} else {
fButton = new JButton("F");
fButton.setToolTipText("Is this the correct one?");
add(fButton);
}
}
I then use ActionListener in order to check whether or not the button is correct. If the button is correct, it will get .setEnabled(false), otherwise the game ends:
//Action
Action action = new Action();
button.addActionListener(action);
fButton.addActionListener(action);
}
private class Action implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Somethin");
if (event.getSource() == button) {
button.setEnabled(false);
} else if (event.getSource() == fButton) {
JOptionPane.showMessageDialog(null, "You lost!");
System.exit(0);
} else {
JOptionPane.showMessageDialog(null, "An error ocurred");
System.exit(0);
}
}
}
Everything in the game turns out as planned, however only the last correct button ("R") and last wrong one ("F") are connected to the ActionListener. The rest of the buttons do not do anything when pressed.
How can I fix this?
The problem is that you only have two variables (attributes of the class GUIBase, specifically), and your are assigning to it each time you create a new button. Hence, you only have a reference to the last buttons.
You need an array of buttons. Let's see:
public class GUIBase extends JFrame {
public final int MAX_BUTTONS = 96;
private JButton[] buttons;
// ...
}
The next step is to create the array itself at the beginning:
public GUIBase() {
super("Minesweeper");
setLayout(new FlowLayout());
this.buttons = new JButton[MAX_BUTTONS];
//Fields
int position;
for (int i = 0; i < buttons.length; i++) {
position = (int) (Math.random() * 100);
this.buttons[ i ] = new JButton("R");
this.buttons[ i ].setToolTipText("Is this the correct one?");
this.add(this.buttons[ i ]);
Action action = new Action();
this.buttons[ i ].addActionListener(action);
}
}
You'll probably need more depth in arrays in order to completely understand the code. Basically, an array is a continuous collection of variables, which you can index by its position, from 0 to n-1, being n the number of positions.
Then you'll probably be able to fill the gaps yourself.
Hope this helps.
One part of your problems is coming from your action listener.
Of course, one part is that your code probably needs a list/array to keep track of all created buttons; but at least right now, you can rework your code without using arrays/list:
private class Action implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Somethin");
if (event.getSource() instanceofJButton) {
JBUtton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
if (buttonText.equals("R") ...
else if (buttonText.equals("F")
You see, the whole point here is: as of now, you just need to know what kind of button was created. And your ActionListener knows which button it was clicked on ...
For example I have 2 checkbox and 1 button my code would be like this.
private class CheckBoxHandler implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (chckbxNewCheckBox1.isSelected() && chckbxNewCheckBox2.isSelected())
{
checkboxcheck1 = 1;
checkboxcheck2 = 1;
}
else if(chckbxNewCheckBox1.isSelected())
{
checkboxcheck1 = 1;
}
else if(chckbxNewCheckBox2.isSelected())
{
checkboxcheck2 = 1;
}
}
}
private class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (checkboxcheck1 == 1 && checkboxcheck2 == 1)
{
textFieldSum.setText(String.valueOf(counter));
textFieldSum1.setText(String.valueOf(counter1));
}
else if(checkboxcheck1 == 1)
{
textFieldSum.setText(String.valueOf(counter));
}
else if (checkboxcheck2 == 1)
{
textFieldSum1.setText(String.valueOf(counter1));
}
else
{
checkboxcheck1 = 0;
}
}
}
But then what if I have more than 2 checkbox like 10 or more.It would take forever to to make the if statement in CheckBoxHandler and ButtonHandler. Anybody know how to make it work if I have more than 2 checkbox ?
My program is read the file and count the specific character in the file and then display it. The way to display it is click on the checkbox and click the yes button. But it will take forever for me to do the if statement. You guys have any idea? Thanks yall so much for help.
Declare an array of checkboxes like so
CheckBox[] checkboxes = new CheckBox[10]; // or JCheckBox if using swing
And in the constructor, create them with
String[] filenames = { ... }; // have a list of files?
for(int i=0;i<checkboxes.length;i++){
// for each box, create and add it to your panel
mypanel.add(checkboxes[i]=new CheckBox(filename[i]));
checkboxes[i].addItemListener(mylistener);
}
then in the listener, you can have
public void itemStateChanged(ItemEvent e) {
boolean state = ((CheckBox)e.getSource()).isSelected();
// do something with this state if needed
}
But notice that you don't actually need the item listeners at all.
In the button listener you can do
public void actionPerformed(ActionEvent e) {
for (int i=0;i<checkboxes.length;i++){
if(checkboxes[i].isSelected()){
// do something with file i
}
}
}
Note that if your file operation takes time, you have to do the processing in a new thread, not just in the button handler!
I've implemented code that will - amongst other things - make a series of JButton's disabled after being clicked. The code for this is below:
ActionListener disableButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (!(event.getSource() instanceof JButton)) {
return;
}
theModel.currentWord.append(event.getActionCommand());
wordDisplay.setText(theModel.getCurrentWord());
((JButton) event.getSource()).setEnabled(false);
}
};
theModel.randomLetters();
for (int i = 0; i < 16; i++) {
dice = new JButton(theModel.letters.get(i));
dice.addActionListener(disableButton);
boggleGrid.add(dice);
}
Notice the "((JButton)event.getSource()).setEnabled(false);" line. This, after completing the previous lines, makes any clicks on the button inactionable. I wish to reverse this when a seperate button is clicked. It's code is below:
JButton submitWordButton = new JButton("Submit Word");
submitWordButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent submit) {
wordDisplay.setText("");
theModel.currentWord.delete(0, 16);
((JButton) submit.getSource()).setEnabled(true);
}
});
info.add(submitWordButton, BorderLayout.SOUTH);
My dilemma is I don't know how to reference the JButton's outside of the ActionListener that disables them once clicked and hence enabled them again. The button I want to use to do this (the one with code most recently pasted above) is in another class. Any ideas?
EDIT: I have fixed the problem. Thank you all for your help.
I am pretty new to programming, and have been struggling through an online course. I am now working on my final project, which is to: Write a program to count the number of mouse clicks on a button within a frame. The code I have seems to be WAY off. Keep in mind that this is an applet. Here is the program:
import java.awt.*;
import java.awt.event.*;
import java.awt.MouseAdapter;
public class finalproject1
{
TextField objTextField1;
public static void main(String[] args)
{
finalproject1 p1 = new finalproject1();
}
public finalproject1
{
Frame f = new Frame("Mouse Clicks");
objTextField1 = new TextField("Click the button",200);
objTextField1.setBounds(220,140,200,40);
Button button1 = new Button("Click here");
button1.setBounds(200,200,140,140);
button1.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent evt)
{
if(evt.getClickCount() == 3)
{
objTextField1TextField1.setText("Triple click");
}
else if(evt.getClickCount() ==2)
{
objTextField1.setText("Double click");
}
});
}
f.add(button1);
f.add(objTextField1);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
f.setSize(800,800);
f.setVisible(true);
}
}
First of all, I'd recommend you fix your tabbing to make sure you're looking at scoping correctly. In addition, there are some other quirks here that could be messing things up -- this really ought not to even compile.
It looks like you're trying to define a constructor, but you haven't added parentheses. This:
public finalproject1 { ... }
should become this:
public finalproject1() { ... }
It's also convention to name classes in camelcase, so FinalProject1 would be a better name.
Your paren placement is also off in this code:
button1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if(evt.getClickCount() == 3) {
objTextField1TextField1.setText("Triple click");
} else if(evt.getClickCount() ==2) {
objTextField1.setText("Double click");
}
}); // This ");" should be one brace down from where it is.
}
I can't help much more without knowing what you mean by "WAY off." Can you elaborate?
parentheses are missing to the constructor : public finalproject1() { ... }
");" at the end of method mouseClicked must be at the end of method addMouseListener.
object objTextField1TextField1 is not declared. It should be objTextField1 instead.
class name must start with upper case (Java convention)