Java call objects by there name and use them - java

I am wondering how I can change my objects individually when giving them a name (setName) seen below.
Code:
//textfield & labels
String[] arrLabelsKlanten = new String[] {"KlantID", "Gebruikersnaam", "Wachtwoord", "Voornaam", "Achternaam", "Straat", "Huisnummer", "Gemeente", "Email", "Telefoonnr"};
for (int i = 0; i < arrLabelsKlanten.length; i++)
{
if(i < 5)
{
lblLabelsKlanten = new ClassLabels.lblIngelogdAls(arrLabelsKlanten[i] + ":", 350, 510 + i * 50, 300, 50);
lblLabelsKlanten.setName(String.valueOf(i));
add(lblLabelsKlanten);
txtTextvakken = new ClassTextfields.txtAdmin(500, 515 + i * 50, 300, 30);
txtTextvakken.setName(String.valueOf(i));
add(txtTextvakken);
}else if (i >= 5)
{
lblLabelsKlanten = new ClassLabels.lblIngelogdAls(arrLabelsKlanten[i] + ":", 910, 260 + i * 50, 300, 50);
lblLabelsKlanten.setName(String.valueOf(i));
add(lblLabelsKlanten);
txtTextvakken = new ClassTextfields.txtAdmin(1050, 265 + i * 50, 300, 30);
txtTextvakken.setName(String.valueOf(i));
add(txtTextvakken);
}
}
}

Your strings are stored in an array named lblLabelKlanten, the valueOf(i) is your iterator, not the array.
lblLabelKlanten.setName(arrLabalKlanten[i]); should get you the String inside your array, and set the name of your object to the string value.
at least I think that is the question you are asking?

Related

How to get a random number in one statement from a list of values;

Given the code below I have to find a way to get a random value from the values: 100, 120, 140, 160, 180, 200, 220, 240, 260, 280. The catch is that I have to write a single statement (One semi-colon) that will randomly pick one of the ints and assign it into the random_int variable. Does anyone have any idea how I could create a list or array of the numbers above and pick a random int from the numbers to assign to random_int in a single statement? Thank you for the help!
public static void main(String[] args) {
Random random = new Random();
int random_int;
// Your single statement goes here
System.out.println(“Number is: “ + random_int);
}
You can do something like:
public static void main(String[] args) {
Random random = new Random();
List<Integer> integerList = Arrays.asList(100, 120, 140, 160, 180, 200, 220, 240, 260, 280);
System.out.println(integerList.get(random.nextInt(integerList.size())));
}
You can make use of the Arrays class to create a collection from your array
System.out.println(Arrays.asList(100, 120, 140, 160, 180, 200, 220, 240, 260, 280).
get(new Random().nextInt(10)));
Push them all into an array and random the array's index. All can be done in one single statement:
public static void main(String[] args) {
Random random = new Random();
int random_int = new int[]{100, 120, 140, 160, 180, 200, 220, 240, 260, 280}[random.nextInt(10)];
System.out.println("Number is: " + random_int);
}
public class Foo {
public static void main(String[] args) {
for (int i = 0; i < NUMBERS.size(); i++)
System.out.println(getRandomNumber());
}
private static final List<Integer> NUMBERS = Arrays.asList(100, 120, 140, 160, 180, 200, 220, 240, 260, 280);
public static int getRandomNumber() {
Collections.shuffle(NUMBERS);
return NUMBERS.get(0);
}
}
int random_int = new Random().nextInt(10)*20 + 100;
int random_int = (new Random().nextInt(10) + 5)*20;
nextInt(10) will give 0..9. (9 = (280 - 100)/20).
It is a matter of seeing the regularities in the desired numbers: steps of 20, starting with 100 upto 280.
Could have been an exam question.
Given below can be the single statement to do the job:
random_int = List.of(100, 120, 140, 160, 180, 200, 220, 240, 260, 280)
.get(random.nextInt(List.of(100, 120, 140, 160, 180, 200, 220, 240, 260, 280).size()));
Explanation:
Random#nextInt(int bound) returns an int value between 0 (inclusive) and bound (exclusive).
List#get(int index) returns the element at the specified position in this list.
List#size() returns the number of elements in this list.

