I have 34 labels with images i can't figure how do i make when ill click the label itself to get selected and in the down right corner that "Selected: " to get changed on every label select.
The labels variable names are from n1 to n34 i have this code so far but in the list getSelectedNumbers()
List<JLabel> lotteryBoxes = new ArrayList<>();
List<JLabel> getSelectedNumbers() {
List<JLabel> numbers = new ArrayList<>();
Iterator<JLabel> it = lotteryBoxes.iterator();
while (it.hasNext()) {
JLabel nr = it.next();
if (nr.isCursorSet()) {
numbers.add(nr);
Selected.setText("Selected: " + nr);
}
return numbers;
}
I do not know what to do, please give me some answers.
If you create the labels in a loop, you can add a handler to them. Either the same handler that checks which of the labels was clicked, or a separate handler for each one.
Here there is a separate handler for each and the labels are put into an array so you can use them later (outside the loop).
int numberOfLabels = 34;
JLabel[] labels = new JLabel[numberOfLabels];
for (int index=0; index<numberOfLabels; index++) {
String labelText = "" + (index + 1);
final JLabel label = new JLabel(labelText));
final int labelNumber = index + 1;
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// do something, you can use "label" in here, eg:
selected.setText(label.getText());
// you have access to the number in "labelNumber"
}
});
somePanel.add(label);
labels[index] = label; // save the label if you need to access it later
}
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]);
}
}
}
}
}
I am currently trying to place individual items within an array list into individual tiles within a inventory GUI. All the tiles are set up and I can display each array list item individually within the console line.
This is the simple GUI:
This is my attempt so far.
HBox itemTile[] = new HBox[31];
for (int i = 0; i < 30; i++) {
Button deleteButton = new Button("Delete Item");
deleteButton.setOnAction((ActionEvent event) -> {
displayItems2(); //temp info to console - delete item code to be added
JOptionPane.showMessageDialog(null, "Item has been deleted", null, 1);
});
itemTile[i] = new HBox(new Label("Item: " + i + " "));
itemTile[i].setStyle("-fx-border-color: black;");
itemTile[i].setPadding(new Insets(5));
itemTile[i].getChildren().add(deleteButton);
itemTile[i].setAlignment(Pos.CENTER_LEFT);
itemTile[i].setStyle("-fx-background-color: #e5efff; -fx-border-color: black;");
this.getChildren().add(itemTile[i]);
}
}
private void displayItems2(){
this.getChildren().removeAll(this.getChildren());
displayInvStructure();
ArrayList<String> descs = InventoryManager.getInstance().getItemDescriptions();
for (int i = 0; i < descs.size(); i++) {
String retString = descs.get(i);
System.out.println("Array item is = " + " " + i + " " + retString);
}
//If i = itemTile[i]
//Add retString to itemTile[i]
}
How do I place each individual retString into each tile using the itemTile[i]?
I'm relatively new to coding and Java, so I have a sneaking suspicion I am over complicating things.
If you want to assign values to the itemTile array inside a method like displayItems2, there are two possibilities: 1) pass a reference to itemTile into displayItems2 or 2) make itemTile a class member.
Example 1 (pass a reference):
private void displayItems2(HBox itemTile) {
// [...]
itemTile[i] = descs.get(i);
}
Example 2 (class member):
class MyClass {
// [...]
HBox itemTile;
// [...]
private void displayItems2() {
// [...]
itemTile[i] = descs.get(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
public class Chap extends Frame implements ActionListener
{
private Button keys[];
private Panel keypad;
private Panel fields;
private TextField nameField;
private TextField numberField;
private String name;
private int number;
private boolean clearText;
private boolean foundKey;
Button enterButton = new Button("Enter");
Button clearButton = new Button("Clear");
Button printButton = new Button("Print");
String names, numbers;
String ArrayValues[][] = new String[10][2];
public Chap()
{
enterButton.addActionListener(this);
clearButton.addActionListener(this);
printButton.addActionListener(this);
enterButton.setActionCommand("Enter");
clearButton.setActionCommand("Clear");
printButton.setActionCommand("Print");
// construct components and initialize beginning values
nameField = new TextField(20);
numberField = new TextField(20);
nameField.setEditable(true);
numberField.setEditable(false);
keypad = new Panel();
fields = new Panel();
keys = new Button[10];
number = 0;
name = "";
clearText = true;
fields.add(nameField);
fields.add(numberField);
fields.add(enterButton);
fields.add(clearButton);
fields.add(printButton);
public void actionPerformed(ActionEvent e)
{
if(arg == "About")
{
String message = "Program";
JOptionPane.showMessageDialog(null,message,"About Program",JOptionPane.INFORMATION_MESSAGE);
}
if(arg == "Enter")
{
for (int counter = 0; counter < 10; counter ++)
{
}
}
if(arg == "Print")
{
JOptionPane.showMessageDialog(null,ArrayValues,"Info",JOptionPane.INFORMATION_MESSAGE);
}
i have to create a program that store up to 10 phone numbers and names. once the user clicks print, all of the stored data should be displayed. i'm unsure of how to store the data in the array. the name field is editable, while the number field is only able to accessed through the numeric keypad
You could use LinkedHashMap for this, here is an example:
LinkedHashMap<String, String> test = new LinkedHashMap<String, String>();
test.put("Dan", "867-5309");
test.put("Sam", "123-4567");
for(String key : test.keySet()) {
System.out.println(key + "'s phone number is " + test.get(key));
}
Which will print:
Dan's phone number is 867-5309
Sam's phone number is 123-4567
The difference between LinkedHashMap and just plain ol' HashMap is that LinkedHashMap maintains the order of the "keys" as you put them in, HashMap disregards the order completely.
Not sure what exactly you mean, but this might help you get the logic:
String[] arr=new String[10] // to store 10 phone numbers
to add elements to array:
arr[i]=numberField.getText();
set counter on "i" for each Action Event. Then print the array elements using loop.
I have a button. If I click this button, a popup appears. The popup asking me to write a word. if I write a word 6 letter, 6 jlabels appear, but if I enter another word shorter, the JLabels do not disappear
I want my JLabels may decrease according to a shorter word, but i don't know :(
thx for your great help !
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//BUTTON 1 WORD
Controller c = new Controller();
try {
final JFrame popup = new JFrame();
//display popup
word = JOptionPane.showInputDialog(popup, "Enter one word", null);
//control the length of the word
c.controleW(word);
//display jlabel lenght of word
keyNumber.setText(String.valueOf(word.length()));
//JLabels displays depending on the word length
int pixels = 50;
for (int i = 0; i < word.length(); i++) {
label = new JLabel("_");
label.setBounds(pixels, 200, 30, 30);
add(label);
label.repaint();
pixels += 20;
}
} catch (Exception e) {
System.out.println(e);
}
}
And my class to control the length of the word
public String controleW(String word) {
boolean flag = false;
final JFrame popup = new JFrame();
while (flag == false) {
if (word.length() <= 3) {
word = JOptionPane.showInputDialog(popup, "Enter one word", null);
} else {
flag = true;
}
};
return null;
}
You are always adding labels in your method, never removing any, thus running the code twice will indeed add labels twice. To fix it, you can simply add a removeAll(); in jButton1ActionPerformed before you add any labels. This makes sure that any previously added components will be removed.