SINGLE_INTERVAL_SELECTION is not working as expected - java

A MULTIPLE_INTERVAL_SELECTION is used to select one or more contiguous range of indices at a time.
A SINGLE_INTERVAL_SELECTION is used to select one contiguous range of indices at a time.
But here it is selecting one list index at a time.
import javax.swing.*;
import java.awt.event.*;
public class SwingLessonFive extends JFrame {
JButton button1;
JList favoriteMovies, favoriteColors;
DefaultListModel defaultList = new DefaultListModel();
JScrollPane scrollBars;
String infoOnComponent ="";
public static void main(String[] args) {
new SwingLessonFive();
}
public SwingLessonFive() {
this.setSize(400,400);
this.setTitle("My Fifth Frame");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel thePanel = new JPanel();
button1 = new JButton("Get Answer");
ListenForButton lForButton = new ListenForButton();
button1.addActionListener(lForButton);
thePanel.add(button1);
String[] movies = {"Kick","Batman","SpiderMan","Lucy"};
favoriteMovies = new JList(movies);
favoriteMovies.setFixedCellHeight(30);
favoriteMovies.setFixedCellWidth(150);
favoriteMovies.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); //this is the part I didn't undertand
String[] colors = {"Black","Orange","Brown","Pink","Yellow","White","Red"};
for(String color : colors) {
defaultList.addElement(color);
}
defaultList.add(2, "Purple");
favoriteColors = new JList(defaultList);
favoriteColors.setVisibleRowCount(4);
scrollBars = new JScrollPane(favoriteColors,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
favoriteColors.setFixedCellHeight(30);
favoriteColors.setFixedCellWidth(150);
thePanel.add(favoriteMovies);
thePanel.add(scrollBars);
this.add(thePanel);
this.setVisible(true);
}
private class ListenForButton implements ActionListener {
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button1) {
if(defaultList.contains("Black")) {
infoOnComponent += "Black is in the list \n";
}
if(!defaultList.isEmpty()) {
infoOnComponent +="The list isn't empty\n";
}
infoOnComponent += "Elements in the list: "+defaultList.getSize() +"\n";
infoOnComponent += "Last Element: "+defaultList.lastElement() + "\n";
infoOnComponent += "First Element: "+defaultList.firstElement()+"\n";
infoOnComponent += "Get element at index 1 "+defaultList.get(1)+"\n";
defaultList.remove(0);
defaultList.removeElement("Yellow");
Object[] arrayOfList = defaultList.toArray();
for(Object color: arrayOfList) {
infoOnComponent += color +"\n";
}
JOptionPane.showMessageDialog(SwingLessonFive.this,infoOnComponent,"Information",JOptionPane.INFORMATION_MESSAGE);
infoOnComponent = "";
}
}
}
}

But here it is selecting one list index at a time.
Correct. A single click will select one row.
To select multiple single rows you hold down the Control key when you click
To select a range of rows you hold down the Shift key when you click.
So the selection depends on the selection mode, as well as whether the shift/control keys are used.
Experiment until you get the proper selection mode for your requirement.

Related

conflicting type with JlistSelectionListener

I have the folling code :
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
public class fenetre extends JFrame {
private JList list1, list2;
// private static String[] players1 = {"Player 1", "Player 2"};
// private static String[] players2 = {"Player 3", "Player 4"};
private JLabel label;
private JPanel panel;
private DefaultListModel model1, model2;
#SuppressWarnings("unchecked")
public fenetre(List<character> eq1,List<character> eq2) {
super("JList Example");
setLayout(new BorderLayout());
model1 = new DefaultListModel();
for (int i = 0; i < eq1.size(); i++) {
model1.addElement(eq1.get(i));
}
List<character> lis = new ArrayList<>();
list1 = new JList<String>(model1);
list1.setVisibleRowCount(2);
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(list1), BorderLayout.WEST);
model2 = new DefaultListModel();
for (int i = 0; i < eq2.size(); i++) {
model2.addElement(eq2.get(i));
}
list2 = new JList(model2);
list2.setVisibleRowCount(2);
list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(list2), BorderLayout.EAST);
panel = new JPanel();
panel.setBackground(Color.WHITE);
add(panel, BorderLayout.SOUTH);
label = new JLabel();
panel.add(label);
list1.addListSelectionListener(event -> {
int index = list1.getSelectedIndex();
if (index != -1) {
// Update the label with the selected player's name
label.setText("Selected player: " + model1.get(index).getName());
}
});
list2.addListSelectionListener(event -> {
int index = list2.getSelectedIndex();
if (index != -1) {
// Update the label with the selected player's name
label.setText("Selected player: " + model2.get(index));
}
});
}
}
in this section :
list1.addListSelectionListener(event -> {
int index = list1.getSelectedIndex();
if (index != -1) {
// Update the label with the selected player's name
label.setText("Selected player: " + model1.get(index).toString());
}
});
I'd like to replace model1.get(index).toString() with model1.get(index).getName()
model1 if filled with object of type " character " as you can see, I created this type and implemented a methode getName, yet I can't call it since it's not clear that model1.get(index) is of type character.
what can I change to make it work ?
no clear idea of what I can try to solve this
You're in for a VERY deep dive
The ListModel should contain the instances of Character, you should then make use of the ListCellRenderer API to customise the way in which the value is rendered.
You should then make use of generic constraints to restrict the ListModel and JList to only accept instances of Character
Start by taking a look at How to Use Lists and Writing a Custom Cell Renderer and Generics
To add generic support to the JList and DefaultListModel, you can simply do...
private DefaultListModel<Character> model1, model2;
When you create the JList, you can then do...
list1 = new JList<Character>(model1);
Then when you want to get a Character out of the model, you can simply do...
... = model.getElementAt(index).getName();

