I have a JButton ArrayList. The code below does not work. How can I access a specific button from the array list and set the size, location and other properties and also add it to the applet?
ArrayList<String> cdTitles = new ArrayList<String>();
ArrayList<JButton> btnCDS = new ArrayList<JButton>();
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Initialize")) {
cdTitles.add("Original Order");
cdTitles.add("Metric - Fantasies");
cdTitles.add("Beatles - Abby Road");
cdTitles.add("Pearl Jam - Ten");
cdTitles.add("Doors - Alive");
cdTitles.add("The Rolling Stones - Gimme Shelter");
for(int i = 0; i < cdTitles.size(); i++) {
String buttonName = "btn" + i;
System.out.println(buttonName);
btnCDS.add(new JButton(buttonName));
break;
}
btnCDS.get(0).setText(cdTitles.get(0));
btnCDS.get(0).setLocation(100, 145);
btnCDS.get(0).setSize(520, 25);
add(btnCDS.get(0));
}
}
provided that this is executing in a Applet sub-class,
this works for me:
#Override
public void init()
{
// all your code between:
// cdTitles.add("Original Order");
// AND
// add(btnCDS.get(0));
// Watch out for dead code in the for loop.
}
Related
Create a program that will count the number of times an input name appeared in a list from an input array of 10 names. Using JOptionPne.
(After input of 10 names and for a name to count from the list, and assuming Maria is the name entered to count)
Expected sample output
My code so far:
import javax.swing.JOptionPane;
public class Chapter4Act_Array {
public static void main(String[] args) {
String ArrayOf_Names[] = new String[10];
for (int i = 0; i < ArrayOf_Names.length; i++) {
ArrayOf_Names[i] = JOptionPane.showInputDialog("Enter name" + (i + 1) + ":");
}
System.out.println("Your friends are: ");
for (int i = 0; i < ArrayOf_Names.length; i++) {
System.out.println(ArrayOf_Names[i]);
}
}
}
Little short on information but I think i know what you are trying to accomplish. In the demo code below, a JOptionPane is used to acquire the names from a User. Do do this a custom panel is created and passed to the JOptionPane#showOptionPane() method:
Yes...that's a JOptionPane. This is most likely more than you require but then again there isn't enough info to clarify either way. In any case, here is the code and be sure to read all the comments in code (comments always make the code look more than it really is):
/* Create a JPanel object to display within the JOptionPane
and fill it with the components we want. */
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
JLabel msg = new JLabel("<html><center><font size='4'>Please enter <font "
+ "color=blue>User</font> names into the list below:"
+ "</font></html>");
msg.setVerticalAlignment(JLabel.TOP);
msg.setPreferredSize(new Dimension(135, 60));
jp.add(msg, BorderLayout.NORTH);
// Add a JTextfield and JLabel
JPanel textPanel = new JPanel();
textPanel.setLayout(new BorderLayout());
JLabel name = new JLabel("Enter Name:");
JTextField textField = new JTextField(0);
textPanel.add(name, BorderLayout.NORTH);
textPanel.add(textField, BorderLayout.SOUTH);
jp.add(textPanel, BorderLayout.CENTER);
// Add a JList (in a JScrollPane) and Add/Remove buttons
JPanel listPanel = new JPanel();
DefaultListModel<String> listModel = new DefaultListModel<>();
JList<String> list = new JList<>(listModel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(120, 150));
scrollPane.setViewportView(list);
listPanel.add(scrollPane, BorderLayout.WEST);
// Add/Remove Buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
JButton addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
int listItemCount = 0;
#Override
public void actionPerformed(ActionEvent e) {
if (textField.getText() != null) {
listModel.addElement(textField.getText());
if (listModel.getSize() == 10) {
addButton.setEnabled(false);
return;
}
}
textField.requestFocus();
textField.setSelectionStart(0);
textField.setSelectionEnd(textField.getText().length());
}
});
buttonPanel.add(addButton, BorderLayout.NORTH);
JButton removeButton = new JButton("Remove");
removeButton.addActionListener(new ActionListener() {
int listItemCount = 0;
#Override
public void actionPerformed(ActionEvent e) {
int selectedIndex = list.getSelectedIndex();
if (list.getSelectedIndex() >= 0) {
listModel.remove(selectedIndex);
}
if (listModel.getSize() < 10) {
addButton.setEnabled(true);
}
if (selectedIndex > 0) {
list.setSelectedIndex(selectedIndex - 1);
}
}
});
buttonPanel.add(removeButton, BorderLayout.CENTER);
listPanel.add(buttonPanel, BorderLayout.EAST);
jp.add(listPanel, BorderLayout.SOUTH);
// Supply what we want the dialog button captions are to be.
Object[] buttons = {"Process", "Cancel"};
// Display the JOptionPane using the Option Dialog.
int res = JOptionPane.showOptionDialog(this, jp, "User Names", 0,
JOptionPane.PLAIN_MESSAGE, null, buttons, 1);
// The following code will no run until the JOptionPane is closed.
/* If the list does not contain 10 names then inform
the User and make him/her do it over again. */
if (listModel.getSize() < 10) {
System.out.println("Not Enough Names! Do it again!");
return;
}
/* Fill a String[] Array with the names in List but,
at the same time keep track of how many times a
specific name was in that list. We use a Map/HashMap
to hold the occurrences information. You really don't
need a String[] Array since the Map can take care of
everything but I thought you might want them separate. */
String[] names = new String[listModel.size()]; // Declare a String[] Array
Map<String, Integer> nameMap = new HashMap<>(); // Declare a Map
// Iterate through the List that was in the dialog using the List Model
for (int i = 0; i < listModel.size(); i++) {
// Get name from list at current index
names[i] = listModel.get(i);
// Is the name already in the Map?
if (nameMap.containsKey(names[i])) {
// Yes, it is ...
// Get the current number of times Count Value for that specific name
int value = nameMap.get(names[i]);
value++; // Increment that value by 1
nameMap.put(names[i], value); // Update the count value for that specific name.
}
else {
/* No, it isn't so add the Name as key and
a count value of 1 for the value. */
nameMap.put(names[i], 1);
}
}
/* Processing the name information is now complete,
we just need to diplay the acquired data now held
within the names[] Array and the nameMap Map. */
/* Display the oringinal list which is now
contained within the names[] String Array. */
for (int i = 0; i < names.length; i++) {
System.out.printf("%-12s%-15s%n", "Name #" + (i+1), names[i]);
}
System.out.println();
/* Now, display the occurrences for all those
names held within nameMap. */
String n;
int o;
for (Map.Entry<String,Integer> entry : nameMap.entrySet()) {
n = entry.getKey();
o = entry.getValue();
System.out.println(n + " appeared " + o
+ (o > 1 ? " times" : " time") + " in the List.");
}
System.out.println();
System.out.println("Process Completed.");
// DONE
If you run this code, your Console Window should display something like this:
Name #1 Bill
Name #2 Jane
Name #3 Marie
Name #4 Tracey
Name #5 Fred
Name #6 Bill
Name #7 Marie
Name #8 Doug
Name #9 Marie
Name #10 Tracey
Marie appeared 3 times in the List.
Bill appeared 2 times in the List.
Fred appeared 1 time in the List.
Jane appeared 1 time in the List.
Doug appeared 1 time in the List.
Tracey appeared 2 times in the List.
Process Completed.
EDIT: Based on comments!
Now that you have provided more info, here is one way it can be achieved. Again, read the comments in code:
public class Chapter4Act_Array {
public static void main(String[] args) {
String arrayOfNames[] = new String[10];
for (int i = 0; i < arrayOfNames.length; i++) {
// Letter case will be ignored during the occurrences processing.
arrayOfNames[i] = JOptionPane.showInputDialog(null, "Please Enter name #" + (i + 1) + ":", "Name",JOptionPane.QUESTION_MESSAGE);
}
System.out.println("Your friends are: ");
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.println(arrayOfNames[i]);
}
System.out.println();
/* List to keep track of the names we've already processed.
This will help to prevent printing the same Name more
than once. */
java.util.List<String> namesAlreadyProcessed = new java.util.ArrayList<>();
int counter;
for (int i = 0; i < arrayOfNames.length; i++) {
counter = 1;
for (int j = 0; j < arrayOfNames.length; j++) {
if (j == i) { continue; } // If we fall onto the same index then skip past it.
if (arrayOfNames[i].equalsIgnoreCase(arrayOfNames[j])) {
counter++;
}
}
/* If counter is greater than 1 then there has been
a name we've encountered more than once. Let's
display the number of times it was encountered
and add that name to namesAlreadyProcessed List. */
if (counter > 1) {
// Have we already processed this name?
boolean processed = false;
for (String name : namesAlreadyProcessed) {
if (name.equalsIgnoreCase(arrayOfNames[i])) {
// Yes, so skip printing the result again for this name.
processed = true;
break;
}
}
/* If No, then let's print the name and count result to
Console Window and add the name to our List. */
if (!processed) {
System.out.println(arrayOfNames[i] + " is in the List " + counter + " times.");
namesAlreadyProcessed.add(arrayOfNames[i]);
}
}
}
}
}
Beginner Java programmer here. I'm trying to create a card game to learn more about Java. I have an array of names I pulled out a database. For each String in the array I want to create a JPanel and inside JLabels where I will set the name, power, health, etc.
The problem is when I create these in a loop they all have the same name and overwrite each other. Since I read Java doesn't have dynamic Variable names, how do I solve this?
public void loadDatabaseCardElements(ArrayList cards) {
ArrayList<String> buildCards = cards;
int i;
for(i = 0; i != buildCards.size();) {
String var = buildCards.get(0);
//create the Panel etc
JPanel mainHolder = new JPanel();
mainHolder.setLayout(new BoxLayout(mainHolder, BoxLayout.PAGE_AXIS));
JLabel name = new JLabel("Name: " + var);
JLabel powerLabel = new JLabel("Power: ");
JLabel healthLabel = new JLabel("Health: ");
JLabel armorLabel = new JLabel("Armor: ");
JLabel type1Label = new JLabel("Type1");
JLabel type2Label = new JLabel("Type2: ");
JLabel ability1Label = new JLabel("Ability1: ");
JLabel ability2Label = new JLabel("Ability2: ");
JLabel ability3Label = new JLabel("Ability3: ");
JButton card1 = new JButton("Add to deck");
mainHolder.add(name);
mainHolder.add(powerLabel);
mainHolder.add(healthLabel);
mainHolder.add(armorLabel);
mainHolder.add(type1Label);
mainHolder.add(type2Label);
mainHolder.add(ability1Label);
mainHolder.add(ability2Label);
mainHolder.add(ability3Label);
mainHolder.add(card1);
mainHolder.setBorder(BorderFactory.createLineBorder(Color.black));
mainHolder.setPreferredSize( new Dimension( 130, 200 ) );
frame1.add(mainHolder, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(frame1);
card1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
preDeck.add(var); //add to another array when clicked
}
});
if (buildCards.size() != 0) {
buildCards.remove(0);
} else {
}
}
}
The reason for overwriting all the panels with same name is due to this part of your code:
int i;
for(i = 0; i != buildCards.size();) {
String var = buildCards.get(0);
You are assigning the first element of your list to each JLabel. This could help you achieve what you need:
for(int i = 0; i < buildCards.size(); i++){
String var = buildCards.get(i);
// Followed by your code
}
set a growable layout for a standard jpanel in the frame and then add a new jpanel to the standard jpanel every time. this should solve the naming problem. if u need access to each panel, you can store them in an array
I have a program that takes an input file, pulls a color word + hexadecimal value from it (for exaple Red 0xFF0000). I had my code working perfectly except I tried to replace my 2 arrayLists with a HashMap... That is where things took a wrong turn. I have my code back to what I believe it was before except now it is NOT changing colors when the radio buttons are pushed. Anyone want to take a peek?
public HashMapTests() {
JPanel p1 = new JPanel();
this.getContentPane().setLayout(new GridLayout(5,4));
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < colorCollection.size(); i++) {
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
}
for(int i = 0; i < colorCollection.size(); i++){
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
for (int j = 0; j < colorCollection.size(); j++){
String hexColor = hexCollection.get(j);
if(hexCollection.get(j).equals(((JRadioButton)e.getSource()).getText())){
getContentPane().setBackground(Color.decode(hexColor));
repaint();
}
}
}
});
}
add(p1);
}
First investigation:
while (colorCollection.size() < 10)
shall be replaced with
if (colorCollection.size() < 10)
Second observation:
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
The second line is useless, see constructor's javadoc.
Third:
The second loop where you attach the listener is useless, you can put this code to the first loop where you create a button.
Finally:
if (hexCollection.get(j).equals(((JRadioButton) e.getSource()).getText())) {
You compare here content of hexCollection with radio button text, but the button has label from colorCollection. I cannot look to your file but I think that this will be the problem.
Map Solution:
Initialization
String name = fileInput.next();
String hexValue = fileInput.next();
colors.put(name, hexValue);
Buttons
int i = 0;
for (String s : colors.keySet()) {
jrbColor[i] = new JRadioButton(s);
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String hexColor = colors.get(((JRadioButton) e.getSource()).getText());
getContentPane().setBackground(Color.decode(hexColor));
}
});
}
I'm new to Java and I am having some trouble with my assignment.
I have a Panel containing 100 JLabels:
for(int i=0;i<100;i++)
{
num[i] = new JLabel(""+i, JLabel.CENTER);
mainPanel.add(num[i]);
}
And a button to set image icon for the label when clicked
public void actionPerformed(ActionEvent ae)
{
int a = ran.nextInt(6) +1;//random number
int b +=a;
if(b>=100)
{
b=99;
num[b].setIcon(icon);
}
else
{
num[b].setIcon(icon);
}
}
How can i remove the icon from the last position and update it to a new position?
You can try to remember the index of the array of the label, for which you tried to set the icon.
For example-
int b = 0; // make b an instance variable
public void actionPerformed(ActionEvent ae)
{
int a = ran.nextInt(6) +1;//random number
num[b].setIcon(null); //remove the icon from from previously set label
b=a; //since b already has some value, b+=a might create unexpected result, hence just assigned a
if(b>=100)
{
b=99;
num[b].setIcon(icon);
}
else
{
num[b].setIcon(icon);
}
}
I have a method that returns an arraylist which i am calling via a buttonListener. I need to be able to store each pushes resulting arraylist in another arraylist. How do I do this? Each time i try, it copies over the existing elements in the arraylist I'm using to keep track of push results.
private class ButtonListener implements ActionListener{
public void actionPerformed (ActionEvent e){
numCounter++;
String reqVal1 = requestor.getText();
int reqVal = Integer.parseInt(reqVal1);
request = reqVal;
requestsArray.get(3).set(0,0);
if(numCounter == 1){//---------------------------numCounter == 1 beginning-------- -------------------------
workingVar = memSize/2;
if(request>workingVar){
requestsArray.get(3).set(0,1);
}
else{
reqCounter++;
while (workingVar>=request){
workingVar = workingVar/2;
holes2.add(workingVar);
}
if(workingVar<request){
workingVar=workingVar*2;
holes2.add(workingVar);
holes2.remove(holes2.size()-2);
holes2.remove(holes2.size()-1);
}
}
e1=workingVar;
}//-----------------------------------------------end of numCounter == 1 section-------------------------------------
if(numCounter > 1){
for (int y = 0; y<requestsArray.get(0).size();y++){
if(requestsArray.get(1).get(y).equals("H")){
holes.add((Integer)requestsArray.get(0).get(y));
}
}
//BubbleSort of holes ArrayList
int in, out;
for(out= holes.size()-1; out>0;out--)
for(in =0; in<out;in++)
if(holes.get(in)<holes.get(in+1)){
int temp1 = holes.get(in+1);
int temp2 = holes.get(in);
holes.set(in, temp1);
holes.set(in+1, temp2);
}
//calculates the value of e1 using holes array
if(holes.isEmpty()){
requestsArray.get(3).set(0, 1);
}
else{
for(element=holes.size()-1;element>-1;element--){//starts at end of holes array loops backwards
e1 = holes.get(element); //assigns value of each element to e1
if(e1>=request) //if value e1 is greater than request stop looping
break;
}
workingVar=e1; //assign the value of e1 to workingVar
if (request>e1){
requestsArray.get(3).set(0, 1);
}
else{
//---------------------code for populating holes2 array---------------------------
reqCounter++;
if(workingVar!=request && workingVar/2>=request){
while (workingVar/2>=request){
workingVar = workingVar/2;
holes2.add(workingVar);
}
if(workingVar<request){
workingVar=workingVar*2;
holes2.add(workingVar);
}
}
}
}
}
//Sort of Holes2 ArrayList - reorder's holes2 for initial set up and subsequent inserts
int in, out;
for(out= holes2.size()-1; out>0;out--)
for(in =0; in<out;in++)
if(holes2.get(in)>holes2.get(in+1)){
int temp1 = holes2.get(in+1);
int temp2 = holes2.get(in);
holes2.set(in, temp1);
holes2.set(in+1, temp2);
}
//-------------------------------requestsArray Setups----------------------------------------------------
//Initial setup of requestsArray
if(numCounter == 1){
if(requestsArray.get(3).get(0).equals(0)){
requestsArray.get(0).set(0,e1);
requestsArray.get(1).set(0,"R");
requestsArray.get(2).set(0, reqCounter);;
for(int i = 0; i<holes2.size();i++){
requestsArray.get(0).add(holes2.get(i));
requestsArray.get(1).add("H");
requestsArray.get(2).add(0);
}
}
else{
requestsArray.get(0).set(0,e1);
requestsArray.get(1).set(0, "H");
requestsArray.get(2).set(0,0);
}
}
//Subsequent setup of requestsArray
int element2;
if(numCounter >1 && requestsArray.get(3).get(0).equals(0)){
for(element2 = 0; element2< requestsArray.get(0).size(); element2++){
if((Integer)requestsArray.get(0).get(element2)==e1 &&requestsArray.get(1).get(element2).equals("H") ){
break;
}
}
if(holes2.isEmpty()){
requestsArray.get(1).set(element2, "R");
requestsArray.get(2).set(element2, reqCounter);
}
else{ //holes2 is not empty
requestsArray.get(0).add(element2, workingVar);
requestsArray.get(2).add(element2,reqCounter);
requestsArray.get(1).add(element2, "R");
requestsArray.get(0).remove(element2+1);
requestsArray.get(2).remove(element2+1);
requestsArray.get(1).remove(element2+1);
for(int i = 1; i<holes2.size()+1;i++){
requestsArray.get(0).add(element2+i,holes2.get(i-1));
requestsArray.get(1).add(element2+i,"H");
requestsArray.get(2).add(element2+i,0);
}
}
}
//-----------------End Section for populating requestsArraywhen numCounter > 1---------------------------
//remove all values from holes1 and holes2
holes.clear();
holes2.clear();
System.out.println(results1);
ok. I have written a similar program that is simpler and easier to understand. Each time the button is pressed, the result is saved as an arrayList to another arrayList. Problem is it's appending it to the previous element. I need to be able to add the results of each press as a separate element. For example:
first press:
[5, 3, 5, 2, 6, 5]
second press would display:
[5, 3, 5, 2, 6, 5][2, 1, 4, 1, 4, 1]
This way I can loop through and get each array result separately. How do I do this?
public class mainClass{
public static void main(String[] args){
JFrame frame1 = new JFrame("testButton");
frame1.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE);
buttonExample b1 = new buttonExample();
frame1.getContentPane().add(b1);
frame1.pack();
frame1.setVisible(true);
}
}
public class Example {
private int rand1;
private ArrayList<ArrayList> count;
private ArrayList<Integer> count2;
private Random rnd;
private int counter1;
private ArrayList<ArrayList>count3;
public Example(){
count = new ArrayList<ArrayList>();
count2 = new ArrayList<Integer>();
rnd = new Random();
count3 = new ArrayList<ArrayList>();
}
private void addCount2(){
for(int x = 0; x<6;x++){
rand1 = rnd.nextInt(6)+1;
count2.add(rand1);// count2 == Integers
}
}
public void addCount(){
addCount2();
count.add(count2);// count == count3
}
public ArrayList<ArrayList> displayCount(){
return count;
}
}
public class buttonExample extends JPanel {
private JButton button1;
private Example example1;
public buttonExample(){
button1 = new JButton("Submit");
add(button1);
button1.addActionListener(new ButtonListener());
example1 = new Example();
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
example1.addCount();
System.out.println(example1.displayCount().get(0));;
}
}
}
I would think about at least two solutions...
create a List<...> list which will last (global variable or something similar, depends on your needs) and use list.addAll() method
create a Map<String, List<...> map and than you can log your lists separately, your key might be a timestamp for example
Well, now when you posted the code you will have to start with a different thing - refactoring. Your code is very long, difficult to read and error prone. You have to think about it a little bit a rewrite it. And trust me, the more effort you put into your code at the beginning the better it will be at the end. Otherwise you may end up with an unmanagable code full of bugs...