Add action to dynamically created button in JDialog - java

I have created and added added a button to JDialog as follows:
JDialog dialog = new JDialog();
dialog.setLayout(new GridLayout(6, 1));
dialog.add(new JButton("test"));
This adds the button JDialog. But is there anyway I could add ActionListener to it?
I know this is possible if I create a whole new button itself like:
JButton button = new JButton("test");
button.addActionListener....
dialog.add(button);
But I am wondering if I can do without this.
So far I reached to the point dialog.getRootPane().getContentPane().getComponent(1) but stuck here with no idea on a way to implement an actionListener. Any help would be appreciated.

I don't think there is a way to add listeners while initializing the JButton.
Initializing the button and adding the listener will do as you said.
The other way, you can have an utility method to create a JButton with listeners as below.
dialog.add(getButton("Test", new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// Action Logic
}
}));
private JButton getButton(String name, ActionListener listener) {
JButton button = new JButton(name);
button.addActionListener(listener);
return button;
}

Related

Have a Button Group in Java where all buttons can be deselected?

I want to have a Button Group in which either only one option is selected or none of them are. At the moment, I can get it to have no options ticked by default, and then if one of them is ticked only one of them can be ticked, but I also want to be able to untick the button that was selected. Is this possible?
EDIT: Ideally without having a clear all button, as it would ruin the symmetry of my GUI. Also, here is my code thus far:
ButtonGroup option = new ButtonGroup();
for(int i = 0; i < n; i++) {
JCheckBox check = new JCheckBox("", false);
option.add(check);
row3b.add(check);
}
Just use the clearSelection() method of ButtonGroup :
ButtonGroup.clearSelection()
Clears the selection such that none of the buttons in the ButtonGroup
are selected.
This snippet demonstrates how you can clear selections using ButtonGroup.clearSelection():
//The buttons
JFrame frame = new JFrame("Button test");
JPanel panel = new JPanel();
JRadioButton btn1 = new JRadioButton("Button1");
JRadioButton btn2 = new JRadioButton("Button2");
JButton clearbutton = new JButton("Clear");
panel.add(btn1);
panel.add(btn2);
panel.add(clearbutton);
frame.add(panel);
frame.setVisible(true);
frame.pack();
//The Group, make sure only one button is selected at a time in the group
ButtonGroup btngroup = new ButtonGroup();
btngroup.add(btn1);
btngroup.add(btn2);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do whatever you want here
}
});
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do whatever you want here
}
});
clearbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Clear all selections
btngroup.clearSelection();
}
});
As you can see, this creates two JRadioButtons and adds them to group then makes a button that clears selections. Really simple. Or you could create your own radio button class that allows for the unchecking of the button, which is also doable relatively easily.

How to run method in the JFrame by clicking button in JDialog?

I have a JFrame (called FTask) with public void method. Example code:
public void clear() {
jTable1.clearSelection();
jButton1.setEnabled(false);
jButton3.setEnabled(false);
jButton2.setEnabled(false);
jTextArea1.setText(null);
}
Then, I have JDialog with a button. I want when I click the button, frame do the 'clear' method to the frame.
I've tried:
FTask ft = new FTask();
ft.clear();
But it didn't work.
I've tried:
FTask ft = new FTask();
ft.clear();
But it didn't work.
No, it wouldn't. This code is creating a new (2nd instance) of the frame that is not set visible. What you need is a reference to the original frame.
This can be fixed in a number of ways, too broad to go into here, and is Object Oriented Programming 101 that should be mastered before trying to write GUI'd apps. - which add their own complications.
You have to use actionlistener in order to run the code when the button is clicked.
JButton button = new JButton("Click me");
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
if(e.getSource() == button){
System.out.println("You clicked the button");
//In your case:
ft.clear();
}
}
});
As #Menno said, you have to use ActionListener in order to detect Button Clicks
Here is the Java 8 Style:
JButton button = new JButton("Click me");
//Add action listener to button
button.addActionListener(
ae -> ft.clear();
);
// Add button to frame
add(button);

Add object for every user input

I am trying to create a new button every time the user presses a button.
So, if I click "add" button, then a new panel/button/thing would be added to the JPanel.
Not sure if this is the same thing I'm asking for
Don't know what
guiButtons[0]
is in
if(buttonClick.getSource().equals(guiButtons[0]))
Would be nice if someone could explain
You can try as bellow code, may it help you
JPanel panel = new JPanel(new FlowLayout());
JButton button = new JButton("Add");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton newButton = new JButton("New Added Bnt");
panel.add(newButton);
}
});

