Clear ArrayList container - java

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.

Related

How can i access a linked list that is implement by me form outside of class

I have a linked list that store bunch of instrument as an object. And i want to access and display it on a GUI. What are some good ways to access it instead of just create a method and return the list to the GUI.
Pls gives some advice.
I will be appreciated.
It depends if you mean the class or an instance of your class. If you mean a class its just an import. If you need an instance of a class there are other ways like making it static (quick and dirty) or using a singleton if just one copy is allowed.
class InstrumentDisplayPanel extends JPanel implements ActionListener {
JPanel status = new JPanel();
JPanel action = new JPanel();
JLabel name = new JLabel();
JLabel number = new JLabel();
JButton next = new JButton("next");
JButton previous = new JButton("previous");
InstrumentDisplayPanel() {
this.setPreferredSize(new Dimension(200,200));
DoublyLinkedList<Instrument> instrumentList = FileRead.loadInstrument();
Node tempNode = instrumentList.getFirstItem();
Item tempItem = (Item)tempNode.getItem();
name.setText(tempItem.getName());
number.setText(tempItem.getNumber());
status.add(name);
status.add(number);
action.add(next);
action.add(previous);
add(status);
add(action);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == next) {
}
}
}
public static DoublyLinkedList<MusicSheet> loadMusicSheet(){
System.out.println("I am loading");
Scanner musicSheetInput = null;
try
{
musicSheetInput = new Scanner(new File("musicSheet.txt"));
}
catch(FileNotFoundException instrument)
{
System.out.println("File does Not Exist Please Try Again: ");
}
DoublyLinkedList<MusicSheet> musicSheetList = new DoublyLinkedList<MusicSheet>();
while (musicSheetInput.hasNextLine()){
String name = musicSheetInput.next();
String number = musicSheetInput.next();
String description = musicSheetInput.nextLine();
if(name.equals("GuitarSheet")){
musicSheetList.add(new GuitarSheet(name,number,description));
}
else if(name.equals("ViolinSheet")){
musicSheetList.add(new ViolinSheet(name,number,description));
}
else if(name.equals("CelloSheet")){
musicSheetList.add(new CelloSheet(name,number, description));
}
}
musicSheetList.display();
return musicSheetList;
}

Unable to use for loop to change which JLabel is currently being affected