Get the number of checkboxes in Swing

I've a swing with some 50 check boxes, and a sample code for 3 is below.
JCheckBox checkboxOne = new JCheckBox("One");
JCheckBox checkboxTwo = new JCheckBox("Two");
JCheckBox checkboxThree = new JCheckBox("Three");
// add these check boxes to the container...
// add an action listener
ActionListener actionListener = new ActionHandler();
checkboxOne.addActionListener(actionListener);
checkboxTwo.addActionListener(actionListener);
checkboxThree.addActionListener(actionListener);
 
// code of the action listener class
 
class ActionHandler implements ActionListener {
    #Override
    public void actionPerformed(ActionEvent event) {
        JCheckBox checkbox = (JCheckBox) event.getSource();
        if (checkbox == checkboxOne) {
            System.out.println("Checkbox #1 is clicked");
        } else if (checkbox == checkboxTwo) {
            System.out.println("Checkbox #2 is clicked");
        } else if (checkbox == checkboxThree) {
            System.out.println("Checkbox #3 is clicked");
        }
    }
}
Here i want to loop through the 50 checkboxes like creating an ArrayList of the available checkboxes and loop them to check which is checked. I'm unable to understand on how to create a ArrayList of checkboxes.
I referred to Array of checkboxes in java, but i'm unable to understand how do i use it?
Please let me know how can do this.
Create an ArrayList of JCheckBox and add them in order.
Then, you can use the indexOf() function to retrieve the number, like so:
public class TestFrame extends JFrame {
public TestFrame() {
setLayout(new GridLayout());
setSize(500, 500);
JCheckBox checkboxOne = new JCheckBox("One");
JCheckBox checkboxTwo = new JCheckBox("Two");
JCheckBox checkboxThree = new JCheckBox("Three");
final ArrayList<JCheckBox> checkBoxes = new ArrayList<>();
add(checkboxOne);
add(checkboxTwo);
add(checkboxThree);
checkBoxes.add(checkboxOne);
checkBoxes.add(checkboxTwo);
checkBoxes.add(checkboxThree);
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
JCheckBox checkbox = (JCheckBox) event.getSource();
int index = checkBoxes.indexOf(checkbox) + 1;
System.out.println("Checkbox #" + index + " is clicked");
}
};
checkboxOne.addActionListener(actionListener);
checkboxTwo.addActionListener(actionListener);
checkboxThree.addActionListener(actionListener);
}
public static void main(String[] args) {
TestFrame frame = new TestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Please note that this is adaptation of your code. This example was made as close as possible to your code so that the only modifications present are supposed to reflect the point I'm trying to get across.
Edit
Since you modified your question and a new one was made, here goes the second part of the answer:
and in my action listener, I was trying to get the checked boxes values, but it is throwing null as name and though I've checked, the output shows as not selected.
Modify your code to use getText() instead of getName(), such as:
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println(checkBoxes.size());
for (int i = 0; i < checkBoxes.size(); i++) {
if (checkBoxes.get(i).isSelected()) {
System.out.println(" Checkbox " + i + " and " + checkBoxes.get(i).getText() + " is selected");
} else {
System.out.println(
" Checkbox " + i + " and " + checkBoxes.get(i).getText() + " is noooooot selected");
}
}
}
});
In order to define an ArrayList with CheckBoxes please refer to following example:
List<JCheckBox> chkBoxes = new ArrayList<JCheckBox>();
Add your JCheckBox elements to the ArrayList using standard approach, for example:
JCheckBox chkBox1 = new JCheckBox();
chkBoxes.add(chkBox1);
Interatve over the list and carry out check if selected using JCheckBox method #.isSelected() as follows:
for(JCheckBox chkBox : chkBoxes){
chkBox.isSelected(); // do something with this!
}
If you need to get all checkboxes from actual existing Frame / Panel, you can use getComponents() method and one by one deside if it's checkbox (not sure if getComponents is supported by all containers)
eg.:
Component[] comps = jScrollPane.getComponents();
ArrayList<JCheckBox> chckBoxes= new ArrayList<JCheckBox>();
for(Component comp : comps) {
if(comp instanceof JCheckBox) {
chckBoxes.add((JCheckBox) comp);
}
}
(Founded # Get all swing components in a container )

Getting a row of names from the first column of JTable

I have a JTable with the column names " Names " , " Quantity " and " Unit " .
I'm coding a program where you get the ingredients names.
So i need to get the whole row of one column and String it all up together,
because i need to store it in mySql and i have already set it all as String.
Any idea how i can do this ?
My code are as follows :
JTable Code:
DefaultTableModel model = (DefaultTableModel)table.getModel();
if(!txtQty.getText().trim().equals("")){
model.addRow(new Object[]{ingCB.getSelectedItem().toString(),txtQty.getText(),unitCB.getSelectedItem().toString()});
}else{
JOptionPane.showMessageDialog(null,"*Quantity field left blank");
}
Getting the values and for storing :
for(int i = 1; i<= i ; i++){
ingredients = table.getName();
}
This is for loop is wrong and it does not work because i have a constructor to take in Ingredients but because it is inside the loop, it cannot take it in.
Any suggestions please ? Thank you.
Constructor :
Food e2 = new Food(Name, Description, priceDbl, Image, Category, Ingredients, promotion );
e2.createFood();
I'm coding a program where you get the ingredients names. So i need to get the whole row of one column and String it all up together, because i need to store it in mySql and i have already set it all as String.
Want to do so, try this. Here I am getting result into ArrayList and String, as I am commented ArrayList you can avoid it.
public class TableValuePrint extends JFrame implements ActionListener{
private final JButton print;
private final JTable table;
private String str="";
public TableValuePrint() {
setSize(600, 300);
String[] columnNames = {"A", "B", "C"};
Object[][] data = {
{"Moni", "adsad", "Pass"},
{"Jhon", "ewrewr", "Fail"},
{"Max", "zxczxc", "Pass"}
};
table = new JTable(data, columnNames);
JScrollPane tableSP = new JScrollPane(table);
JPanel tablePanel = new JPanel();
tablePanel.add(tableSP);
tablePanel.setBackground(Color.red);
add(tablePanel);
setTitle("Result");
setSize(1000,700);
print=new JButton("Print");
JPanel jpi1 = new JPanel();
jpi1.add(print);
tablePanel.add(jpi1,BorderLayout.SOUTH);
print.addActionListener(this);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableValuePrint ex = new TableValuePrint();
ex.setVisible(true);
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==print){
// ArrayList list = new ArrayList();
for(int i = 0;i<table.getModel().getRowCount();i++)
{
//list.add(table.getModel().getValueAt(i, 0)); //get the all row values at column index 1
str=str+table.getModel().getValueAt(i,0).toString();
}
//System.out.println("List="+list);
System.out.println("String="+str);
}
}
}
Output
String=MoniJhonMax

