java gui help actionlistener - java

I'm trying to set a combobox in my GUI to print the the information about a student in a JLabel.
private void studentComboBoxMouseClicked(java.awt.event.MouseEvent evt) {
if combobox1="student1"{
println.jlabel."name:a";
println.jlabel.""age:12";
println.jlabel."course:english";
}
if combobox1="student2"{
println.jlabel."name:b";
println.jlabel.""age:11";
println.jlabel."course:maths";
}
if combobox1="student3"{
println.jlabel."name:c";
println.jlabel.""age:10";
println.jlabel."course:science";
}
}

You have to listen for itemstatechange on your combobox,
Upon selecting your student , fetch the selected item and operate on to display appropriate messages.
Have a look at this example

If it is a pseudocode, then it's correct. But in java the same code would be:
if ("student1".equals(combobox1)) {
jlabel.setText("name:a age:12 course:english");
} else if ("student2".equals(combobox1)) {
jlabel.setText(...);
} else if ("student3".equals(combobox1)) {
jlabel.setText(...);
}
Of course, it works if combobox1 is String, which holds the value of your combobox.

You are on the right track but you need to read more tutorials. Start with the one suggested by Babban Shikaari. Your code should be something similar to this:
if (combobox.getSelectedItem().equals("student1")){
jlabel.setText("Your new information");
}

Related

Searching trough jList with key events

I have a problem with my Java code. I am trying to search trough a JList, with key events, but it seems like it can't find anything.
With this event, I am adding values to my JList:
DefaultListModel<String> model = new DefaultListModel<>();
private void productButtonActionPerformed(java.awt.event.ActionEvent evt) {
for (Shop i : shopSettings.Products) {
model.addElement(i.getProductName()+i.getPrice()+i.getProductCategory()+i.getNumber());
}
jList1.setModel(model);
}
Here I am trying to search trough the JList, with this action, but anytime I write something, it just overwrites the list, and displays nothing.
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
DefaultListModel filteredProducts = new DefaultListModel();
for (Shop i: shopSettings.Products) {
String productName=i.getProductName()+i.getPrice()+i.getProductCategory()+i.getNumber().toLowerCase();
if(productName.contains(jTextField1.getText().toLowerCase()));
{
model.addElement(i.getProductName()+i.getPrice()+i.getProductCategory()+i.getNumber());
}
}
model=filteredProduct;
jList1.setModel(model);
}
Sorry, if the answer is way too obvious, I have just getting started with Java.
could be:
String productName= (i.getProductName()+i.getPrice()+i.getProductCategory()+i.getNumber()).toLowerCase();
Best to learn how the debugger works in your IDE of choice and step through the algorithm to see why it doesn't match.
Edit: To be more clear: Call toLowerCase on the result of the concatenation, not just the last part.

How to Give Two Forms to JCombobox Items in Java Swing

i am stuck with a new problem, don't know if this works but here i have list of JCombobox as follow.
JCombobox comboBox = new JComboBox();
comboBox.addItem("UserName");
comboBox.addItem("Password");
comboBox.addItem("DLNo 20 b");
comboBox.addItem("DLNo 20 b");
i want to print my database column names which are more than 40!
when i select the Combobox it must internally print my custom item here.
Here i tried with this code but i am not satisfied with this
if(comboBox.getSelectedIndex()==0)
{
System.out.println("U_NAME");
}
if(comboBox.getSelectedIndex()==1)
{
System.out.println("P_NAME");
}
if(comboBox.getSelectedIndex()==2)
{
System.out.println("DL_NO_20_b");
}
if(comboBox.getSelectedIndex()==3)
{
System.out.println("DL_NO_20_b");
}
is there any better way to over come this, like mapping objects
You could create a class ComboBoxItem with a name- and a columnName-attribute.
Use instances of this class for the ComboBox.
In the ComboBoxItem-class, overwrite the toString()-method to return the name, so it gets displayed as wished in the ComboBox. Add a getColumnName()-method to return the columnName, so you could invoke getSelectedItem().getColumnName().

How do i add a customized CellEditorListener to my JTable?

I start typing my code:
private void addMyCellEditorListener() {
class MyCellEditorListener implements CellEditorListener
{
public MyCellEditorListener() {}
public void editingCanceled(ChangeEvent e) {}
public void editingStopped(ChangeEvent e) {
if(row == 0 && column > 0)
rechargeTableWithFindedResults(graphicTable.getValueAt(row,column));
else
dataTable.setValueAt(graphicTable.getValueAt(row,column),row,column);
}
};
.... addCellEditorListener(new MyCellEditorListener());
}
I would like my graphicTable to detect data changes into its cells by giving it a customized CellEditorListener, but I really can't understand how to add it. I tried several times with a code like the following:
DefaultCellEditor editor = new DefaultCellEditor(new JTextLabel());
editor.addCellEditorListener(new MyCellEditorListener());
this.graphicTable.setCellEditor(editor);
... or:
this.graphicTable.setCellEditor(this.graphicTable.getCellEditor().addCellEditorListener(new MyCellEditorListener()));
... however these techniques give me a NullPointerException in both cases.
I have looked around through forums to get a solution, but they are just getting me more confused.
Every hint would be appreciated.
Thanks in advance.
Your approach is incorrect. You can easily detect data changes in your TableModel, specifically in setValueAt method. Once you detected the change and reacted on it, you have to call one of the fireTable.. methods to let table and all other listeners know that data changed
There no need to assign any listeners to cell editors at all.

