How to clean whitespaces in jComboBox - java

I´m trying to make a jComboBox that contains books titles and when i hit a button that "loan a book", that book no longer appear.
I was able to make all that work, but when I "lend a book", there is a blank space where it was located.
This is the code that i tryied:
private void cargarLibros()
{
String[] libros = new String[this.librosDisponibles()]; //librosDisponibles() returns the amount of books available
for(int i=0; i<this.librosDisponibles(); i++)
{
if(!(this.getBiblioteca().getLibros().get(i).prestado()))
{
libros[i] = this.getBiblioteca().getLibros().get(i).getTitulo(); //get the titles
}
}
jComboBox3.removeAll();
DefaultComboBoxModel modelo = new DefaultComboBoxModel(libros);
this.jComboBox3.setModel(modelo);
}
And also tryied this:
private void cargarLibros()
{
String[] libros = new String[this.librosDisponibles()];
for(int i=0; i<this.librosDisponibles(); i++)
{
if(!(this.getBiblioteca().getLibros().get(i).prestado()))
{
libros[i] = this.getBiblioteca().getLibros().get(i).getTitulo();
}
}
DefaultComboBoxModel modelo = (DefaultComboBoxModel)jComboBox3.getModel();
modelo.removeAllElements();
for(String libro : libros)
{
modelo.addElement(libro);
}
jComboBox3.setModel(modelo);
}
With both of them i obtain this results:
Picking a book
Borrowed book

and when i hit a button that "loan a book", that book no longer appear.
You need to remove the selected item from the model of the combo box.
So the code in your ActionListener of the combo box would be something like:
JComboBox comboBox = (JComboBox)e.getSource();
DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox.getModel();
Object item = comboBox.getSelectedItem();
model.removeElement( item );

Related

I want to add Data in JTable when an item is selected from JComboBox in Java?

I have made a JComboBOx in which I am showing the products that I sell. When a user clicks the Item i search in array list and a Object is returned and from that Object I want to put information in a two dimensional array and after that I want to add that two dimensional array to the row of the JTable but i am not getting anything in table.
Anyone who can help my how I can add items in JTable when an Item is selected from JComboBox?
public void actionPerformed(ActionEvent arg0) {
String boughtThing = InventoryList.getSelectedItem().toString();
int NumberOfItems = Integer.parseInt(JOptionPane.showInputDialog("Enter the Number Item"));
ImplementInventoryServices service = new ImplementInventoryServices();
Inventory thing = service.searchInventory(boughtThing);
double price = thing.getPricePerUnit();
String nameOfProduct = thing.getInventoryName();
int stock = thing.getNumberOfInventory();
int IDofProduct = thing.getInventoryID();
subtotal = 0;
subtotal = price * NumberOfItems;
stock = stock - NumberOfItems;
data[0][0] = Double.toString(price);
data[0][1] = nameOfProduct;
data[0][2] = Integer.toString(NumberOfItems);
data[0][3] = Double.toString(subtotal);
info = new Information(price, nameOfProduct, IDofProduct, subtotal);
Inventory inventory = new Inventory(nameOfProduct, IDofProduct, price, stock);
ImplementInventoryServices updating = new ImplementInventoryServices();
updating.updateInventory(nameOfProduct, inventory);
subTotalList.add(subtotal);
DataHandlingForInventory.write();
}
});
String [] columns = {"ID","Name","Price Per Unit", "Sub Total"};
OrignalTable = new JTable(data,columns);
OrignalTable.setBounds(10, 119, 425, 219);
InvoiceMake.getContentPane().add(OrignalTable);
Try like this:
Create a DefaultTableModel to hold your data and link that to the table:
Object [] columns = {"ID","Name","Price Per Unit", "Sub Total"};
tableModel = new DefaultTableModel(columns, 0);
OrignalTable = new JTable(tableModel);
Now you can use that model (defined as a field in your class so you have access inside the anonymous ActionListener) to work on the data:
// before
// data[0][0] = Double.toString(price);
// data[0][1] = nameOfProduct;
// data[0][2] = Integer.toString(NumberOfItems);
// data[0][3] = Double.toString(subtotal);
// after
tableModel.addRow(new Object[]{Double.toString(price),
nameOfProduct,
Integer.toString(NumberOfItems),
Double.toString(subtotal)});
Please be sure to read up on the documenentation on How to Use Tables