tooltip hover just works sometimes

I am trying to implement a Tooltip in a loop, for displaying some words after hovering over a rectangle. The problem is that, the words just show up once in a while (sometimes even without a delay, sometimes not even after waiting for a minute). When I put the tooltip statement outside of the loop the words always show up (with a short delay), but I need the statement inside. Any idea what causes the problem?
for (int i = 0; i < finalList.size(); i++) {
for (int j = 0; j < names.getName().size(); j++) {
Label number = new Label(" " + finalList.get(i).get(j).getNamesFrequencySection());
Rectangle rec = new Rectangle();
rec.setY(j * 20 + 20);
rec.setX(i * 80 + 100);
rec.setWidth(80);
rec.setHeight(20);
if (finalList.get(i).get(j).getNamesFrequencySection() == 0) {
rec.setFill(Color.rgb(255, 255, 255));
}
else {
rec.setFill(Color.rgb(250 - (3 * finalList.get(i).get(j).getNamesFrequencySection()), 0, 0));
}
number.setLayoutY(j * 20 + 20);
number.setLayoutX(i * 80 + 130);
root.getChildren().add(rec);
root.getChildren().add(number);
Tooltip.install(rec, new Tooltip(finalList.get(i).get(j).getMostCommon().replaceAll("[^a-zA-Z ]","")));
}
}
NamesFrequency is an Integer and getMostCommon() is the String of the words.

Difficulty initiating Random with Float to Integer

