Java JButton List Call Back - java

I am trying to create a JButton that will call back a selected list of items with the number of the items selected.
I have a primitive list made out displaying different JRadioButtons but with the JRadioButtons named rather than listed out. I have looked on another site that uses Vector collections I believe use the basic for iteration method but I just feel like I am getting a bit overwhelmed.
This is my button code right now.
// create new ButtonHandler for button event handling
ButtonHandler handler = new ButtonHandler();
submitButton.addActionListener( handler );
} // end Frame constructor
// inner class for submit button event handler
private class ButtonHandler implements ActionListener
{
//handle button event
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog(Frame.this, String.format(
"You entered: %s", event.getActionCommand() ) );
Am I anywhere near the right answer here or am that far off?

Related

Trying to create a really simple button for my Panel, but even though i implement the action listener in the class, it isn't working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
I am trying just to get the button to display some text in the console, but whatever i do it isn't working here is the code for the Button class:
public class Button extends JButton implements ActionListener {
JButton button;
Button (){
button = new JButton();
this.setText("Click NOW");
button.addActionListener(this);
this.setForeground(Color.white);
button.setBounds(300, 100, 100, 50);
this.setBackground(Color.red);
this.setBorder(null);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()== button) {
System.out.println("Display if you work");
}
}
}
There are no errors displayed and the code compiles correctly, it just isn't displaying the text in the terminal.
This code creates two JButtons, one the button field inside of the class, that you add the action listener to:
public class Button extends JButton implements ActionListener {
JButton button; // here!
Button (){
button = new JButton(); // here!
this.setText("Click NOW");
button.addActionListener(this); // and add the listener here
and the other which is the instance of this class that extends JButton:
// here !!!
public class Button extends JButton implements ActionListener {
// ....
and which is likely the one that is displayed as elsewhere you likely have this code:
Button button = new Button();
and then add this button to the GUI. Again, this "button" is from your Button class which extends JButton but doesn't have the action listener added to it.
You can solve this in one of two ways:
Don't create the new JButton button field inside of your new class and instead add the ActionListener to the this JButton, the instance of this class,
for example:
public class Button1 extends JButton implements ActionListener {
// JButton button;
Button1() {
// button = new JButton();
this.setText("Click NOW");
// button.addActionListener(this);
this.addActionListener(this);
this.setForeground(Color.white);
// button.setBounds(300, 100, 100, 50); // You really don't want to do
// this
this.setBackground(Color.red);
this.setBorder(null);
}
#Override
public void actionPerformed(ActionEvent e) {
// no need for the if block
// if (e.getSource() == button) {
System.out.println("Display if you work");
// }
}
}
Don't create a class that extends JButton but instead create code that creates a single JButton (not two) and add the ActionListener to the same object that is added to the GUI.
I'd go with number 2 myself and make it a method that returns a button with my properties of interest:
private JButton createMyButton(String text) {
JButton button = new JButton(text);
button.setForeground(Color.WHITE);
button.setBackground(Color.RED);
button.setBorder(null);
button.addActionListener(e -> {
System.out.println("Display if you work");
});
return button;
}
Side notes:
Avoid giving your class names that clash with core Java classes, such as class Button which clashes with the java.awt.Button class.
Avoid use of null layouts and setBounds. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For that reason you're far better off learning about and using the layout managers. You can find the layout manager tutorial here: Layout Manager Tutorial, and you can find links to the Swing tutorials and to other Swing resources here: Swing Info.
In your actionPerformed method, use equals in the if statement, like this:
if (e.getSource().equals(button)) {
System.out.println("Display if you work");
}
It should work. == doesn't work in this case.

addActionListener argument is incorrect

In the program I want to use actionListener to monitor a TextFrame. I created a class called monitor and there is a constructor which invoke the whole TextFieldFrame, TFFrame.
class Monitor implements ActionListener{
TFFrame tf = null;
public void Monitor(TFFrame tf){
this.tf = tf;
}
In the TFFrame class, I add a actionListener which invoke itself.
class TFFrame extends Frame{
TextField num1, num2, num3;
public void launchFrame(){
num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(20);
Label plus = new Label("+");
Button equal = new Button("=");
equal.addActionListener(new Monitor(this));
However the compiler fails with an error and the error is that the argument in the Monitor is incorrect. What is the problem?
ActionListener is an interface and has only one required method:
actionPerformed(ActionEvent e)
You don't appear to have actually implemented that method here. Normally it's called under the hood when an appropriate event occurs.
I think you may not be using events and listeners correctly. Logically speaking, given what I understand from your example code, you'd have something like this:
TFFrame tf = new TFFrame();
tf.addActionListener( new Monitor() );
One problem is that the frame has it's own set of events and will not communicate the events from clicking buttons or focusing on textfields up through the frame to the listener. The frame's events are what will end up calling the actionPerformed method that you should have in Monitor.
You could certainly add other stuff to your custom listener, but the listener generally doesn't contain a reference to thing its listening to. Perhaps what you really wanted was just an actionlistener to check when the equals button is pressed, in which case you'd have something like this.
TFFrame tf = new TFFrame();
tf.launchFrame();
Inside of the launchFrame method you would add an action listener to the equals button with some kind of listener for buttons.
equals.addActionListener( new ButtonListener() );
Now for that to work you'd have to create a class called button listener that implements action listener, and then write the appropriate event handling code inside of it's actionPerformed method.
P.S.
To be perfectly honest, much of this inference. If I'm wrong about what you want, then I'd recommend you go and read through this: https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

Handle RadioButton events after button clicked

help,
my questions are:
why isn't itemStateChanges triggered, I tried to put it in the inner class ButtonHandler and also in RadioButtonHandler Im having trouble with it, what is the right way to do it?
I want to trigger and check the marked JRadioButtons after the user click the "check" button.
What is the right way to check which button was clicked, I feel like comparing the strings is bad programming practise. Maybe using an ID ?
How should I make a "reset" button(start over), I want to uncheck all radio buttons and run the constructor once again.
Thank you for your help !
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class ExamFrame extends JFrame {
static ArrayList<Question> qArrList;
JRadioButton a1,a2,a3,a4;
public ExamFrame() {
super("Quiz");
setLayout(new GridLayout(0, 1));
GridBagConstraints gbc = new GridBagConstraints();
Exam exam = new Exam();
qArrList = exam.getExam();
int count=0;
for(Question q : qArrList){
count++;
JLabel questionLabel = new JLabel(count+". "+q.getQustion()); //swing constant ?
ArrayList<String> ansRand = q.getAllRandomAns();
a1 = new JRadioButton(ansRand.get(0));
a2 = new JRadioButton(ansRand.get(1));
a3 = new JRadioButton(ansRand.get(2));
a4 = new JRadioButton(ansRand.get(3));
add(questionLabel);
add(a1);add(a2,gbc);add(a3);add(a4);
ButtonGroup radioGroup = new ButtonGroup(); //logical relationship
radioGroup.add(a1);radioGroup.add(a2);radioGroup.add(a3);radioGroup.add(a4);
}
//buttons:
JButton checkMe = new JButton("Check Exam");
JButton refresh = new JButton("Start Over");
ButtonHandler handler = new ButtonHandler();
checkMe.addActionListener(handler);
refresh.addActionListener(handler);
add(checkMe);
add(refresh);
}
/** Listens to the radio buttons. */
public class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e) {
if(e.getActionCommand().equals("Start Over")){ //id?
//how to do this?
}
else{
RadioButtonHandler handler = new RadioButtonHandler();
a1.addItemListener(handler);
System.out.println("success?");
}
JOptionPane.showMessageDialog(ExamFrame.this, String.format("You pressed: %s", e.getActionCommand()));
}
public void itemStateChanged(ItemEvent e) //can i add it here?
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("yes?"));
System.out.println("success!");
}
}
public class RadioButtonHandler implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("radio state changed"));
}
}
}
why "itemStateChanges" isn't triggered, i tried to put it in the inner
class "ButtonHandler" and also in "RadioButtonHandler" Im having
troubles with it, what is the right way to do it? I want to trigger
and check the marked JRadioButtons after the user click the "check"
button.
ButtonHandler is implemented with ActionListener only:
public class ButtonHandler implements ActionListener{}
The itemStateChanged(ItemEvent) function belongs to ItemListener. This function is triggered if state of a source component to which this listener is registered gets changed. So implement the ItemListener. However, one more thing to note, that JButton doesn't respond to ItemListener but JRadioButton will. Because this Item events are fired by components that implement the ItemSelectable interface. Some example of such components are: check boxes, check menu items, toggle buttons and combo boxes including Radio Buttons as mentioned above.
What is the right way to check which button was clicked, i feel like
comparing the strings is wrong programming. Maybe using an ID
Well using the event source function: e.getSource(), check whither the type of the source is your expected type and cast it to appropriate type. And then you can use getName(String) function and check the name you were expecting. Of-course you should assign the name using setName(String) after initialization of component. Or using the component reference directly if it is declared in the Class context and you have direct access to the component.
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JCheckBox)
{
JCheckBox checkBox = (JCheckBox)e.getSource();
if(checkBox.getName().equals("expectedName"))
; // do my thing
}
}
How should i make a "reset" button(start over), i want to uncheck all
radio buttons and run the constructor once again.
Well you are working with ButtonGroup. And ButtonGroup has a nice function: clearSelection() to help with whatever(I could not understand the part: run the constructor part) you want.
Edit: As you wanted me to see an ItemListener implemented class, Yes i can see that But:
i can not see that you have actually registered an instance of that class(a1.addItemListener(handler);) to any component before performing any action on the component to which ButtonHandler is registered to: checkMe, refresh
In addition to that, in this action performed function, you are checking with
action command, which you haven't even set with JButton.setActionCommand(String) function. You should not assign a (Item)listener depending on event-occurrence of another (Action)listener.
Tutorial:
How to Write an ItemListener
How to Write an ActionListener
How to Use the ButtonGroup Component

