Get the number of checkboxes in Swing - java

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 )

Related

SINGLE_INTERVAL_SELECTION is not working as expected

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.

Clear ArrayList container

I would like to ask you about a way to clean container after mouse click.
Jbutton clearButton = new Jbutton("CLear");
ArrayList<Figure> picture = new ArrayList<>();
How to clean "picure" container after mouse click? I found that class ArrayList has got clear() method to remove all the elements but how to use it in a good way?
Thank you in advance.
Example of using clear :
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(30);
arrlist.add(10);
arrlist.add(50);
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
// finding size of this list
int retval = arrlist.size();
System.out.println("List consists of "+ retval +" elements");
System.out.println("Performing clear operation !!");
arrlist.clear();
retval = arrlist.size();
System.out.println("Now, list consists of "+ retval +" elements");
}
}
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#clear()
The good way: picture.clear();
Et voila.
For the ActionListener:
final Jbutton clearButton = new Jbutton("CLear");
final ArrayList<Figure> picture = new ArrayList<>();
clearButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
picture.clear();
}
});
You can try picture.clear(); since there is no other way to call it.
Assuming this code is defined in a class say MyClass, your class can implement ActionListener interface.
public class MyClass implements ActionListener {
as a part of this, you will have to add a definition for the method actionPerformed and then add an addActionListener to your button clearButton
public void actionPerformed(ActionEvent e) {
if(e.getSource() == clearButton) {
picture.clear();
}
}
The above method can similarly handle different events or button clicks as well.

ArrayList , JFrame, JLabel

I am trying to create and simple program that has the user input 4 fields using the JFrame and textfields. Save those into a class. Put that class into an ArrayList (So they have the option to delete / or add more "classes" to it later). Then display all the contents of the ArrayList on one Frame.
I got the four fields to work I believe , but the part where the ArrayList contents are supposed to be displayed is not working ( I get a blank frame ).
this is my add into the arrayList ..
public void newEntryFrame()
{
JFrame entryFrame = new JFrame("Passafe");
entryFrame.setVisible(true);
entryFrame.setSize(500, 500);
entryFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
entryFrame.setLocationRelativeTo(null);
entryFrame.setLayout(new FlowLayout());
header.setFont(new Font("Serif", Font.BOLD, 16));
entryFrame.add(header);
entryFrame.add(nameLabel);
entryFrame.add(nametf);
entryFrame.add(usernameLabel);
entryFrame.add(usernametf);
entryFrame.add(passwordLabel);
entryFrame.add(passwordtf);
entryFrame.add(descriptionLabel);
entryFrame.add(descriptiontf);
entryFrame.add(enterButton);
enterButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == enterButton)
{
name = nametf.getText();
description = descriptiontf.getText();
username = usernametf.getText();
password = passwordtf.getText();
totalEntries++;
JOptionPane.showMessageDialog(null, "SAVED");
}
else if(source == okButton)
{
JOptionPane.showMessageDialog(null, "Ok Button Works");
}
}
this is what I have to display the arrayList.
public void viewEntryFrame()
{
JFrame viewFrame = new JFrame("Passafe");
viewFrame.setSize(500, 500);
viewFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
viewFrame.setLocationRelativeTo(null);
viewFrame.setLayout(new FlowLayout());
viewFrame.add(listHeader);
newEntry tempView = new newEntry();
for(int i = 0; i < totalEntries; ++i)
{
tempView = entries.get(i);
viewFrame.add(tempView.display);
}
viewFrame.add(okButton);
okButton.addActionListener(this);
viewFrame.setVisible(true);
}
I might be doing this completely wrong if so could you point me in the right direction.
I don't think you ever called setContentPane() A JFrame has only one component in the main part of it. You have to create a JPanel to which you can add all of the components you want, then add that to your JFrame.
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(/**whatever you want in your JFrame**/);
//...
panel.add(/**whatever you want in your JFrame**/);
frame.setContentPane(panel);
You never seem to be adding anything to your entries list...
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if(source == enterButton)
{
name = nametf.getText();
description = descriptiontf.getText();
username = usernametf.getText();
password = passwordtf.getText();
totalEntries++;
// Nope, nothing here...
JOptionPane.showMessageDialog(null, "SAVED");
}
//...
}
Also, this is very dangrouos...
newEntry tempView = new newEntry();
for(int i = 0; i < totalEntries; ++i)
{
tempView = entries.get(i);
viewFrame.add(tempView.display);
}
Rather the relying on the actual side of the ArrayList, you relying on some other variable, which may or may not equal the actual size, instead you should be using ArrayList#size, for example
for(int i = 0; i < entries.size(); ++i)
{
newEntry tempView = entries.get(i);
viewFrame.add(tempView.display);
}
Or if you're using Java 5+...
for(newEntry tempView : enties)
{
viewFrame.add(tempView.display);
}

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