For my program, I am trying to get a random range with variables I can input, but it seems to cause the program to crash when I try to work it. I have pinpointed where the main problem is, though:
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import java.util.Random;
public class main {
private static Text attackBox;
private static Text cooldownBox;
private static Text ammoBox;
private static Text stabilityBox;
static int attack = 0;
static int ammo = 0;
static int stability = 0;
static int damage = 0;
static int damageRaw = 0;
static int minuteDamage = 0;
static int minuteDamageRaw = 0;
static float attacksPerMinute = 0;
static float cooldown = 0;
static Random rand;
/**
* Launch the application.
* #param args
*/
public static void main(String[] args) {
Display display = Display.getDefault();
Shell shell = new Shell();
shell.setSize(450, 269);
shell.setText("Xenolbade X DPS Calculation");
shell.setLayout(null);
Label lblAttack = new Label(shell, SWT.NONE);
lblAttack.setBounds(10, 10, 69, 15);
lblAttack.setText("Attack:");
Label lblCooldown = new Label(shell, SWT.NONE);
lblCooldown.setBounds(10, 31, 69, 15);
lblCooldown.setText("Cooldown: ");
Label lblAmmo = new Label(shell, SWT.NONE);
lblAmmo.setBounds(10, 52, 69, 15);
lblAmmo.setText("Ammo:");
Label lblStability = new Label(shell, SWT.NONE);
lblStability.setBounds(10, 73, 69, 15);
lblStability.setText("Stability: \u00B1");
attackBox = new Text(shell, SWT.BORDER);
attackBox.setText("0");
attackBox.setBounds(85, 10, 76, 21);
cooldownBox = new Text(shell, SWT.BORDER);
cooldownBox.setText("0");
cooldownBox.setBounds(85, 31, 76, 21);
ammoBox = new Text(shell, SWT.BORDER);
ammoBox.setText("0");
ammoBox.setBounds(85, 52, 76, 21);
stabilityBox = new Text(shell, SWT.BORDER);
stabilityBox.setText("0");
stabilityBox.setBounds(85, 73, 76, 21);
Label label = new Label(shell, SWT.NONE);
label.setBounds(10, 94, 414, 15);
label.setText("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
Label lblWithoutStability = new Label(shell, SWT.NONE);
lblWithoutStability.setBounds(10, 115, 414, 15);
lblWithoutStability.setText("Within a minute, without stability, your weapon would do:");
Label rawDamageLabel = new Label(shell, SWT.NONE);
rawDamageLabel.setBounds(10, 136, 414, 30);
rawDamageLabel.setText(damageRaw + " damage " + (int)attacksPerMinute + " times for a total of "
+ minuteDamageRaw + " damage per minute.");
Label lblNewLabel_1 = new Label(shell, SWT.NONE);
lblNewLabel_1.setBounds(10, 172, 414, 15);
lblNewLabel_1.setText("If we include the stability, we can estimate a minute of combat to do:");
Label stabilityDamageLabel = new Label(shell, SWT.NONE);
stabilityDamageLabel.setBounds(10, 193, 414, 30);
stabilityDamageLabel.setText(damage + " damage " + (int)attacksPerMinute + " times for a total of "
+ minuteDamage + " damage per minute.");
Button runButton = new Button(shell, SWT.NONE);
runButton.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
damage = 0;
damageRaw = 0;
minuteDamage = 0;
minuteDamageRaw = 0;
attack = Integer.valueOf(attackBox.getText());
cooldown = Float.valueOf(cooldownBox.getText());
ammo = Integer.valueOf(ammoBox.getText());
stability = Integer.valueOf(stabilityBox.getText());
attacksPerMinute = 60 / cooldown;
damageRaw = attack * ammo;
minuteDamageRaw = damageRaw * (int)attacksPerMinute;
rawDamageLabel.setText(damageRaw + " damage " + (int)attacksPerMinute + " times for a total of "
+ minuteDamageRaw + " damage per minute.");
float flux = stability/100;
int max = (int)(attack * (1 + flux));
int min = (int)(attack * (1 - flux));
System.out.println(min);
System.out.println(max);
for (int i = 0; i < attacksPerMinute; ++i) {
damage = 0;
for (int j = 0; j < ammo; ++j) {
damage += damageFlux(min, max);
//
}
minuteDamage += damage;
}
stabilityDamageLabel.setText(damage + " damage " + (int)attacksPerMinute + " times for a total of "
+ minuteDamage + " damage per minute.");
}
});
runButton.setBounds(349, 10, 75, 25);
runButton.setText("Open Fire!");
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
private static int damageFlux(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
}
T
The error:
Exception in thread "main" java.lang.IllegalArgumentException: max must be greater than min
at main.damageFlux(main.java:144)
at main.access$4(main.java:141)
at main$1.widgetSelected(main.java:120)
at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:249)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:86)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4428)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4238)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3817)
at main.main(main.java:135)
Now, in my head, the min and max should work, but its not. It causes the error to be thrown, most likely because its not doing the math to cause the pair to be different. Here are a couple variables on how it should work:
If attack is 10 and the flux is .20, then max should be (10 * (1 + .20) = 12 and min should be (10 * (1 - .20) = 8. However, if I am getting the error thrown by the damageFlux call, then it means they are matching the same value. by doing a System.out.println on the min and max, they are both returning as 10 instead of 8 and 12.
You should change float flux = stability/100; to float flux = stability/100.0f;.
That way, by having a float in the operation, you promote the division's result to a float. Your actual code makes it so that stability, an int, divided by 100 an other int, results in a rounded answer. Judging by your examples, the result of that is closer to 0 so when that's the case, your next operations with flux become:
int max = (int)(attack * (1 + 0));
int min = (int)(attack * (1 - 0));
Which is why you see 10 in both variables.
For more info, please see: Java implicit conversion
It seems that variable attack is negative. You get it from the UI.
BTW: Add to error message values of min and max. It makes easier debugging

Adding JLabel dynamically in a pattern but last one is not working correctly

I'm trying to creating 40 dynamical JLabels in a pattern, which is working quite good but the last JLabel is not placing according to the pattern. Can anyone tell me what I did wrong ?
Here what I have done so far:
public class Booking2 {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(700, 400);
jf.setLocationRelativeTo(null);
int c1 = 40;
int count = 0, count2 = 0, count3 = 0, count4 = 0, x;
JLabel[] jl = new JLabel[c1];
for (int i = 0; i <= c1 - 1; i++) {
jl[i] = new JLabel();
if (i <= 9) {
x = 25 * count;
jl[i].setBounds(x, 50, 20, 30);
count++;
}
if (i >= 10 && i <= 19) {
x = 25 * count2;
jl[i].setBounds(x, 80, 20, 20);
count2++;
}
if (i >= 20 && i <= 29) {
x = 25 * count3;
jl[i].setBounds(x, 110, 20, 20);
count3++;
}
if (i >= 30 && i <= 39) {
x = 25 * count4;
jl[i].setBounds(x, 130, 20, 20);
count4++;
}
// jl[i].setIcon(new
// ImageIcon(Booking2.class.getResource("booked.png")));
jl[i].setText("O");
jf.add(jl[i]);
}
}
}
you are using absolute positioning / null layout but you haven't set layout to null .default layout of jframe is Border layout.
add this line
jf.setLayout(null);
and after you add all components call revalidate() and repaint() method of jframe.
example
public class Booking2 {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setLayout(null); // this is important
jf.setSize(700, 400);
int c1 = 40;
int count = 0, count2 = 0, count3 = 0, count4 = 0, x;
JLabel[] jl = new JLabel[c1];
for (int i = 0; i <= c1 - 1; i++) {
jl[i] = new JLabel();
if (i <= 9) {
x = 25 * count;
jl[i].setBounds(x, 50, 20, 20);
count++;
}
if (i >= 10 && i <= 19) {
x = 25 * count2;
jl[i].setBounds(x, 80, 20, 20);
count2++;
}
if (i >= 20 && i <= 29) {
x = 25 * count3;
jl[i].setBounds(x, 110, 20, 20);
count3++;
}
if (i >= 30 && i <= 39) {
x = 25 * count4;
jl[i].setBounds(x, 130, 20, 20);
count4++;
}
//jl[i].setIcon(new ImageIcon(Booking2.class.getResource("booked.png")));
jl[i].setText("O");
jf.add(jl[i]);
}
jf.revalidate();
jf.setVisible(true);
}
}
output
Note
1) you should avoid null layout .use a layout GRID layout seems good for your case .and also if this is a kind of a game /animation you should look at these example https://www3.ntu.edu.sg/home/ehchua/programming/java/J8a_GameIntro-BouncingBalls.html. you can use paintComponent() method to draw this grid in a jpanel which is efficient and you can draw any kind of pattern .think if you make a big grid,for instance 100*100 using jlables it's not good
2) it's better to add components to jpanel instead of add directly to jframe .you can use setContentPane() method for that
It would be much better to use layout, for example GridLayout:
import javax.swing.*;
import java.awt.*;
public class Booking2 {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setLayout(new GridLayout(4,10));
jf.setSize(700, 400);
jf.setLocationRelativeTo(null);
int c1=40;
JLabel[] jl = new JLabel[c1];
for(int i=c1-1; i>=0; i--){
jl[i]=new JLabel();
jl[i].setText("O");
jf.add(jl[i]);
}
}
}
It is more elegant way. But, if you are determined to use setBound() you should set JFrame (or other container with your JLabels) layout to null:
jf.setLayout(null);
This will allow for absolute positioning inside container. It seems that default JFrames BorderLoyout distorted your setBounds() settings.
However it is generally not recomended to use null layout, and it is considered a bad programming practice. It is better idea to use LayoutMenagers!