How to set the Radio Button based on the value fetched from the database

I have a JTable filled with data about students (student id, name...), and when I select a row from a table, the form opens and its field need to be filled with same values (eg. if Johny Bravo was selected from the table.
Then his name should be shown in text filed Name on the form, I did like this txtfieldName.setText(student.getName).
My question is how do I set my Radio button automatically (my radio button is Male or Female) when I clicked the field.
enter code here
tableGuest.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try{
int row = tableGuest.getSelectedRow();
String guestEdit=(tableGuest.getModel().getValueAt(row, 0).toString());
String query = "Select guest_id,guest_fname,guest_lname,guest_contact,guest_age,guest_gender,guest_address,guest_email from guest_tbl where guest_id= '"+guestEdit+"'";
PreparedStatement pst = con.prepareStatement(query);
ResultSet rs = pst.executeQuery();
buttonGroupEdit.add(rdbtnMaleEdit);
buttonGroupEdit.add(rdbtnFemaleEdit);
while(rs.next())
{
String genderEdit=rs.getString("guest_gender");
if(genderEdit.equals("Male"))
{
rdbtnMaleEdit.setSelected(true);
}
else if(genderEdit.equals("Female"))
{
rdbtnFemaleEdit.setSelected(true);
}
else
{
JOptionPane.showMessageDialog(null, "error !");
}
tfEditFname.setText(rs.getString("guest_fname"));
tfEditLname.setText(rs.getString("guest_lname"));
tfEditEmail.setText(rs.getString("guest_email"));
tfEditContact.setText(rs.getString("guest_contact"))
}
pst.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
});
String gender = "male"
// this comes from db - since we don't know the structure this is a plain guess.
if (gender.equals("male") {
rbtMale.setSelected(true);
} else {
rbtFemale.setSelected(true);
}
And like MadProgrammer said, you will need a ButtonGroup and add all relevant buttons to it.
private final ButtonGroup genderButtons = new ButtonGroup();
genderButtons.add(rbtMale);
genderButtons.add(rbtFemale);
I've worked with same kinda solution in my work I am generating radiobutton with database values and showing them in java dialog.
We have a values from database stored in list like below:
List Titles; //This is a list containing your database values
First count the values of this list elements:
int list_count=Titles.size();
Now to proceed with radio function first we need to convert list elements into array like below:
String[] col = new String[list_count]; //created an array with limit of list count values
for(int i=0; i < list_count; i++){
col[i]=Titles.get(i).toString(); // add values of list into array with loop
}
Below is the function that is creating radio buttons with database array we created above:
public String get_key(int list_count, String[] col){
JRadioButton jb[] = new JRadioButton[col.length]; //Create Radion button array
ButtonGroup rb = new ButtonGroup(); //Group Radio Button
JPanel panel = new JPanel( new GridLayout(0, 1) ); //Set layout of radion button to display each after other
JScrollPane sp = new JScrollPane(panel); // Create a scrollpane to put all these radio button on that
GridBagLayout gridbag = new GridBagLayout(); //Layout for scrollpane
sp.setViewportBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); //bordre for scrollpane
List<Component> q = new ArrayList<>(); // q is a component to store and display each radio button
JLabel h1=new JLabel("Select a value"); //put a heading on top of jpanel before radio button
h1.setFont(new Font("Serif", Font.BOLD, 18)); // set heading text
panel.add(h1); //add heading on top of jpanel
panel.setBorder(new EmptyBorder(10, 10, 10, 10)); //set panel border to padding each radio button
for(int i=0; i < list_count; i++){
jb[i]=new JRadioButton(col[i]); //create radion button dynamacially "col[i]" is the value of each radio
rb.add(jb[i]); //it is important also to put all radio in a group we created so only one element should be selected
panel.add(jb[i]); // add all radio on jpanel
}
sp.setPreferredSize( new Dimension( 350, 300 ) ); //set size of scrollpane
int act=JOptionPane.showConfirmDialog(null, sp, "Select Primary Key",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE); //add and show scrollpane in dialog
}
Calling this function with parameter values we created first "list_count" & "col":
get_key(list_count, col);
Create a Student.java class to get particular table value from database.
In the current form AddStudent create a function call as getStudentList to fill the GUI form with database data to particular id.
public ArrayList<Student> getStudentList() {
ArrayList<Student> studentList = new ArrayList<>();
conn = DbConnection.ConnectDb();
String selectQuery = "SELECT * FROM student";
try {
PreparedStatement pst = conn.prepareStatement();
ResultSet rs = pst.executeQuery();
Donor donor;
while(rs.next()) {
student = new Student(rs.getString("id"),
rs.getString("gender"));
studentList.add(student);
}
} catch (SQLException ex) {
Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
}
return studentList;
}
After create a function called showStudent to show the particular data value to called id.(In below code male,female are the checkbox values)
public void showStudent(int index) throws ParseException {
if(getStudentList().get(index).getGender().equals("male")) {
male.setSelected(true);
female.setSelected(false);
gender = "male";
}
else {
female.setSelected(true);
male.setSelected(false);
gender = "female";
}
}
Set action to the jbutton, When get value id from jtextfield then fill the checkbox in particular gender value.

