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);
Related
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 am back with another problem :(
Let me show you guys the code:
JCheckBox pPec = new JCheckBox("Potion Effect");
pPec.setBounds(new Rectangle(50, 270, 140, 30));
pPec.setFont(fDisp);
List<String> pPeLl = new ArrayList<String>();
for (DPE dpe : DPE.values()){
pPeLl.add(dpe.toString());
}
String[] pPeL = pPeLl.toString().replace("[", "").replace("]", "").split(", ");
JComboBox<String> pPeE = new JComboBox<String>(pPeL);
pPeE.setBounds(new Rectangle(175, 270, 150, 30));
List<String> pPeNLl = new ArrayList<String>();
for (int i = 1; i <= 255; i++){
pPeNLl.add(Integer.toString(i));
}
String[] pPeNL = pPeNLl.toString().replace("[", "").replace("]", "").split(", ");
JComboBox<String> pPeN = new JComboBox<String>(pPeNL);
pPeN.setBounds(new Rectangle(175, 300, 73, 30));
JTextField pPeT = new JTextField();
((AbstractDocument)pPeT.getDocument()).setDocumentFilter(new NumberFilter());
pPeT.setBounds(new Rectangle(175+73+4, 300, 73, 30));
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerPotionEffect%%##")){
pPec.setSelected(true);
potionEffect = true;
break;
}else{
pPeN.setEnabled(false);
pPeT.setEnabled(false);
pPeE.setEnabled(false);
potionEffect = false;
}
}
if (DFileLoader.getMethod(pathToSaveAs).size() <= 0){
pPeN.setEnabled(false);
pPeT.setEnabled(false);
pPeE.setEnabled(false);
potionEffect = false;
}
}else{
pPeN.setEnabled(false);
pPeT.setEnabled(false);
pPeE.setEnabled(false);
potionEffect = false;
}
pPec.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (pPec.isSelected()){
pPeE.setEnabled(true);
pPeN.setEnabled(true);
pPeT.setEnabled(true);
}else if (!pPec.isSelected()){
pPeE.setEnabled(false);
pPeN.setEnabled(false);
pPeT.setEnabled(false);
}
if (pPec.isSelected()) potionEffect = true;
else potionEffect = false;
}
});
pane.add(pPec);
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerPotionEffect%%##")){
String[] d = s.split("%%##");
String text;
if (d.length <= 1) text = "";
else text = d[3];
pPeE.setSelectedItem(d[1]);
pPeN.setSelectedItem(d[2]);
pPeT.setText(text);
}
}
}
pane.add(pPeN);
pane.add(pPeT);
pane.add(pPeE);
The DFileLoader.getMethod(String) returns a String List
What I am trying to do is that it loads the information from a file, and if the file starts with "playerPotionEffect%%##" (as shown after file.exists()), it sets the checkbox as selected. If not, it doesn't select it and it disables the other components shown in this piece of code. The checkbox selection works fine, it's just when I load the file, the 2 JComboBoxes and the JTextField are disabled, even though I want them to be enabled.
Can anyone help me? It might be really obvious where the problem is, and that I just haven't noticed. I have tried moving code around, but it still doesn't work.
the "pane" is a Container for the JFrame's content pane.
Also, I have it set to as you click on the checkbox, it enables and disables the other components. This works, and if I turned the checkbox off and on again, the components would be enabled. However, I just want it so that it is enabled on load when the box is checked.
Lol I suck!
To fix this, I have to enable the components in the loop as well before the break. Not all the strings start with playerPotionEffect
xD
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.
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]);
I create a button that will onclick show in a separate window (like you see below) the list of all users from my database.
But, they are displayed all in one line! Even though I put /n - it just wont work. I mean, it work in console when I use Sys.out but when I go to the Window and put it there it is all in one line :(
What should I change in order to display all of the users one below another.
public class ViewAll {
private String listax = "";
ViewAll() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{
ArrayList<String[]> allUsers = DbBroker.getArray("select * from user");
for(String[] usr : allUsers)
listax += usr[0] + ")" + usr[1] + ", " + usr[2] + ", " + usr[3] + "\n";
}
public void display() {
JFrame lis = new JFrame("List of all users");
lis.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
lis.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel pane = new JPanel(new GridLayout(0,1));
lis.add(pane);
pane.add(new JLabel("This is the complete list of all users in my db: "));
pane.add(new JLabel(listax));
lis.pack();
lis.setSize(500,400);
lis.setVisible(true);
}}
I suggest that you don't use a JLabel but instead use a JList. It was built to do just this sort of a thing. The key here being: use the right tool for the job. It also appears that you're trying to use a JFrame in a dialog capacity, and if so, don't -- use a JDialog instead, or even a JOptionPane:
public void display(List<String> userList) {
DefaultListModel<String> listModel = new DefaultListModel<String>();
for (String user : userList) {
listModel.addElement(user);
}
JList<String> userLabel = new JList<String>(listModel);
JScrollPane scrollPane = new JScrollPane(userLabel);
String title = "This is the complete list of all users in my db:";
// mainJFrame is the main JFrame for the GUI
JOptionPane.showMessageOption(mainJFrame, scrollPane, title,
JOptionPane.PLAIN_MESSAGE);
}