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.
Related
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]);
}
I am really new in Java, and just practising ActionListeners. As the part of the application I work on, I will have a JTextField that lets the user to search a name, and then a JTextArea to show the result of the search. I have a api for searching and fining the the names, only problem is to connect the widgets to the methods and action listener file.
Here is some parts of the code:
Widget File:
//Text Field
JTextField searchbox = new JTextField();
leftSide.add(searchbox, cnt);
String userText = searchbox.getText();
ActionListener sendsText = new SearchListener(search box);
searchbox.addActionListener(sendsText);
//TextArea
JTextArea stationList = new JTextArea(12, 0);
leftSide.add(stationList, cnt);
String entered = userText;
stationList.append(entered);
SearchListener:
public class SearchListener implements ActionListener {
private JTextField searchbox;
private JTextArea stationList;
public SearchListener(JTextField search box) {
this.searchbox = searchbox;
}
public void ListF(JTextArea stationList){
this.stationList = stationList;
public void actionPerformed(ActionEvent event) {
XXXX<NAMES> stations = HHHH.SimilarNames(searchbox.getText());
for (NAMES station : stations) {
//System.out.println(station);
*Problem*> String result = (searchbox.getText());
*Problem*> stationList.append(result);
}
So in this program, the TextFiels is connected and the ActionListener working, but it prints out the list on Similar names in the CMD, (I commented it here). But I want it to send the list back to the Text Area in the API.(Widget File). So I am not sure my ActionListener method at the top of the SearchListener is right. Also the Problem> in the code is where I tired to pass the search result to the text field, which doesnt work.
So anyone know how to fix it?
Thank is advance.
I think you may be twisting a few things around, but perhaps this is what you're trying to accomplish:
A search field who's value determines what the text area is populated with.
If this is the case, then a few things have to change. First, only code within the ActionListener will be axecuted upon UI events, so there is no reason to call getText() on any of the UI elements during initialization.
Second, adding a button to this UI greatly simplifies the logic here. If attaching the listener to the search box, issues begin to arise such as "when do I know the user is done entering text?" and "How do I handle partial text?", however using a "Search" button puts this logic in the hands of a user.
Once the "Search" button is clicked, the action event from the listener that is attached to the button will trigger, and the stationListArea will be populated with the results of similarNames(<text from search box>).
Note that though what is shown below is not the cleanest way to perform this task (which would involve fields and anonymous inner classes), it is straightforward and easy to understand.
Widget (not sure what cnt was, so I omitted in in sample code below)
//Create the search text box
JTextField searchBox = new JTextField();
leftSide.add(searchBox);
// Create a button that will serve as the "Action" for the search box
JButton searchButton = new JButton("Search");
lefSide.add(searchButton);
// Create the station-list text area that will display text
// based on results from the search box
JTextArea stationListArea = new JTextArea(12, 0);
leftSide.add(stationListArea);
// Create a listener that listens to the Button, then performs an
// action from the search box to the text area
ActionListener searchButtonListener = new SearchListener(searchBox, stationListArea);
searchButton.addActionListener(searchButtonListener);
SearchListener
NOTE: Logic here will continue adding text into your stationListArea every time the button is clicked and HHHH.SimilarNames() returns a value. To have the stationListArea just update with the new text every time, replacing the old, add a stationListArea.setText("") at the beginning of actionPerformed().
public class SearchListener implements ActionListener {
private JTextField searchBox;
private JTextArea stationListArea;
public SearchListener(JTextField searchBox, JTextArea stationListArea) {
this.searchBox = searchBox;
this.stationListArea = stationListArea;
}
public void actionPerformed(ActionEvent event) {
XXXX<NAMES> stations = HHHH.SimilarNames(searchBox.getText());
for (NAMES station : stations) {
stationListArea.append(station);
}
}
}
Updated based on feedback in main comments
Your NAMES object needs some way to provide a String representation of itself. This way, you can then append that value to your text area..
public class SearchListener implements ActionListener {
private JTextField searchbox;
private JTextArea stationList;
public SearchListener(JTextField search box) {
this.searchbox = searchbox;
}
public void actionPerformed(ActionEvent event) {
XXXX<NAMES> stations = HHHH.SimilarNames(searchbox.getText());
for (NAMES station : stations) {
stationList.append(station.getLocationName()());
}
}
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
}
}
I'd like to add to a database, and my editable comboBoxModel when I enter a new name into the comboBox. I have the method for adding to the database down fine, I'm just trying to get it to somehow listen to an entry being added to the ComboBox.
What's the Best way to do this?
I've read the Java tutorial on Editable ComboBoxes, and noted where it said:
An editable combo box fires an action event when the user chooses an item from the menu and when the user types Enter. Note that the menu remains unchanged when the user enters a value into the combo box. If you want, you can easily write an action listener that adds a new item to the combo box's menu each time the user types in a unique value.
So I thought to myself, ok lets try this, and looked up some examples. Here is my attempt, essentially copy pasted out of the example I found, with my variable names:
playerNameComboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxEdited")) {
System.out.println("Adding new player!");
IController.Util.getInstance().addNewPlayer();
playerNameComboBox.insertItemAt(playerNameComboBox.getSelectedItem(), 0);
}
}
});
When I type in a new name, and press enter, it does nothing. No new database entry and no addtional option on the ComboBox. I haven't attached an action command to the ComboBox as I thought the example above assumed it would have that as default, and so did I.
But how do I get it to shout out that action command when I press enter, with the focus on the comboBox? I would have thought that comboBoxes would have had some sort of default behaviour to shout that out? Do I need to use an if(playerNameComboBox.hasFocus()) statement? Should I implement some kind of keylistener when my comboBox hasFocus()?
I'm very new at Java, so I'm unsure as to how this sort of thing should be done; any help is very much appreciated.
As requested, here is my short example in which names may be added to a JComboBox.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Test extends JFrame {
private JComboBox box;
public static void main(String[] args) {
new Test();
}
public Test()
{
super();
setSize(200, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
box = new JComboBox();
box.setEditable(true);
getContentPane().add(box);
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxEdited")) {
System.out.println("Adding new player!");
box.insertItemAt(box.getSelectedItem(), 0);
}
}
});
setVisible(true);
}
}
I'm quite new to Java Swing. And I'm stuck on trying to add a ListSelectionListener on a JComboBox instance. It seems only the ListSelectionModel interface has addListSelectionListener method. I kind of cannot figure it out...
Why I want to do add it is that I want program do something even the item in the combo box is not changes after selecting.
POTENTIAL ANSWER
I was simply thinking of attaching an actionListener on combobox not working. and i think it's bug of openjdk. I've reported it here
Thanks in advance.
Take a look at JComboBox#addItemListener:
JComboBox combo = createCombo();
combo.addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
Object selectedItem = e.getItem();
// Do something with the selected item...
}
}
});
This event is fired for both mouse and keyboard interaction.
For JComboBox, you'll have to use ActionListener.
JComboBox jComboBox = new JComboBox();
jComboBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("combobox event");
}
});
AFAIK, actionPerformed is raised whenever the user makes a selection for the JComboBox even if it's the same item that was already selected.
It depends on your requirement. The ActionEvent is only fired when the keyboard is used, not when the selection changes as the mouse is moved over the items.
If you want to do some action when the item selection changes even if the mouse is moved then yes you will probably need access to the JList. You can access the JList used by the popup with the following code:
JComboBox comboBox = new JComboBox(...);
BasicComboPopup popup = (BasicComboPopup)comboBox.getAccessibleContext().getAccessibleChild(0);
JList list = popup.getList();
list.addListSelectionListener(...);
Use a PopupMenuListener. When the popup menu closes get the selected index and do your processing.