ActionEvent for jButton given a jRadioButton option - java

So basically, I'm trying to make a simple program here with GUI that let's you make a choice given two jRadioButtons as choices of which either of the two leads to a corresponding storyline in similar fashion to visual novels. The problem however is that I'm having trouble connecting the idea of a jButton to a choice from a jRadioButton.
The concept is like this: In a frame, there's a jTextArea which displays strings of texts forming a storyline which gives two options to choose from here and there as represented by two jRadioButtons which then must be executed by a jButton.
So far, the only logic I've placed inside the ActionListener for both jRadioButtons is having to disable the other once a jRadioButton is clicked while the jButton is intentionally blank. Anyone got any similar program or module he / she would like to share, at least, the logic on this one programatically speaking?

We usually use RadioButtons to choose between one of a few options and only one button can be selected at a time. To get this functionality, you need to add your buttons to a javax.swing.ButtonGroup . Here is a quick example:
//Fields declared in your main GUI class
JRadioButton option1,option2;
JButton goButton; //executes the "Story"
//Constructor code or place in init() method that constructor calls:
{
//initialize buttons and place them in your frame.
ButtonGroup buttonGroup = new javax.swing.ButtonGroup();
buttonGroup.add(option1);
buttonGroup.add(option2);
buttonGroup1.setSelected(option1.getModel(), true);
goButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
goButtonActionPerformed(evt);
}
});
}
private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(option1.isSelected()) {
//place text in your text area
}
if(option2.isSelected()) {
//place different text in your text area
}
}

Related

Java: Creating multiple (duplicate) buttons that perform the same action but to themselves

BACKGROUND INFO: I want to make a 9x9 grid of buttons that act as empty beds. All buttons say "Add bed" and when clicked open up a window to write data about the occupant. Once saved the button will change to an occupied bed image.
QUESTION: Is it possible to create an event listener that does the same thing for each button, but applies it to the button being pressed? Im new to java but I understand that good code should be able to do this in a few lines rather than 100+
CODE:
//button1 (inside the gui function)
addBed1 = new JButton("Add bed"); //button 1 of 9
addBed1.addActionListener(new room1Listener());
class room1Listener implements ActionListener{
public void actionPerformed(ActionEvent event){
addBed1.setText("Adding bed..);
addBedGui(); //Generic window for adding bed info.
}
}
Is it possible to create an event listener that does the same thing for each button, but applies it to the button being pressed? Im new to java but I understand that good code should be able to do this in a few lines rather than 100+
Absolutely. In fact you can create one ActionListener object and add this same listener to each and every button in a for loop. The ActionListener will be able to get a reference to the button that pressed it via the ActionEvent#getSource() method, or you can get the JButton's actionCommand String (usually its text) via the ActionEvent#getActionCommand() method.
e.g.,
// RoomListener, not roomListener
class RoomListener implements ActionListener{
public void actionPerformed(ActionEvent event){
AbstractButton btn = (AbstractButton) event.getSource();
btn.setText("Adding bed..);
addBedGui(); //Generic window for adding bed info.
}
}
and
RoomListener roomListener = new RoomListener();
JButton[] addButtons = new JButton[ADD_BUTTON_COUNT];
for (int i = 0; i < addButtons.length; i++) {
addButtons[i] = new JButton(" Add Bed "); // make text big
addButtons[i].addActionListener(roomListener);
addBedPanel.add(addButtons[i]);
}

Issue with button icons, Java 8-Queens puzzle

The problem I am running into is this: I have a grid of buttons in a JPanel, these buttons are supposed to change to an image of a queen when I click them. The code looks like this:
private Component createButtonBlack() {
final JButton button = new BoardButton();
final ImageIcon queen = new ImageIcon("/images/queen.png");
button.setBackground(Color.BLACK);
button.setPreferredSize(new Dimension(40, 40));
class QueenClick implements ActionListener {
public void actionPerformed(ActionEvent event) {
button.setIcon(queen);
button.repaint();
}
} // end QueenClick
ActionListener queenClicker = new QueenClick();
button.addActionListener(queenClicker);
return button;
} // end createButtonBlack
The problem (image not appearing) occurs on both the methods for creating black and white buttons but the methods are the same except for the color. Ideally I would like to be able to un-click the buttons and the image disappears but I do not know how to do that.
I am having difficulty with other parts of my 8queens GUI based problem so if you have any suggestions let me know!
Also if you need more code I will certainly supply it. Thank you.
State the exact problem when asking a question.
These buttons are supposed to change to an image of a queen when I click them.
So I'm guessing the icon doesn't change?
Did you:
Verify the ActionListener code is executed?
Verify the Icon was read properly?
You can easily add a System.out.println(...) to verify both of the above.
final ImageIcon queen = new ImageIcon("/images/queen.png");
I'm guessing the problem is the leading "/" in the path. The "/" tells the file system to look at the root of the drive.
if you have any suggestions let me know!
There is no need to create two methods. You can just do:
Component button = createButton();
button.setBackground( Color.BLACK );
There is no need to create individual ActionListeners. You can create a single generic listener with code like:
ActionListener queenClicker = new ActionListener()
{
#Override
public void actionPerformed(Action Event e)
{
JButton button = (JButton)e.getSource();
button.setIcon( queen );
//button.repaint(); // not needed the setIcon method will do the repaint()
}
}

Using JButtons as Tabs

Could I use JButtons as tabs? Since the JTabbedPane cannot hold the same component in multiple tabs, would there be a way for a JButton to be a tab? I know it looks like tiDE(Website) uses the JButtons as a tab. How would I do that?
I could make something like this
JButton newTab = new JButton("New Tab");
newTab.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JButton tab = new JButton("Tab 1");
JToolBar.add(tab)
tab.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
makeTextAreaTab();
}
}
);
}
}
);
But, how would I make the method makeTextAreaTab()? It would have to be the same component as my other editor(JTextArea), and have the same functionality as a JTabbedPane.
You state in a comment:
I would like to be able to have buttons serve the functionality of tabs. Click on one button, it moves to one editor. Click on another button, it moves to another editor.
Consider using a CardLayout for this where your JButtons (or perhaps better, a JComboBox) tells the CardLayout-using container which "card" (which component -- here a JScrollPane/JTextArea combination) to display.

