i am very new to java.I am developing a inventory management system where i want to add the data to the jtable when "ENTER" key is pressed.but i don't know how to do so.i have searched about key bindings but got nothing helpful for me at that initial stage.here is my action that i want to perform at key pressed..
private void addItemActionPerformed(java.awt.event.ActionEvent evt) {
int quantity,price;
Product p=new Product();
String[] result=new String[8];
String data[]=new String[6];
int i=0;
result=p.getInfo(this.addItemField.getText());
for(String s:result){
data[i]=s;
i+=1;
}
data[0]="1";
quantity=Integer.parseInt(data[0]);
price=Integer.parseInt(data[5]);
int tPrice=price*quantity;
data[5]=Integer.toString(tPrice);
System.out.println(quantity+" "+price);
table.addRow(data);
this.addItemField.grabFocus();
}
and here is my default constructor
public SellWindow() {
initComponents();
String title[]={"Qty","Code","Name","Unit Value","ml/kg","Line Total","Action"};
entry.getColumnModel().getColumn(0).setPreferredWidth(20);
table.setColumnIdentifiers(title);
this.entry.setModel(table);
}
i mean the action is executed when i clicked the button(Add item).i want it to be executed also when i pressed the ENTER in keyboard
You can make a button on the dialog the default button. It will be invoked when the Enter key is pressed. See Enter Key and Button for a solution.
If the data to be added is being entered in a JTextField, an actionEvent should be fired when you press enter.
inputField.addActionListener(listener);
Where listener is the container for your actionPerformed method.
But otherwise go with Nizil's suggestion and use KetListener.
Related
I have the following code to set up a Button in JavaFX 8:
Button button = new Button("target name");
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Button pressed = (Button)event.getSource();
// next target name is the title of the button
handleClick(pressed.getText());
}
});
I would like to pass some information to the handleClick() routine. In this case I have a String that is a "target name" and handleClick() is a method that knows what to do with that. Right now I'm passing that information by making it the name of the Button. Is there a better way? For instance, what if I wanted to pass two pieces of information? Or, what if the info I want to pass is not a String?
The handle() routine only accepts an ActionEvent parameter. I can't find anything in ActionEvent that would help me here.
One idea I had: Maybe I could write my own SmartButton subclass that extends Button, and include in that subclass some additional info that is passed in at the time the SmartButton is constructed (so in the subclass I would only implement an extra constructor and one or more new getters/setters). The handleClick() routine would then have access to that information via getters called on (SmartButton)event.getSource().
This seems like a common UI programming issue. What is the best practice?
Thanks.
In the code snippet you posted, the event handler is only associated with the button created in the first line. Furthermore, since it's an anonymous inner class you know you only have the one instance of that class, and consequently that event handler cannot be associated with any other control. So your code is completely equivalent to
Button button = new Button("target name");
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
handleClick(button.getText());
}
});
or, using lambda expressions:
Button button = new Button("target name");
button.setOnAction(event -> handleClick(button.getText()));
You can basically always do this, even if the data needed to handle the button press is not the text in the button. Consider a calculator app (restrict it to integers for simplicity). You would likely have some variable storing the current value displayed:
private int value ;
and then you want a bunch of numeric buttons which "append" their own value to the current value (so if the current value is 1 and you press "2", the current value should be 12, etc):
You would just need
for (int i = 0 ; i <= 9 ; i++) {
Button button = createButton(i);
// place button in UI...
}
with
private Button createButton(int buttonValue) {
Button button = new Button(Integer.toString(buttonValue));
button.setOnAction(e -> value = value * 10 + buttonValue);
return button ;
}
Some variation on this idea will always give you what you need.
My task is to enable removing Jlist selected elements when alt is pressed and jlist is clicked. I did this by adding mouse listener to my jlist:
list.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
java.util.List selectedItems = list.getSelectedValuesList();
if (e.isAltDown()){
for (Object o : selectedItems){
cm.removeElement(o); //cm is my custom model
}
}
}
});
My issue is that when there are two elements selected and I click the list with alt pressed only nearest element gets selected and is removed then. I have no clue how to remove several elements with this input combination.
The problem is that the mouse click clears all the previous selections and then selects the row you just clicked on. So therefore only that row is deleted.
So instead you should be handling a "right mouse" click and then use the right mouse button only for the deletion of the item.
if (e.isAltDown() && SwingUtilities.isRightMouseButton(e)) {
Or if you really want to do this on a left mouse click then you would probably need to use a ListSelectionListener. Every time the selection changes you would need to use the getSelectedValuesList() method and save the List returned from the method. Then in the MouseListener you would access the saved List instead of getting the currently selected List of items.
I don't like this approach because the logic is now contained in two separate listeners. Although I guess you could create a class that implement both the selection listener and the mouse listener.
This is not a perfect answer. But it solves the issue.
I just tried to see how the selection event works. When he selection happens an Mouse pressed event is triggered and then the Selection happens. So the MouseListeners which are already added to the component are responsible to make the selection. Removing the MouseListeners which are already in place would prevent the selection happen using mouse. So i did this.
MouseListener[] adapters = list.getMouseListeners();
for (int i = 0; i < adapters.length; i++) {
list.removeMouseListener(adapters[i]);
}
Now user will not be able to do the selection using mouse but he will be make the selection using keyboard. So the below would work.
list.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
java.util.List selectedItems = list.getSelectedValuesList();
if (e.isAltDown()){
for (Object o : selectedItems){
model.removeElement(o); //cm is my custom model
}
}
}
});
I think the answer given by camickr, should be followed.
I have a check box and when I create an Action script from the Netbeans' design, it creates a function like;
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
total=8.99f;
xc = "XCheese";
exTop++;
calculateTotal(total);
updateTextArea();
}
This works perfectly, but I want to set everything to zero when the jCheckBox1 is unchecked, if I uncheck it the way the code is now, no changes appear.
It is an sample of code. Hope it will help you.
private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {
if(checkBox.isSelected() ){
total=8.99f;
xc = "XCheese";
exTop++;
calculateTotal(total);
updateTextArea();
}else{
// set everything zero here.
}
}
Start by taking a look at How to Use Buttons, Check Boxes, and Radio Buttons
Basically, the ActionListener will be called when ever the check box is selected (checked) or unselected (unchecked). You need to check the state of the check box when ever the method is called.
Take a look at AbstractButton#isSelected which will tell you the (in this case) the checked state of the JCheckBox
I am pretty new in Java programming, I have been trying to solve this simple program
it reads user input, then the ADD button will simply display the typed string on the JList.
The remove button will simply remove the desired item in the JList.
I am quite confused how to put the action listener thing in the code, or get text whatever
it is. I'd really appreciate if you can help me solve this simple GUI.
It reads user input in JText (String) and when I click the add button (maybe action performed?) the String will be basically populated in JList. and the Remove button will
simply remove the selected String in JList.
Step 1
Bind the code to the specific event, using the addActionListener method.
button.addActionListener(new ActionListener({
public void actionPerformed(ActionEvent e)
{
// Bind the method to the button.
}
});
Step 2
Populate that method with the relevant code.
String value = jTextBox.getText();
// Grab the String value.
jListModel.addElement(value);
// And add it to the list model that informs the JList.
Altogether
button.addActionListener(new ActionListener({
public void actionPerformed(ActionEvent e)
{
String value = jTextBox.getText();
// Grab the String value.
jListModel.addElement(value);
// And add it to the list.
}
});
Useful Links
Here is a very good tutorial from Oracle detailing how to manipulate lists a million and one different ways.
I have an ActionListener attached to a JComboBox(uneditable). Once an item from the JComboBox is selected, I have to make the next button in the frame visible.
The skeleton of the code looks like this:
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource()==jComboBox){
if(jComboBox.getSelectedIndex()==-1)
//Display an alert message
else{
nextButton.setVisible(true);
//Do other actions
}
}
}
It is found that actionPerformed is called only when the second, third, fourth (and so on) items are selected. But actionPerformed is not called when the first item is selected the very first time. But if the first item is selected after selecting other items actioPerformed gets called and the code works fine.
This error appears on some systems and doesn't on other systems. Any help in this regard would be appreciated.
Thanks in Advance!!
This is the normal behavour. The ActionEvent is not fired when you reselect the same item. If you want the event to be fired when you create the combo box then your code should be something like:
JComboBox comboBox = new JComboBox(...);
comboBox.setSelectedIndex(-1); // remove automatic selection of first item
comboBox.addActionListener(...);
comboBox.setSelectedIndex(0);
or
JComboBox comboBox = new JComboBox();
comboBox.addActionListener(...);
comboBox.addItem(...);
comboBox.addItem(...);
Seems like you first condition is a little wrong.
If you want to execute certain code if no item is in your JComboBox, you should check content size : jComboBox.getItemCount()==0 instead of jComboBox.getSelectedIndex()==-1, because selected index can depend upon various conditions, while getItemCount() is only 0 when, well, combo box is empty :-)