How to open a JDialog

I am creating an application that has 1 JFrame java file and 1 JDialog java file.
In the JFrame, I have a button and when pressed I want it to display what I have designed in the JDialog.
So for example, my JFrame java file is called MMainView.java and my JDialog is called OptionView.java. So when the button in MMainView.java is pressed I want to display the JDialog I have designed in OptionView.java.
So in my MMainView.java file, I have a function that is called when that button is pressed. How do I display the dialog in OptionView.java?
SOLVED
For those wondering. This is what I did:
private JDialog optionView; ~~> JDialog Declaration
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (optionView == null) {
JFrame mainFrame = myApp.getApplication().getMainFrame();
optionView = new OptionView(mainFrame, true);
optionView.setLocationRelativeTo(mainFrame);
}
myApp.getApplication().show(optionView);
}
Sounds like you want to create an ActionListener for your button, and set the visibility of the JDialog to true when you press the button.
Something on these lines:
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionevent)
{
//set the visibility of the JDialog to true in here
}
});
Let's say your button is called myBtn.
The class should look like this.
public class MMainView extends JFrame
implements ActionListener
You should use a listener for the button.
JButton myBtn = new JButton();
myBtn.addActionListener(this);
And finally:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myBtn) {
new OptionView();
You don't really need the if, it's just in case you want to add more buttons for the actionPerformed.
First register the button in "MainView.java", like below.
b1.addActionListener(this);
b1.setName("OpenJDialog");
//this is to read in actionperformed method incase you have more than one button
// in action performed method call the dialogue class
public void actionPerformed(ActionEvent ae){
JButton jb = (JButton)ae.getSource();
String str = jb.getName();
if(str.equals("OpenJDialog"){
new OptionView();
//I am assuming u are configuring jdialog content in OptionView constructor
}
}

Manipulating buttons in different Jpanel

I have a various panels with various buttons. Some buttons should call a method initiating a search through an array list, other buttons should call methods that send information to different JTextArea boxes.
After adding an event listener for each button, how do I create specific actions depending on the button clicked in my actionPerformed method? Below is my code for various gui properties, as you can see there are 3 different JPanels, the buttons of each needing to perform different functions. I just need to know how to determine which button was clicked so I can link it to the appropriate method (already written in another class). Does this require an if statement? Can my other class access the buttons on the GUI if I make them public, or is there a more efficient way to do this.
JPanel foodOptions;
JButton[] button= new JButton[4]; //buttons to send selected object to info panel
static JComboBox[] box= new JComboBox[4];
JPanel search;
JLabel searchL ;
JTextField foodSearch;
JButton startSearch; //button to initialize search for typed food name
JTextArea searchInfo;
JPanel foodProfile;
JLabel foodLabel;
JTextArea foodInfo;
JButton addFood; //but to add food to consumed calories list
JPanel currentStatus;
JLabel foodsEaten;
JComboBox foodsToday;
JLabel calories;
JTextArea totalKCal;
JButton clearInfo; //button to clear food history
As per people's comments, you need to use listeners of some sort, here is a real basic example to get you started, however I would define your listeners elsewhere in most cases, rather than on the fly:
JButton startSearch = new JButton("startSearch");
JButton addFood = new JButton("addFood");
startSearch.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//DO SEARCH RELATED THINGS
}
});
addFood.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//DO FOOD ADD RELATED THINGS
}
});
Something like this:
JButton searchButton = new JButton("Start search");
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do some search here
}
});
JButton addFoodButton= new JButton("Add food");
addFoodButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// add your food
}
});
and so on. If you need to reuse an behaviour through multiple buttons, create a ActionListener instance instead of using anonymous classes and assign it multiple times to your buttons.
Well there any many ways to do that I guess. I suppose you can do the following:
public class Myclass implements ActionListener
{
private JButton b1,b2;
private MyClassWithMethods m = new MyClassWithMethods();
// now for example b1
b1 = new JButton("some action");
b1.setActionCommand("action1");
b1.addActionListener(this);
public void actionPerformed(ActionEvent e) {
if ("action1".equals(e.getActionCommand()))
{
m.callMethod1();
} else {
// handle other actions here
}
}
}
And you can do the same for more buttons and test which action triggered the event and then call the appropriate methods from you class.

Categories

Resources