I am attempting to use a forloop to be able to change which jlabel is being affected, as for they all perform the same function, and have the same name other than the numerical value at the end of each name.
Essentially, I use a drag and drop transfer handler to create a food web game. I want to randomize the game to three different food webs that may appear. The randomization is fine and all, but I am unknowledgable of how to use a loop to determine which JLabel's icon is being set. Since I am using generally all the same name for each individual JLabel that has an icon that will change based on which themed food web was randomly selected, I am wanting to know how to make the loop change which JLabel is being selected, as for I get a syntax error from attempting to do the "selection(i+1)".
private static int randomNumber(){
return(int) (Math.random() * (3 - 1 + 1) + 1);
}
private void generateQuiz(){
switch(randomNumber()){
case 1: //the for loop changes each available selection based on each element in the foor loop.
for(int i = 0; i < consumers1.size(); i++){
selection(i+1).setIcon(new ImageIcon(getClass().getResource(
"/resources/quiz/"+consumers1.get(i)+".png")));
}
break;
case 2:
break;
case 3:
break;
want: change each of these selection boxes auto-magically using a for loop rather than typing each individual thing manually for each case
EDIT: This is the rest of the general code around this problem,
private String[] producers = {"grass", "plankton", "berries"};
private ArrayList<String> consumers1 = new ArrayList();
private ArrayList<String> consumers2 = new ArrayList();
private ArrayList<String> consumers3 = new ArrayList();
//mouselistener to handle all image move-ability
MouseListener mouseListener = new MouseListener() {
#Override public void mouseClicked(MouseEvent e) {}
//a mouselistener for that each img has the ability to be moved into spots
#Override
public void mousePressed(MouseEvent e) {
JComponent jc = (JComponent)e.getSource();
TransferHandler th = jc.getTransferHandler();
th.exportAsDrag(jc, e, TransferHandler.COPY);
// System.out.println(producers1.getIcon());
}
#Override public void mouseReleased(MouseEvent e) {}
#Override public void mouseEntered(MouseEvent e) {}
#Override public void mouseExited(MouseEvent e) {}
};
/**
* Creates new form Quiz
*/
public Quiz() {
initComponents();
//sets the jframe to the center of the screen
setLocationRelativeTo(null);
//changes how the jframe closes
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent windowEvent) {
//confirm dialog to ensure user wants to close, if not return
int confirm = JOptionPane.showConfirmDialog(null,
"A quiz is currently inprogress. "
+ "\nAll unsubmitted quizs will not be saved!"
+ "\nDo you wish to exit?",
"Exit",
JOptionPane.YES_NO_OPTION);
if (confirm == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
//random algorithm; t1 = x, tn = (tn-1) + xn
//<--- RANDOM QUIZ GENERATION --->
//add all the image names to array lists
Collections.addAll(consumers1, "goat", "rabbit", "jackal", "wildcat",
"lion");
Collections.addAll(consumers2, "fish", "mussel", "bird", "octopus",
"human");
Collections.addAll(consumers3, "butterfly", "grasshopper", "frog",
"spider", "snake");
generateQuiz();
// end of quiz generaiton
//<--- DRAG AND DROP ADDITIONS LISTENERS AND TRANSFER HANDLERS --->
//adds mouse listener to be able to drag and drop the imgs in the seleciton boxes
selection1.addMouseListener(mouseListener);
selection2.addMouseListener(mouseListener);
selection3.addMouseListener(mouseListener);
selection4.addMouseListener(mouseListener);
selection5.addMouseListener(mouseListener);
selection6.addMouseListener(mouseListener);
//creates transfer handlers to bea ble to drag and drop the images in the frame
TransferHandler th = new TransferHandler("icon");
selection1.setTransferHandler(th);
selection2.setTransferHandler(th);
selection3.setTransferHandler(th);
selection4.setTransferHandler(th);
selection5.setTransferHandler(th);
selection6.setTransferHandler(th);
producer.setTransferHandler(th);
consumer1.setTransferHandler(th);
consumer2.setTransferHandler(th);
consumer3.setTransferHandler(th);
consumer4.setTransferHandler(th);
consumer5.setTransferHandler(th);
//<--- END OF DRAG AND DROP ADDITIONS LISTENERS AND TRANSFER HANDLERS --->
}
private static int randomNumber(){
return(int) (Math.random() * (3 - 1 + 1) + 1);
}
private void generateQuiz(){
switch(randomNumber()){
case 1:
for(int i = 0; i < consumers1.size(); i++){
selection(i+1).setIcon(new ImageIcon(getClass().getResource(
"/resources/quiz/"+consumers1.get(i)+".png")));
}
break;
case 2:
break;
case 3:
break;
}
}
P.S.: It's made in netbeans gui builder for a school assignment so it'x declared in the automatic generated code by neatbeans
Ah, "selection..." is simply a variable name.
When the Java program is compiled, most variable names are replaced by pointers to memory locations, so you can't assemble a string at run time and invoke the corresponding variable. (You could make them public and use Reflection but it would be absolutely wrong here).
Here the simplest way to do what you are trying is the following:
JLabel[] selections={
selection1,
selection2,
selection3,
selection4,
selection5,
selection6
};
and then use selections[i] instead of selection(i+1).

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 )

How can I implement loops and if-else logic for ActionListener?

I'm trying to build a simple quiz game using Swing. The user should be able to pick a fruit or vegetable from the combobox and guess if it is a fruit or vegetable. If they guess correctly, the GUI should output "yes". If they guess wrong, it should output "no". The code seems to compile correctly, but it is not running correctly.
I am using an if-else loop within the "fruit" and "vegetable" button's ActionListener in order to determine if the user guessed correctly.
public class GUI {
public static String input;
public static void main(String[] args) {
new GUI();
}
public GUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Simple GUI");
frame.setSize(400,300);
frame.setLocationRelativeTo(null);
final String[] fruitOptions = {"Apple", "Apricot", "Banana"
,"Cherry", "Date", "Kiwi", "Orange", "Pear", "Strawberry"};
final String[] vegOptions = {"Asparagus", "Beans", "Broccoli", "Cabbage"
, "Carrot", "Celery", "Cucumber", "Leek", "Mushroom"
, "Pepper", "Radish", "Shallot", "Spinach", "Swede"
, "Turnip"};
String[] combined = {"Apple", "Apricot", "Banana"
,"Cherry", "Date","Cucumber", "Leek", "Mushroom"
, "Pepper", "Radish","Kiwi", "Orange", "Pear", "Strawberry", "Asparagus", "Beans", "Broccoli", "Cabbage"
, "Carrot", "Celery","Shallot", "Spinach", "Swede"
, "Turnip"};
JPanel comboPanel = new JPanel();
JLabel comboLabel = new JLabel("Is it a Fruit or Vegetable?:");
final JComboBox fruitsVeggies = new JComboBox(combined);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
input = (String) fruitsVeggies.getSelectedItem();
}
};
fruitsVeggies.addActionListener(actionListener);
comboPanel.add(comboLabel);
comboPanel.add(fruitsVeggies);
final JButton fruitButton = new JButton( "Fruit");
JButton vegButton = new JButton("Vegetable");
final JLabel yes = new JLabel("YES");
final JLabel no = new JLabel("NO");
ActionListener listener = new ActionListener()
{
public void actionPerformed (ActionEvent d)
{
int i;
for(i=0; i<vegOptions.length-1; i++)
{
if (input.equals(fruitOptions[i]))
{
yes.setVisible(true);
}
else
no.setVisible(true);
}
}
};
ActionListener vegListener = new ActionListener()
{
public void actionPerformed(ActionEvent f)
{
int i;
for(i=0; i<vegOptions.length-1; i++)
{
if (input.equals(fruitOptions[i]))
{
no.setVisible(true);
}
else
yes.setVisible(true);
}
}
};
no.setVisible(false);
yes.setVisible(false);
fruitButton.addActionListener(listener);
vegButton.addActionListener(vegListener);
frame.add(comboPanel, BorderLayout.NORTH);
frame.add(vegButton,BorderLayout.WEST);
frame.add(fruitButton, BorderLayout.EAST);
frame.add(yes, BorderLayout.CENTER);
frame.add(no, BorderLayout.CENTER);
frame.setVisible(true);
}
}
You're problem is with the following code
public void actionPerformed (ActionEvent d)
{
int i;
for(i=0; i<vegOptions.length-1; i++)
{
if (input.equals(fruitOptions[i]))
{
yes.setVisible(true);
}
else
{
no.setVisible(true);
}
}
}
With each iteration of your loop you're setting the visibility of one of your labels. Instead you should check the result in the loop and then set the visibility after. Also, you appear to checking only if the input is a fruit, and if so, setting yes to visible. This isn't a correct comparison. You should be checking if the type of the selection matches the users guess.
Declaring component variable local to method is not preferable especially when you will need to use means of Anonymous class which will need your component variable declared to be final. Declare the component variable in the class context.
No need to use two separate JLabel to show YES and NO for correct input. Use one JLabel and make use of setText(string) method of JLabel. When a decision is yet to take, use resultNo answer is chosen or similar which make sense to you. For example:
answerLabel = new JLabel("No answer is chosen");
// answerLabel is a JLabel declared in class context
You have mistakes in your actionPerformed function as pointed out below:
public void actionPerformed (ActionEvent d)
{
int i;
for(i=0; i<vegOptions.length-1; i++)
{
if (input.equals(fruitOptions[i])) //<---i is bounded to vegOptions length
//but iterating over fruitOptions !!
answerLabel.setText("YES! Correct Answer");
else
answerLabel.setText("NO! Wrong Answer");
}
}
And similar changes to other action component, i.e., two JButton
for(i=0; i<vegOptions.length-1; i++)
{
if (input.equals(fruitOptions[i]))
yes.setVisible(true);
else
no.setVisible(true);
}
This code is wrong.
The first problem, as mentioned by Sage, is that vegOptions.length-1 should be fruitOptions.length - you are checking the fruits, not the vegetables.
The other problem might not be obvious at first. Let's say the user enters "apple". The code checks "apple" (their input) against "apple" (from fruitOptions), and displays the "yes" label. Then the code checks "apple" (their input) against "apricot" (from fruitOptions) and displays the "no" label. After the loop, both the "yes" and "no" labels will be visible.
This code should work. Make sure you understand why it works:
boolean isInArray = false;
for(i=0; i<fruitOptions.length; i++)
{
if (input.equals(fruitOptions[i]))
{
isInArray = true;
}
}
if(isInArray)
{
yes.setVisible(true);
no.setVisible(false);
}
else
{
no.setVisible(true);
yes.setVisible(false);
}
Note that neither problem has anything to do with ActionListener.
Also as Sage pointed out, there's no need to have two JLabels when you can have one and change the text on it.