Hangman Graphics

I'm having trouble getting the graphics to show up with my hangman program.
This is the code for my engine class:
public static void main(String[] args)
{
//hangman viewer stuff
//////////////////////////////////////////////////////////////
JFrame frame = new JFrame();
frame.setSize(200,375); //invoked the method setSize on the implicit parameter frame
frame.setTitle("Hangman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
HangmanComponent g = new HangmanComponent();
frame.add(g);
frame.setVisible(true);
///////////////////////////////////////////////////////////////
String wordd = JOptionPane.showInputDialog("Type in a word.");
int length = wordd.length();
String blank = "_ ";
String word2 = new String("");
int guesscount = 10;
ArrayList<String>answers=new ArrayList<String>(); //creates reference to empty structure that will contain references
char blanks[]=new char[wordd.length()]; //creates an array with the same number of terms as the length of the word
for (int i=0; i<length; i++)//fills the array with blanks corresponding to the length of the word
{
blanks[i] = '_';
}
HangmanComponent y = new HangmanComponent();
while (true)
{
String letter = JOptionPane.showInputDialog("Guess a letter! You have "+guesscount+" guesses."+"\n"+answers+"\n"+Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")); //Prints a space
char letterchar = letter.charAt(0); //converts string letter to char letterchar
int idx = 0;
boolean found = false;
answers.add(letter); //adds the string to the arraylist answers
while (idx >= 0 && idx < length) //idx is greater than or equal to 0 but less than the length of the word
{
//System.out.println("idx = " + idx);
idx = wordd.indexOf(letter, idx); //idx is the index of "letter" in "wordd" and finds all instances of the letter
//System.out.println("idx = " + idx + ", guesscount = " + guesscount);
if (idx != -1) //if idx is not -1 (the letter exists in the word)
{
found = true;
blanks[idx] = letterchar; //sets the term in the array equal to the letter
idx += 1; //idx=idx+1
}
else
{
guesscount=guesscount-1;
y.nextStage();
y.printStage();
frame.add(y);
frame.setVisible(true);
break;
}
}
if (found)
{
JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"You found a letter!"+"\n"+answers);
}
else
{
JOptionPane.showMessageDialog(null, Arrays.toString(blanks).replace(",", " ").replace("[","").replace("]","")+"\n"+"That letter is not in the word! Guess again!"+"\n"+answers);
if (guesscount == 0)
{
JOptionPane.showMessageDialog(null, "Sorry, you're all out of guesses. The answer was '"+wordd+".' Thanks for playing!");
break;
}
}
char [] lettersArray = wordd.toCharArray(); //converts word to array of chars
if (Arrays.equals(blanks, lettersArray))//compares array of blanks to array of letters
{
JOptionPane.showMessageDialog(null, "You guessed the word! Thanks for playing!");
break;
}
}
}
and this is the code for my HangmanComponent class (with the graphics)
int stage=0;
public void nextStage()
{
stage++;
}
public void printStage()
{
System.out.println("Your stage number is:"+stage);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(5,BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
g2.setColor(Color.BLACK);
g.drawLine(50, 30, 50, 10);
g.drawLine(50, 10, 130, 10);
g.drawLine(130, 10, 130, 300);
g.drawLine(20, 300, 150, 300);
if (stage==1)
{
//draws the head
g2.setStroke(new BasicStroke(3,BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
Ellipse2D.Double head = new Ellipse2D.Double(25, 30, 50, 50);
g2.draw(head);
}
else if (stage==2)
{
//draws the body
g.drawLine(50, 80, 50, 180);
}
else if (stage==3)
{
//draws the left arm
g.drawLine(10, 150, 50, 100);
}
else if (stage==4)
{
//draws the right arm
g.drawLine(50, 100, 90, 150);
}
else if (stage==5)
{
//draws the left leg
g.drawLine(30, 250, 50, 180);
}
else if (stage==6)
{
//draws the right leg
g.drawLine(50, 180, 70, 250);
}
else if (stage==7)
{
//draws the left eye
Ellipse2D.Double lefteye = new Ellipse2D.Double(40, 50, 1, 1);
g2.draw(lefteye);
g2.fill(lefteye);
}
else if (stage==8)
{
//draws the right eye
Ellipse2D.Double righteye = new Ellipse2D.Double(58, 50, 1, 1);
g2.draw(righteye);
g2.fill(righteye);
}
else if (stage==9)
{
//draws the mouth
Arc2D.Double mouth = new Arc2D.Double(40.00, 50.00, 20.00, 20.00, 180.00, 190.00, Arc2D.OPEN);
g2.draw(mouth);
}
}
Right now, the hangman program runs perfectly fine, but the graphic is only added the first time the user inputs a wrong letter. How do I get the graphics to be inputted for every time a wrong letter is inputted?

Categories

Resources