Printing String of JList Selections with ListSelectionListener in Java

fairly new to java here. I'm writing a GUI program of which I want to be able to append the strings (rather than the index number) of selected list items to a text area using a JButton. I am unaware of which java method would allow me to do this. When I use the getSelectedIndex method, it only allows me to append the index number, rather than the string value of the list item to my text area. If it is still unclear what I am asking, here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class FantasyInterface extends JFrame implements ActionListener{
private JList list1;
private JList list2;
private JLabel runningbacks;
private JButton addPlayer1;
private JButton addPlayer2;
private JTextArea text;
String lineSeparator = System.getProperty("line.separator");
private String[] rbs = {"Matt Forte", "Arian Foster", "Maurice Jones-Drew", "Adrian Peterson", "Ray Rice"};
FantasyTeam team1 = new FantasyTeam(5);
FantasyTeam team2 = new FantasyTeam(5);
public FantasyInterface(){
super("Fantasy Football Simulator");
// Set up listsPanel
JPanel listsPanel = new JPanel();
runningbacks = new JLabel("Running Backs:");
listsPanel.add(runningbacks);
list1 = new JList(rbs);
list1.setVisibleRowCount(5);
list1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
listsPanel.add(list1);
addPlayer1 = new JButton("Add To Team 1");
listsPanel.add(addPlayer1);
list2 = new JList(rbs);
list2.setVisibleRowCount(5);
list2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
listsPanel.add(list2);
addPlayer2 = new JButton("Add To Team 2");
listsPanel.add(addPlayer2);
// Add formatted JPanels to Content Pane
getContentPane().add(listsPanel, BorderLayout.NORTH);
// Set up textPanel, where info will appear
JPanel textPanel = new JPanel();
text = new JTextArea(20, 20);
textPanel.add(text);
// Add formatted JPanels to Content Pane
getContentPane().add(text, BorderLayout.SOUTH);
ListSelectionListener listSelectionListener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent listSelectionEvent) {
//System.out.println("First index: " + listSelectionEvent.getFirstIndex());
//System.out.println(", Last index: " + listSelectionEvent.getLastIndex());
boolean adjust = listSelectionEvent.getValueIsAdjusting();
//System.out.println(", Adjusting? " + adjust);
if (!adjust) {
JList list = (JList) listSelectionEvent.getSource();
int selections[] = list.getSelectedIndices();
Object selectionValues[] = list.getSelectedValues();
for (int i = 0, n = selections.length; i < n; i++) {
if (i == 0) {
System.out.println(" Selections: ");
}
System.out.println(selections[i] + "/" + selectionValues[i] + " ");
}
}
}
};
list1.addListSelectionListener(listSelectionListener);
addPlayer1.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
Object srcObj = event.getSource();
if (srcObj == addPlayer1){
text.append(lineSeparator + list1.getSelectedIndex());
}
}
}
The last part,
if (srcObj == addPlayer1){
text.append(lineSeparator + list1.getSelectedIndex());
}
is where I am wondering if there is a method to get the selected index in string form. Thanks to anyone who helps!
Use:
if (!list1.isSelectionEmpty()) {
text.append(lineSeparator + list1.getModel().getElementAt(list1.getSelectedIndex()));
}