Multiple JComboBox Event Handling in Same Class

I have two JComboBox and one button. I am trying to do that if I select an item from the two combo box individually and press the button called search. Then the two selected items from the two combo box will save in a new two separate string.
Please anyone help me to solve the problem.
Here is the code snippet
//here is the strings that in the combo box
String lc[] = {"Kolabagan-Dhaka", "Gabtoli-Dhaka", "Fakirapul-Dhaka", "Shaymoli-Dhaka"};
String rc[] = {"Banani-Bogra", "Rangpur","Shatrasta-Bogra"};
//here is my two jcombo box
JComboBox lcCombo = new JComboBox(lc);
JComboBox rcCombo = new JComboBox(rc);
// here is my search button
JButton searchButton = new JButton("Search");
There are two ways to go about this. The first is to have one class that implements ActionListener and in the implementation, check the source (ActionEvent.getSource()). Based on which component sourced the event, you take the appropriate action.
The other option (and my preference) is to create an ActionListener for each component that requires one. You can use anonymous classes if you don't want to explicitly define one for each case. This way each listener knows exactly what component caused the event and what action to take.
Example:
JComboBox lcCombo = new JComboBox(lc);
lcCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do left stuff
}
});
JComboBox rcCombo = new JComboBox(rc);
rcCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do right stuff
}
});
To expand on unholysampler, once you have the ActionListener working you can use lcCombo.getSelectedIndex() to check which item has been selected.

performing multiple actions on one button in java swing

I am trying to create a wizard in java swing programatically.
On the wizard pane I have a next button and it has to perform multiple actions according to which panel is displayed on the wizard.
Is it possible to use java command pattern? may I know how?
thanks in advance.
the code i used for the wizard is
this.mainPanel.add(fileSelectionPane,"SELECT FILE");
this.mainPanel.add(sqlConnectionPane,"SQL CONNECTION");
this.mainPanel.add(devicePane,"PARSER");
this.mainPanel.add(detailsPane,"DISPLAY");
thisLayout.show(this.mainPanel,"SELECT FILE");
this.finishButton.setEnabled(false);
this.backButton.setEnabled(false);
if(newValue==1) {
this.thisLayout.show(this.mainPanel, "SQL CONNECTION");
this.nextButton.setEnabled(true);
this.nextButton.setText("Connect..");
this.cancelButton.setEnabled(true);
this.backButton.setEnabled(true);
}
if(newValue==2) {
this.thisLayout.show(this.mainPanel, "PARSER");
this.nextButton.setEnabled(true);
this.nextButton.setText("Parse..");
this.cancelButton.setEnabled(true);
this.backButton.setEnabled(true);
}
i want the next button to perform specific actions on SELECT FILE and SQL CONNECTION.
is it possible to use command patterns?
Ok, so, You add action listeners to buttons. These action listeners do something when an event occurs.
You want to change the functionality of the button depending on which panel is being displayed? Why not set a instance variable which reflects the state of the Wizard?
For example (roughly),
int state = 0; // home panel
change panel to help page, event listener is fire, set 'state' to 1. You are now tracking which panel is being displayed.
Now, in your original problem, when the button (the one you want multiple functionality with) fires, you can choose the action it will take based on the 'state' var.
have look at CardLayout
those cards put to the JDialog (JDialog has preimplemented by default BorderLayout) to the CENTER area
create a new JPanel and place there JButtons
JPanel with JButtons put to the SOUTH area
search here, on this forum, there are a few excelent examples for wizard or image previue based on CardLayout
try the following code for button:
JButton btn1;
btn1= new javax.swing.JButton();
btn1.setToolTipText("Submit");
btn1.setContentAreaFilled(false);
btn1.setBorderPainted(false);
btn1.setMargin(new java.awt.Insets(2, 2, 2, 2));
btn1.addActionListener(this);
btn1.setIcon(this.getIcons()[21]);
add(btn1); // add to Jpanel
btn1.setBounds(250,10, 12, 12);
public void actionPerformed(java.awt.event.ActionEvent evt) {
Object obj = evt.getSource();
if (obj == btn1) {
// your function on on click of button
return;
}

Categories