Can two JButton have the same mouse clicked event function?

I am developing a calculator in Java language. The problem is that, i put ten buttons for digits(0,1,2..9) and i want that when i clicked one of them, all perform the same mouse clicked function. Is it possible? In netbeans, it does not let me do that, or i couldnt achieve. Thank you for helping.
Yes. Add the same listener to both buttons you are using.
For example, suppose you are using actionListener then:
public class ListenerClass implements Action{
#override
public void actionPerformed(ActionEvent e) {
//here retrieve information on which button has generated the event
}
}
ListenerClass listener = new ListenerClass();
JButton first = new JButton();
JButton second = new JButton();
first.addActionListener(listener);
second.addActionListener(listener);

using java swing

I need to put a value in to my class from UI (Swing) and then start my method by clicking a button. What should I do?
Getting started with swing
Here's a super simple example of a text field and a button that, when clicked, will get the text value then you can all the method you'd like to pass that value to.
public class ButtonExample extends JPanel
{
private JTextField _text;
public ButtonExample()
{
_text = new JTextField();
setLayout( new BorderLayout() );
add( _text, BorderLayout.NORTH );
add( new JButton( new CaptureTextAction() ), BorderLayout.SOUTH );
}
private class CaptureTextAction extends AbstractAction
{
private CaptureTextAction()
{
super( "Click Me" );
}
#Override
public void actionPerformed( ActionEvent ae )
{
String textToCapture = _text.getText();
// do something interesting with the text
}
}
}
Swing is just the user interface you provide to to your app.
it works like this....
you have buttons, panels and all the stuff you need for providing a proper interface, which means if you need to take text input you'll put textfield or textArea in your UI
swing applications are based on events, thats the basic difference between console based and window based applications, a console based application is sequential it compiles and then executes code sequentially it has no regard of how you interact with it.
a swing application on the other hand is event based, until any event is fired and caught it won't do anything, in java you just handle the event, which means what happens after an event occurs is decided by the programmer.
suppose there is a button click event fires and there is a listener attached to the element then the actionPerformed function gets called and it is executed
suppose you want to get the user name from the app
JButton btnSubmit = new JButton("Submit");
JTextField txtName = new JTextField("", 4);
btnSubmit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String name = txtName.getText();//see below for explanation
printInfo();//write the function call statements here if you want them to be executed when button is clicked
}
});
whenever button is clicked or more generally any event occurs on the button then it creates a string object in the string pool and assigns to it the value of the text field at the time when the button was clicked

Categories

Resources