Radio button to change JCombo Data

Looking for a way to change the data outputted to the combo box by selecting the radio buttons, but the data is being pulled in off a text file and saved into an array and then passed back into JCOMBO array list. sorry if question is a big vague i was not to sure how to word it. but the files are separated by two different TXT files which i can easily return data from.
ArrayList<String> stations = Reader("Default.txt");
JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]));
JRadioButton belgrave = new JRadioButton("Belgrave Line");
belgrave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
cb.removeAllItems();
stations.clear();
ArrayList<String> stations = Reader("Belgrave.txt");
JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]));
}
});
JRadioButton glenwaverly = new JRadioButton("Glen Waverly Line");
glenwaverly.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
cb.removeAllItems();
stations.clear();
ArrayList<String> stations = Reader("Glenwaverly.txt");
JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]));
}
});
ButtonGroup bG = new ButtonGroup();
JButton apply = new JButton("Touch on ?");
JButton cancel = new JButton("Cancel");
Much like the action listener that you added into the apply and cancel button you will need to apply an action listener to the radio button as well.
And then do something like the following.
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//suppose this is your file input, that you will have to read
String[] test = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
//your combobox name supposed it is combo
//remove all the previous items
combo.removeAllItems();
//add all the items of the array(there is no addAll method)
for(int i=0; i<test.length; i++)
combo.addItem(test[i]);
}
Hope it helps.
Note that reading from a TXT file and parsing the data as an Array is related with the structure of your txt. Take a look here for how to read a txt line by line.
EDIT
In your listeners you are creating a new local combobox . However cb inside the listeners is not the same as cb outside of the listeners, it is simply a variable that is created & known only inside the method. You need to directly call cb without creating a new object.
Replace this JComboBox<String> cb = new JComboBox<>(stations.toArray(new String[stations.size()]))
with that
String[] items = stations.toArray(new String[stations.size()];
for(int i=0; i<items.length; i++)
cb.addItem(items[i]);

Printing all content of a JList as output

I have a JList in my GUI, which uses an ArrayList as data:
ArrayList Cruise = new ArrayList();
Cruise.add("Scottish to Greek Waters");
Cruise.add("Greek to Scottish Waters");
JScrollPane scrollPane = new JScrollPane();
CruiseList = new JList(Cruise.toArray());
CruiseList.setPreferredSize(new Dimension(200, 200));
scrollPane.setViewportView(CruiseList);
CruiseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
CruiseList.setSelectedIndex(0);
CruiseList.setVisibleRowCount(6);
listPanel.add(scrollPane);
Frame1.setVisible(true);
I have a button - List all Cruises, which once clicked on should display this as output:
"Scottish to Greek Waters"
"Greek to Scottish Waters"
However, upon clicking the button, it only displays the selected list option as output.
This is what I have so far:
listallCruises.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String AllCruises = CruiseList.getSelectedValue().toString();
System.out.print("All Cruises:\n" + AllCruises + CruiseList.getModel() + "\n");
}
});
How do I print out all element in the list upon clicking the button?
You are outputting just the selected value because that's the method you are calling, getSelectedValue().
To display ALL the values, you have to get the model and iterate through the values, like so:
int size = CruiseList.getModel().getSize();
StringBuilder allCruises = new StringBuilder("All cruises:");
for(int i = 0; i < size; i++) {
allCruises.append("\n").append(CruiseList.getModel().getElementAt(i));
}
System.out.print(allCruises);