drop down list within JTextField

I wnt that when i enter some letter in the textfield then the related items should be picked up from my database and should appear as a drop down list.
For Example:
I typed 'J' in text Field, in my database is having names such as {"Juby','Jaz','Jasmine','Joggy'....}
Theses names should appear as a list. So that i could select one from them.and so on for other leters as well.
Is there any predefined control in awt??
Thnx
Why not just use a JComboBox? By default, when the user types a keystroke in a read-only combobox and an item in the combobox starts with the typed keystroke, the combobox will select that item.
Or you could set the JComboBox to be editable using setEditable(true), and use a KeySelectionManager. The link explains selecting an item in a JComboBox component with multiple keystrokes.
This is a small example implementing what ( i think) you asked for.. the database in this example is a vector of strings.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Answer extends JFrame {
public static final int MAXITEMS = 100;
JPanel panel = new JPanel();
JTextField textField = new JTextField(10);
String[] myDataBase = { "Juby", "Jaz", "Jasmine", "Joggy", "one", "dog","cat", "parot" };
String[] listItems;
JList theList = new JList();
public Answer() {
this.add(panel);
panel.setPreferredSize(new Dimension(500, 300));
panel.add(textField);
panel.add(theList);
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent ke) {
String compareString = ("" + textField.getText() + ke.getKeyChar());
listItems = new String[MAXITEMS];
if (compareString.trim().length() > 0 ){
int counter = 0;
for (int i = 0; i < myDataBase.length; i++) {
if (counter < MAXITEMS) {
if (myDataBase[i].length() >= compareString.length() &&
myDataBase[i].substring(0, compareString.length()).equalsIgnoreCase(compareString)) {
listItems[counter] = myDataBase[i];
counter++;
}
}
}
}
theList.setListData(listItems);
}
});
}
public static void main(String[] args) {
final Answer answer = new Answer();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
answer.pack();
answer.setVisible(true);
}
});
}
}
One option is to use GlazedLists, as it has some support for auto-completion.

Categories