How to retrieve value from multiple checkboxes Java

I have this SOAP based webservice implemented in Java where the client has a list of checkboxes which after he selects will be stored in the DB.For example for a checkbox of Sex(maschio,femmina) he can select both of them or one of them i implemented it like this but the issue is that the array has fixed size in this case 2 so if the user selects only one of them sexarra[0] will contain it but sexarra[1] will be null so if i pass it to the server it can create problems and the other checkboxes are much larger in size is there any better way to handle this situation? Thank you all in advance your help is really appreciated! i should add that System.out are for testing only:
private void femminaActionPerformed(java.awt.event.ActionEvent evt) {
if (femmina.isSelected()) {
if (sexint == 0) {
sexint++;
sexarra[sexint] = femmina.getText();
} else {
sexarra[sexint] = femmina.getText();
}
}
System.out.println(sexarra[0]);
System.out.println(sexarra[1]);
}
private void maschioActionPerformed(java.awt.event.ActionEvent evt) {
if (maschio.isSelected()) {
if (sexint == 0) {
sexarra[sexint] = maschio.getText();
sexint++;
} else {
sexarra[sexint] = maschio.getText();
}
}
System.out.println(sexarra[0]);
System.out.println(sexarra[1]);
}
please read How to Use Buttons, Check Boxes, and Radio Buttons and if there are lots of checkboxes then you have to read How to Use the ButtonGroup Component, something about Action Listener, you can find examples here
You don't need any event handler.
If you do need to populate some arrays, only do it when you are submitting your data in the end. Each button knows its state; there is no need to redundantly store this info in another data structure each time a button is clicked.
In the end, when submitting the finalized data:
System.out.println(jButton1.getName() + ": " + jButton1.isSelected());
System.out.println(jButton2.getName() + ": " + jButton2.isSelected());\
...
Instead of printing out in your code, you just fill whatever data structure you are sending to the DB when you are ready to submit.
Also you should think about synchronization: you want one method that runs on the Swing EDT to fill your data structure, but some other method on another thread to send those to the DB. And somehow you must make sure the data is synchronized between the two threads.
Ok i resolved the problem i had, i introduced an integer sexint which gets updated whenever one of the checkboxes is selected thus determining the size of the array here is the code:
private void femminaActionPerformed(java.awt.event.ActionEvent evt) {
if(femmina.isSelected()){
if(sexint==0){
sexint++;
sexone=femmina.getText();
}
else if(sexint==1){
sexint++;
sextwo=femmina.getText();
}
else
sexint--;
System.out.println(sexint);
}
}
private void maschioActionPerformed(java.awt.event.ActionEvent evt) {
if(maschio.isSelected()){
if(sexint==0){
sexint++;
sexone=maschio.getText();
}
else if(sexint==1){
sexint++;
sextwo=maschio.getText();
}
else
sexint--;
System.out.println(sexint);
}
}
after which i take sexint and use it to instantiate the array sexarra
Thanks everybody for having taken their time in looking at my problem

set focus for all fields

I noticed I can use getName() as part of the trick.
What is java.awt.Component.getName() and setName() used for?
But I don't really have a clue where to start. What type of listener should I use (assuming the textfield / or box is currently blinking / selected)
This is my previous question, and thank you for the help guys.
How do I use requestFocus in a Java JFrame GUI?
I realize that for each component (Textfield) that I am creating, I have to insert a statement like requestFocus (or using transferFocus).
Is it possible to apply this policy to all the fields???
I have several textfields and ComboBox. The problem I hit is that I don't want to write methods for every single field / box.
For example, I write a method like this
private JTextField getFirstNameEntry() {
.... do something
}
because my instructor writes his program like this
private JPanel getJContentPane() {
jContentPane = new JPanel();
jContentPane.setLayout(new java.awt.FlowLayout(FlowLayout.LEADING));
jContentPane.add(makeLabel(" First Name *", 100, 20));
jContentPane.add(getFirstNameEntry(), null);
jContentPane.add(makeLabel(" Middle Initial", 100, 20));
jContentPane.add(getMiddleInitialEntry(), null);
// etc
return jContentPane;
However, to save redundancy (that was my motive at first), say I have a box, I can simply add the following code inside the method above: getJContentPane()
titleBox = new JComboBox(new String[]{"Mr.","Mrs.","Ms.","Dr.","Prof.","Rev."});
jContentPane.add(titleBox);
But doing this, I still need to create a method to do addItemListener
private void setComboBoxFocus() {
titleBox.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED)
{
String titleSelected = titleBox.getSelectedItem().toString();
System.out.println(titleSelected);
titleBox.transferFocus();
}
}
});
}
However, this doesn't really save redundancy at all. If I have more than one ComboBox to be added, I would have to write another similar method. In fact, even in the case with one ComboBox (titleBox), I would still end up with writing a method for titleBox.
So my question is: is there a way to write a general method that can call focus to all (maybe one for ComboBox type)?
Thank you and sorry for the long post.
Why not take a JComboBox argument to your setComboBoxFocus() method, which allows you to set that listener to any JComboBox you may have? Like so:
private void setComboBoxFocus(JComboBox box) {
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED)
{
String titleSelected = box.getSelectedItem().toString();
System.out.println(titleSelected);
box.transferFocus();
}
}
});
}

Categories

Resources