I am tying to perform and action when an item in combo box are selected, but it performs an action no matter what item is selected.Can someone help me out please.
//number of players combo box
players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
players.addItem("2 Players");
players.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
makeFrame();
}
});
players.addItem("3 Players");
//end of combo box
In order to change behavior based on which item was selected, you will need to retrieve the selected value inside your ActionListener and change the behavior based on the selected value. You could use something like the following:
//number of players combo box
//notice that you have to declare players
//as final. If it is a member of the class,
//you can declare it final in the field
//declaration and initialize it in the
//constructor, or if local, just leave it
//as it is here. Unless using Java 8, then it
//doesn't need to be declared final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
//your combo box still needs to be final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
players.addItem("2 Players");
players.addItem("3 Players");
players.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String selectedValue = String.valueOf(players.getSelectedItem());
if (selectedValue != null && (selectedValue.equals("1 Player") || selectedValue.equals("2 Players"))) {
makeFrame();
}
else {
//do something else
}
}
});
//end of combo box
If you happen to know the index ahead of time (i.e., you statically initialize the list of options instead of dynamically generating the list), you could also just refer to .getSelectedIndex() to retrieve the index as follows:
//number of players combo box
//the combo box still needs to be final here
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("1 Player");
//your combo box still needs to be final
final JComboBox players = new JComboBox();
contentPane.add(players, BorderLayout.SOUTH);
players.addItem("2 Players");
players.addItem("3 Players");
players.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int myIndex = players.getSelectedIndex();
if (myIndex == 0 || myIndex == 1) {
makeFrame();
}
else {
//do something else
}
}
});
//end of combo box
Related
I am trying to change JCombobox items list (towns) depending on the value of the other JCombobox (city). When I change the value in the city list, it changes the items in the towns list. But there are 2 issues.
The updated list (towns) shows double of the items but when click on it then it shows the correct number of items as shown in the first screenshot.
The updated list doesn't allow me to choose one of the item, it only select the first item
here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Testing extends JFrame implements ActionListener {
public static void main(String[] args )
{
new Testing();
}
JComboBox cb,cb1,cb2;
JFrame f;
JLabel label1,label2;
JButton b1;
JTextField name,ID,birth;
Testing(){
f=new JFrame("Information Example");
label1 = new JLabel("Please input your information below");
label1.setBounds(10, 20, 260, 30);
f.add(label1);
String question[]={"Calculate my Age","When do I drive","When do I vote"};
String city[]={"Asimah","Ahmadi","Hawalli"};
name= new JTextField("NAME");
name.setBounds(10,50,264,25);
f.add(name);
ID= new JTextField("CIVIL ID");
ID.setBounds(10,80,264,25);
f.add(ID);
birth= new JTextField("DATE OF BIRTH");
birth.setBounds(10,110,264,25);
f.add(birth);
cb=new JComboBox(question);
cb.setBounds(50, 150,180,20);
f.add(cb);
b1= new JButton("Get");
b1.setBounds(100,250,60,20);
f.add(b1);
cb1=new JComboBox(city);
cb1.setBounds(10, 200,120,20);
f.add(cb1);
cb2=new JComboBox();
cb2.setBounds(150, 200,120,20);
f.add(cb2);
f.setLayout(null);
f.setSize(300,400);
f.setVisible(true);
cb.addActionListener(this);
cb1.addActionListener(this);
cb2.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent event)
{
if(cb1.getSelectedIndex() == 0)
{
cb2.removeAllItems();
cb2.addItem("Rawdhah");
cb2.addItem("Abdahll");
}
else if(cb1.getSelectedIndex() == 1)
{
cb2.removeAllItems();
cb2.addItem("Siddiq");
cb2.addItem("Aljabryha");
}
else
{
cb2.removeAllItems();
cb2.addItem("Fintas");
cb2.addItem("Abdahll");
}
}
}
So, basically, the combination of removeAllItems and addItem is causing the JComboBox to generate a ActionEvent, but only for the first new item added.
You should isolate your functionality to only perform certain actions based on the source of the event, for example...
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == cb1) {
if (cb1.getSelectedIndex() == 0) {
cb2.removeAllItems();
System.out.println(cb2.getItemCount());
cb2.addItem("Rawdhah");
cb2.addItem("Abdahll");
} else if (cb1.getSelectedIndex() == 1) {
cb2.removeAllItems();
cb2.addItem("Siddiq");
cb2.addItem("Aljabryha");
} else {
cb2.removeAllItems();
cb2.addItem("Fintas");
cb2.addItem("Abdahll");
}
}
}
You could also make use of the actionCommand property, but the above is the simpler, immediate solution
Would really appreciate some help.
Short version Basically I can call a method with a hardcoded string as argument, but I can't use one specific global string variable (even though I can print it and checked that it is a string, and it is recognised)
Long version:
So I'm trying to get a function to work in a basic bank application and this drives me absolutely nuts.
I have classes for the logic of the bank, customers, and accounts. It's working as intended. The problem lies in the Gui class.
I'm using JTable to show the list of customers. Each customer has a personal number that I store in a global variable. I use this variable as an argument for the methods I'm calling. For example bank.findCustomer(personalNumber).
I can print the current selected personal number each time I click on a row in the table. That works fine. I have checked that it's indeed a string. But as soon as I create a Customer object to change the name (using a method from the customer class), I can't use the global variable of the selected personal number.
It seems so strange that I can hardcode the string but I can't pass the variable string.
My guess is that the string is somehow "locked up" in a synchronous(?) event or that the even listeners are in conflict. I have tried 1000 different things to get it to work. It feels like I'm bashing my head against a the wall...
I get the null-pointer exception when trying to call customer.setName() inside the actionPerformed method. If I use it outside this method, it works?
Here is the code:
class Gui implements ActionListener {
private BankLogic bank;
private JFrame frame;
protected JTable table;
protected JMenuBar menuBar;
protected JMenu mainMenu, customerMenu, accountMenu;
protected JPopupMenu popupMenu;
protected JMenuItem addCustomerItem, removeCustomerItem, editCustomerItem, showCustomersItem,
createSavingsAccountItem, createCreditAccountItem, showAccountsItem,
removeAccountItem, depositToAccountItem;
protected JButton refreshButton;
protected DefaultTableModel defModel;
String pNumOfCustomerSelected;
protected int accNumOfAccountSelected;
private JScrollPane scroll;
private ArrayList<String> customerDataList;
protected String test = "14";
Gui() {
bank = new BankLogic();
// dummy customers
bank.createCustomer("Donald", "Duck", "12");
bank.createCustomer("Dauda", "Dabo", "14");
bank.createSavingsAccount("12");
bank.createCreditAccount("12");
// for testing
pNumOfCustomerSelected = "12";
// === MAIN MENU === //
// Item for menu
addCustomerItem = new JMenuItem("Add customer");
addCustomerItem.addActionListener(this);
// Menu to hold items
mainMenu = new JMenu("Menu");
// Menu bar to hold menu
menuBar = new JMenuBar();
// Install components
mainMenu.add(addCustomerItem);
menuBar.add(mainMenu);
// === POPUP MENU === //
// Items for popup menu
editCustomerItem = new JMenuItem("Edit customer name(s)");
editCustomerItem.addActionListener(this);
// Popup menu
popupMenu = new JPopupMenu();
// Install compeonents
popupMenu.add(editCustomerItem);
// === TABLE === //
// Model for table
defModel = new DefaultTableModel();
defModel.addColumn("First name");
defModel.addColumn("Last name");
defModel.addColumn("Personal number");
// Table
table = new JTable(defModel);
fillTable();
// Scroll feature for table
scroll = new JScrollPane(table);
// refresh button
refreshButton = new JButton("Refresh");
refreshButton.addActionListener(this);
// Install popup menu
table.setComponentPopupMenu(popupMenu);
// Install mouse listener
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent me) {
pNumOfCustomerSelected = (String) table.getValueAt(table.getSelectedRow(), 2);
System.out.println(pNumOfCustomerSelected); // works fine
}
});
// === MAIN FRAME === //
// Main frame
frame = new JFrame("Bank application");
// Layout for frame
frame.setLayout(new BorderLayout());
// Install components to frame
frame.add(scroll, BorderLayout.CENTER);
frame.add(refreshButton, BorderLayout.SOUTH);
frame.setJMenuBar(menuBar);
// Settings for main frame
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/**
* Fills the customer table with data
*/
public void fillTable(){
customerDataList = bank.getAllCustomers();
// Filling the table with rows (of customer info)
for(int i = 0; i < customerDataList.size(); i++){
String customerInfo = customerDataList.get(i);
String[] customerInfoComponents = splitString(customerInfo);
Vector row = new Vector();
row.add(customerInfoComponents[0]);
row.add(customerInfoComponents[1]);
row.add(customerInfoComponents[2]);
defModel.addRow(row);
}
}
/**
* Clears the table rows
*/
public void clearTable(){
int rowCount = defModel.getRowCount();
if(rowCount > 0) {
for (int i = 0; i < rowCount; i++) {
defModel.removeRow(0);
}
}
}
/**
*
* #param stringForProcess customer info
* #return an array of the words in the string (separated by " ")
*/
String[] splitString(String stringForProcess){
return stringForProcess.split("\\s+");
}
// action listener
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == addCustomerItem)
new AddCustomerWindow(bank, "Add customer");
else if(e.getSource() == refreshButton){
clearTable();
fillTable();
}
else if(e.getSource() == editCustomerItem){
Customer cust = bank.findCustomer(pNumOfCustomerSelected);
// Customer customer = bank.findCustomer("12"); // This works fine???
customer.setName("name"); // nullpointer
customer.setSurName("surname");
}
}
}
I was wondering in someone could point me in the right direction for this. I have this simple calculator, where the user enters two numbers and then has to select an action (+, -, *, *) from a drop down menu.
After they select an option, it gives them an answer, but I was trying to add a check box to allow the result to be displayed as a float if the box was checked. I was confused on how to have the actionPreformed handle both the JCheckBox and the JComboBox. I tried just adding newCheckBox, but that causes casting errors, between JCheckBox and JComboBox.
public class Calculator2 implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JPanel xpanel;
String[] mathStrings = { "Multiply", "Subtraction", "Division", "Addition"}; //Options for drop down menu
JComboBox mathList = new JComboBox(mathStrings); //Create drop down menu and fill it
public Calculator2() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("Result:"));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
JPanel southPanel = new JPanel(); //New panel for the drop down menu
southPanel.setBorder(BorderFactory.createEtchedBorder());
JCheckBox newCheckBox = new JCheckBox("Show My Answer In Floating Point Format"); //Check box to allow user to view answer in floating point
southPanel.add(newCheckBox);
//newCheckBox.addActionListener(this);
southPanel.add(mathList);
mathList.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Font thisFont = result.getFont(); //Get current font
result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD)); //Make the result bold
result.setForeground(Color.red); //Male the result answer red in color
result.setBackground(Color.yellow); //Make result background yellow
result.setOpaque(true);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent event) {
String xText = xfield.getText(); //Get the JLabel fiels and set them to strings
String yText = yfield.getText();
int xVal;
int yVal;
try {
xVal = Integer.parseInt(xText); //Set global var xVal to incoming string
yVal = Integer.parseInt(yText); //Set global var yVal to incoming string
}
catch (NumberFormatException e) { //xVal or yVal werent valid integers, print message and don't continue
result.setText("ERROR");
//clear();
return ;
}
JComboBox comboSource = (JComboBox)event.getSource(); //Get the item picked from the drop down menu
String selectedItem = (String)comboSource.getSelectedItem();
if(selectedItem.equalsIgnoreCase("Multiply")) { //multiply selected
result.setText(Integer.toString(xVal*yVal));
}
else if(selectedItem.equalsIgnoreCase("Division")) { //division selected
if(yVal == 0) { //Is the yVal (bottom number) 0?
result.setForeground(Color.red); //Yes it is, print message
result.setText("CAN'T DIVIDE BY ZERO!");
//clear();
}
else
result.setText(Integer.toString(xVal/yVal)); //No it's not, do the math
}
else if(selectedItem.equalsIgnoreCase("Subtraction")) { //subtraction selected
result.setText(Integer.toString(xVal-yVal));
}
else if(selectedItem.equalsIgnoreCase("Addition")) { //addition selected
result.setText(Integer.toString(xVal+yVal));
}
}
}
What I would recommend is that you keep a reference to the JCheckBox in the Calculator2 class. So something along the lines of
public class Calculator implements ActionListener {
...
JComboBox mathList = ...
JCheckBox useFloatCheckBox = ...
...
}
then in your actionPerformed mehtod, instead of getting the reference to the widget from event.getSource() get it directly from the reference in the class. So actionPerformed would look like this
public void actionPerformed(ActionEvent e) {
String operator = (String)this.mathList.getSelected();
boolean useFloat = this.useFloatCheckBox.isSelected();
...
}
This way you can use the same listener on both objects without having to worry about casting the widget.
The casting errors are because event.getSource() changes depending on which object fired the event. You can check the source of the event and process based on that:
if (event.getSource() instanceof JCheckBox) { ... act accordingly ... } else
Instead you could add a different ActionListener implementation to the JCheckBox so that the event it creates goes to a different place. An anonymous listener that sets a flag or calls a different method would work too.
There are other ways you could approach the problem, do you want the checkbox to affect an existing calculation, or only a new one? If only a new calculation you don't need an action listener on the checkbox, you can find out whether it is checked when you do the calculation:
if (myCheckbox.isSelected()) {
// do float calculation...
} else {
// do int calculation
}
I have a table and at each row i have a combox of operator from which we can choose any operator and value1 field value 2 field. COMBO BOX DEFAULT OPERATOR IS " EQUAL TO".so my question is when u click on combobox in any row i should get the value of the selected row and get the operator which i am selecting such that i can perform some operation based on selected operator....
Or else if i change the combobox operator from in between to equal to i should get clear the value 2 field....
Help me get out of this..
You should have an event to know item in the combo is clicked.
Like this:
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
//doSomething();
}
});
You have three methods to get current item selected:
Will get the index of the item is order number.
int selectedIndex = myComboBox.getSelectedIndex();
-or-
Will get item selected with Object. You can do many method contains in this Object.
Object selectedObject = myComboBox.getSelectedValue();
-or-
Will get real values of item selected with string type.
String selectedValue = myComboBox.getSelectedValue().toString();
You can see full example code at here (from #secario member):
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}
I want to make a JComboBox in which a particular item text should change and becomes editable on selection.For example if JComboBox has two items "ONE","TWO" in it's list then on Selection of "TWO".
I have wrote a sample program in which either i can make field editable or can change the Text but not both.So someone please suggest how to make selective item editable and changed text as well
Object[] items = new Object[]{"One","Two"};
DefaultComboBoxModel dcbm = new DefaultComboBoxModel(items);
final JComboBox comboBox = new JComboBox(dcbm);
comboBox.setPreferredSize(new Dimension(200, 20));
comboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
Object selectedItem = comboBox.getSelectedItem();
boolean editable = selectedItem instanceof String && ((String)selectedItem).equals("Two");
comboBox.setEditable(editable);
//comboBox.setSelectedItem("text has changed");
}
});
Something like...
String[] data = {"One", "Two"};
JComboBox<String> cb = new JComboBox<>(data);
add(cb);
cb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cb.setEditable(cb.getSelectedIndex() != 0);
}
});
will basically do it, but what it won't do, is update the value of the model, just so you know ;)
If you want to make the editor "blank" when the combobox becomes editable, you could add...
if (cb.isEditable() && cb.getSelectedIndex() != -1) {
cb.setSelectedItem("");
}
to the ActionListener
So I'm not the best with jComboBox off the top of my head so this may not help but I would assume it uses an array to set the strings for the objects in the combo box along the lines of
(new String[] {"ONE","TWO"});
and with my understanding of arrays you could do something like
comboBox.addMouseListener(new MouseAdapter(){
public void ActionPerformed(MouseEvent click){
optionTwoClicked(click);
}
}
and then add the handler with something like
private void optionTwoClicked(MouseEvent click){
if (click.getSelectedItem()=String[2]){
String onTwo = JOptionPane.showInputDialog(null,"Enter your message","Messages",2);
textItem.setText()="onTwo";
}else{ //do something here?
}
}
Like I said before, not absolutely familiar with jComboBox, but,
Hope that helps!