java, collect data from one JTable, using event handler change display of other JTable

Since the program is too large I'll just paste the important parts of code. Here's the problem:
I have two JTables. First one collects data from DB and displays the list of all invoices stored in DB. The purpose of the second table is when you click on one row from the table, event handler needs to collect integer from column ID. Using this ID the second table will then display all the contest of that invoice (all the products stored in it).
First and second table work perfectly. The problem is that I have no idea how can I collect certain data (I basically just need ID column) from a selected row and then through a method I already made update the second JTable with new info. Here's my code if it helps:
(PS: once I learn how to do that, will the list on the left change every time by default when I select different row, or do I need to use validate/revalidate methods?)
public JPanel tabInvoices() {
JPanel panel = new JPanel(new MigLayout("", "20 [grow, fill] 10 [grow, fill] 20", "20 [] 10 [] 20"));
/** Labels and buttons **/
JLabel labelInv = new JLabel("List of all invoices");
JLabel labelPro = new JLabel("List of all products in this invoice");
/** TABLE: Invoices **/
String[] tableInvTitle = new String[] {"ID", "Date"};
String[][] tableInvData = null;
DefaultTableModel model1 = new DefaultTableModel(tableInvData, tableInvTitle);
JTable tableInv = null;
/** Disable editing of the cell **/
tableInv = new JTable(model1){
public boolean isCellEditable(int r, int c) {
return false;
}
};
/** Load the invoices from DB **/
List<Invoice> listInv = is.getAllInvoices();
for (int i = 0; i < listInv.size(); i++) {
model1.insertRow(i, new Object[] {
listInv.get(i).getID(),
listInv.get(i).getDate()
});
}
/** TABLE: Invoice Info **/
String[] tableInfTitle = new String[] {"ID", "Name", "Type", "Price", "Quantity"};
String[][] tableInfData = null;
DefaultTableModel model2 = new DefaultTableModel(tableInfData, tableInfTitle);
JTable tableInf = null;
/** Disable editing of the cell **/
tableInf = new JTable(model2){
public boolean isCellEditable(int r, int c) {
return false;
}
};
/** Load the products from DB belonging to this invoice **/
List<Product> listPro = is.getInvoiceInfo(1); // Here's where I need the ID fetched from selected row. For now default is 1.
for (int i = 0; i < listPro.size(); i++) {
model2.insertRow(i, new Object[] {
listPro.get(i).getID(),
listPro.get(i).getName(),
listPro.get(i).getType(),
listPro.get(i).getPrice(),
listPro.get(i).getQuantity()
});
}
/** Scroll Panes **/
JScrollPane scrollInv = new JScrollPane(tableInv);
JScrollPane scrollPro = new JScrollPane(tableInf);
panel.add(labelInv);
panel.add(labelPro, "wrap");
panel.add(scrollInv);
panel.add(scrollPro);
return panel;
}
For now, the right table only displays content of the first invoice:
With the help of following code you can get the value of selected clicked cell, so you just have to click on ID cell value (the Invoicee ID whose Products you want to see in second table) and with the help of following event handler you will get the value and then you can get data based on that ID and set to second table. (In the code below, table is the object of your first table)
(Off-course you will have to apply some validation too, to check that the selected (and clicked) cell is ID not the DATE)
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
int col = table.columnAtPoint(e.getPoint());
Object selectedObj = table.getValueAt(row, col);
JOptionPane.showMessageDialog(null, "Selected ID is " + selectedObj);
}
});

Categories