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]);
Related
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 );
I am creating a GUI for users to create a Menu from a selection of four combo boxes with Entrees, Sides, Salads, and Desserts. The "Create Menu" button prompts the user to input a menu name and store the new Menu object in the input. How can I store an object of type "Menu" that contains Entrees, Sides, Salads, and Desserts into this user input which is then stored in a JTextArea(My menuList variable)? I would also like to store the new menu name into the new menu object. Any help would be great, thanks!
btnMenuInput = new JButton("Create New Menu");
btnMenuInput.setBounds(120, 100, 200, 30);
btnMenuInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Entree selectedEntree = (Entree)cboEntrees.getSelectedItem();
Side selectedSide = (Side)cboSides.getSelectedItem();
Salad selectedSalad = (Salad)cboSalads.getSelectedItem();
Dessert selectedDessert = (Dessert)cboDesserts.getSelectedItem();
Menu menu = new Menu("", selectedEntree, selectedSide, selectedSalad, selectedDessert);
if(menuList.getText().length() == 0) {
menuList.setText(input.getText().toString());
}
else menuList.setText(menuList.getText() + "\n" + input.getText());
childFrame.setVisible(false);
}
});
childFrame.getContentPane().add(btnMenuInput);
}
});
I have created a jtable that hosts a cell that is a combobox I can get the combobox to populate the jtable but once I restart the program the cells become completely empty. I need a way to save the changes so that once the program is restarted the changes made will remain.( Noted: I have searched solutions for this but to no advance.)
String path ="C:\\Users\\GrantAJ\\Documents\\Comment Matrix";
File folder = new File(path);'File[] listOfFiles= folder.listFiles();
////// filters file objects in java to populate jcombobox with just the name /////
List<String> fileNames = new ArrayList<String>();
for(File files1: listOfFiles){
if(files1.isFile()){
fileNames.add(files1.getName());
}else if (files1.isDirectory())
{ System.out.print("Directory : );
}
final JComboBox jList1 = new JComboBox(listOfFiles);
jList1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessageDialog(null, files1.getName());
}
});
TableColumn col = jTable_Files_Name.getColumnModel().getColumn(4);
col.setCellEditor(new DefaultCellEditor(jList1));
}
Object[] row = new Object[6];
// fill the rows and columns
row[0] = file.getName();
row[1] = file.getAbsolutePath();
row[2]= dt;
row[3]=sb.toString();
row[4]=files1.getName();
row[5]=hostname;
model.addRow(new Object []{row[0],row[1],row[2],row[3],"",row[5]});
}
}catch(Exception e){e.printStackTrace();}
Try to build an "AbstractTableModel".
This table model will contains your data and could be saved.
To load your model, call new JTable(your_model).
You can look here for more help : http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data
Good luck.
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.
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);