case sensitive jcombobox

My problem is a bit tricky. I am using an Editable JComboBox. It may contain case sensitive items. For example, it may have Item1 and item1. So, these two items should be treated as different in my case.
But the problem is, these two items is treated as same. No matter which Items I have selected, it always select the first one (Item1). I've searched in Google, but didn't find any solution. That's why, I am here.
Code:
//loading of Items
jdcbmItemType = new javax.swing.DefaultComboBoxModel(ItemTypeHandler.getItemTypeComboData(MainFrame.companyId));
private void jcbItemTypeMouseReleased(MouseEvent evt)
{
if (jcbItemType.getSelectedIndex() != -1)
{
loadItemTypeDetails(((ItemObject) jcbItemType.getSelectedItem()).getId());
}
else
{
resetFields();
}
}
public static Vector<ItemObject> getItemTypeComboDataV(BigInteger companyId, BigInteger categoryId, boolean addFirstElement, TriState deleted) throws ExceptionWrapper, EJBException
{
try
{
return (Vector<ItemObject>)lookupItemTypeFacade().getItemTypeComboData(companyId, categoryId, addFirstElement, deleted);
} catch (ExceptionWrapper exceptionWrapper)
{
throw exceptionWrapper;
} catch (EJBException ejbEx)
{
throw ejbEx;
} catch (Exception ex)
{
throw new ExceptionWrapper(ex.getMessage());
}
}
ItemObject is a customClass where one field is BigInteger and another is String.
getItemTypeComboData is functioning properly. So, you can assume to get a list of ItemObject from here and it will nicely convert it to Vector<ItemObject>
jcbItemType.getSelectedIndex() always return the same index for Item1 and item1. But it returns different index for item2.
I know, it would be better if I can use itemStateChanged event. But in my case, I can't use it. But my question is, MouseReleased and FocusLost works fine for different name string but not same string with different case. I am really stumbled.
Another way to ask the question:
Does MouseReleased or FocusLost event check for case-sensitive items?
How to resolve this problem?
Thanks.
Here is my SSCCE and this works fine , If this is not what youre looking for, then post your SSCCE for better sooner help!
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxTest {
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
new ComboBoxTest();
}
public ComboBoxTest() {
String items[] = {"Item1", "item1"};
JFrame frame = new JFrame("JComboBox Case-sensitivity Test");
JPanel panel = new JPanel();
combo = new JComboBox(items);
combo.setEditable(true);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
String str = (String) combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 100);
frame.setVisible(true);
}
}
I think you are doing like this :-
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
cb.setEditable(true);
Now you have to access the JCombobox elements which you have insert into this as in array form like this:-
MyItemListener actionListener = new MyItemListener();
cb.addItemListener(actionListener);
class MyItemListener implements ItemListener {
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
JComboBox cb = (JComboBox)evt.getSource();
// Get the affected item
Object item = evt.getItem();
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
// Item is no longer selected
}
}
}
After adding the itemListener you can do your different tasks with individual JCombobox Item
Try this, it works fine...
use ActionListener() to capture the click... then use getSelectedItem() to capture the item clicked on the JComboBox
try this,
check in your console for the output
myComboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
String str = (String) myComboBox.getSelectedItem();
System.out.println(str);
}

Categories