I am trying to Randomize the colors automatically on a single button click. I am able to randomize and display the background color, but I have to click the button each time to get a different color. I am trying to click the button once and it automatically loop through the array and display the colors automatically. I know I need some form of loop around the array, but I have no clue where to put it.
private View windowView;
private Button clickMe;
private int[colors];
colors=new int[]{Color.CYAN, Color.GREEN, Color.RED};
for (int i = 0; i < colors.length; i++) {
Random random = new Random();
int randomNum = random.nextInt(colorArrayLength);
windowView.setBackgroundColor(colors[randomNum]);
}
I do not understand why this is not looping through the array. Any hints and assistance would be much appreciated.
I believe you are randomly selecting the color and setting it in the background. However as it is inside a loop, it is changing so fast that the change is not notable in the visual rendering. You need to pause few milliseconds to see the change visually.
You may try out out the following:
private View windowView;
private Button clickMe;
private int[colors];
colors=new int[]{Color.CYAN, Color.GREEN, Color.RED};
final int[] finalColors = colors;
final View finalWindowView = windowView;
for (int i = 0; i < finalColors.length; i++) {
Random random = new Random();
final int randomNum = random.nextInt(finalColors.length);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Do after 500ms
finalWindowView.setBackgroundColor(colors[randomNum]);
}
}, 500 * i);
}
Try out this it will helpful to you
private int getMatColor(String typeColor)
{
int returnColor = Color.BLACK;
int arrayId = getResources().getIdentifier("mdcolor_" + typeColor, "array", getApplicationContext().getPackageName());
if (arrayId != 0)
{
TypedArray colors = getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.BLACK);
colors.recycle();
}
return returnColor;
}
Your code isn't really randomizing an array, but simply picking a random color from your array.
There's a slight difference in this. Randomizing an array means the order of every item in your array becomes randomized. There is no way for repeats to be possible for this.
Whereas, randomly selecting a color from your array might make it possible for you to have the same color selected.
What you're doing is the latter and it's doing that task properly.
Therefore, your code isn't considered looping through an array. You're simply selecting a random color from the array for n number of times, with n being the size of your array.
Additionally, the colors you're randomly picking aren't displaying to windowView because the colors are being changed immediately.
For example, your for loop might turn windowView to CYAN, but immediately afterwards the loop will change it to RED. Thus, it'll only display the very last random value that is selected from your array and you won't see any of the previous color changes.
If you want to see the changes, you need to add a delay between each random color change.
What's colorArrayLength? no this variable. Codes like below are run normally.
for (int i = 0; i < colors.length; i++) {
Random random = new Random();
int randomNum = random.nextInt(colors.length);
button.setBackgroundColor(colors[randomNum]);
}
But even this, the view's background color is the last color after loop, you can not see the result of color looping effect. If you want to see the process of color changing, maybe add Timer.schedule() method.
Related
I'm developing a chat application, for this, I'm in need of generation random colour for the user profile picture. But I need to generate the same colour for the same person. I have a unique user id. I don't like to save the colour code after generating the colour code once. So, basically I need an method to get colour code.
int getUserColourCode(String userId) {
//code needed.
//It should return random colour code (int) with respect to user id.
//I would like to exclude light shade colours (dark and semi dark colours are preferred).
}
Thanks in advance.
int getUserColourCode(String userId) {
StringBuilder input1 = new StringBuilder();
input1.append(userId);
input1=input1.reverse();
String pair[]={"0","0","0","0","0","0","0","0"};
char[] character = input1.toString().toCharArray();
for(int i=0;i<character.length;i++)
{
pair[i]=String.valueOf(character[i]);
}
int color = Color.argb((Integer.parseInt(pair[0]+pair[1])*2)+50, (Integer.parseInt(pair[2]+pair[3])*2)+50, (Integer.parseInt(pair[4]+pair[5])*2)+50, (Integer.parseInt(pair[6]+pair[7])*2)+50);
return color;
}
First, you need to pass integer as the argument of you function. Instead of String userId, please use int userId. If you still want to pass String type as the argument, you need to parse it to integer.
Second, you need to define all the colors you want in an array.
Basically you can not use Java Random number build in function because it will always generate new random number, so it will not match with your need.
int getUserColourCode(String userId) {
int id = Integer.parseInt(userId);
//create integer color as much as you want,
int[] colors = {Color.BLUE, Color.CYAN, Color.MAGENTA, Color.parseColor("#ff00f8")};
int colorLength = colors.length - 1;
int randomNumber = id % colorLength;
return colors[randomNumber];
}
If you pass integer as the type of your argument you can use this:
int getUserColourCode(int userId) {
//create integer color as much as you want,
int[] colors = {Color.BLUE, Color.CYAN, Color.MAGENTA, Color.parseColor("#ff00f8")};
int colorLength = colors.length - 1;
int randomNumber = userId % colorLength;
return colors[randomNumber];
}
Using this you can generate random colors from color code,
But if you need to get color from the user you need shared preference value for the local database to save the color of the user
int getUserColourCode(String userId) {
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
return color;
}
What I have done.
I have created an array of JLabel like that:
static JLabel numbers[] = new JLabel[25];
I Have given to each of the numbers[each of this] a random number between 1 and 80.
I have added to each of numbers[] array a MouseListener.
I want to make something like, once I press a specific label to change itself background. But to do that I have to detect the ID of the JLabel has been pressed.
The Question:
How can I get the name or the number of the array on JLabel that has been pressed?
So far I only know how to get the text from it with the following code:
JLabel l = (JLabel) e.getSource();
int strNumber = Integer.parseInt(l.getText());
I want the ID of numbers[THIS], not the text but the number of array.
In Button listener, I know how to do that, but in MouseListener is not working...
(At least with the methods I tried to...(e.getSource().getName(); etc.)
You've got the array, you've got a reference to the pressed JLabel: e.getSource();, so simply iterate through the array to find the one that matches the other. e.g.,
#Override
public void mousePressed(MouseEvent e) {
Object source = e.getSource();
int index = -1;
for (int i = 0; i < numbers.length; numbers++) {
if (numbers[i] == source) {
index = i;
break;
}
}
}
// here index either == the array item of interest or -1 if no match
Side issue: that array should not be static, and that it is static suggests that you have some design issues with your program that need to be fixed.
So I have this 2d array of buttons and I have an array of images. I want to get the images on the buttons but I want the images to be on random buttons every time the program starts. Like this:What I want it to look like. Right now I can only get one color to be on all of the buttons by changing the value of icons when I make the new JButton. What I think I need to do is have Math.Random() set to a variable and to get a random value from the array of images and then put the variable in icons[] when i declare the new JButton but I don't know if this is right and don't know how to do it. I did some searching and tried using this:
var randomValue = icons[Math.floor(Math.random() * icons.length)];
but I get an error saying
possible loss of precision, required int, found double.
Help would be greatly appreciated. If you want me to post the entire code let me know.
// 2D Array of buttons
buttons = new JButton[8][8];
for(int row=0; row<8; row++)
{
for (int col=0; col<8; col++)
{
buttons[row][col] = new JButton(icons[0]);
buttons[row][col].setLocation(6+col*70, 6+row*70);
buttons[row][col].setSize(69,69);
getContentPane().add(buttons[row][col]);
}
}
// Array of images
public static ImageIcon[] icons = {new ImageIcon("RedButton.png"),
new ImageIcon("OrangeButton.png"),
new ImageIcon("YellowButton.png"),
new ImageIcon("GreenButton.png"),
new ImageIcon("BlueButton.png"),
new ImageIcon("LightGrayButton.png"),
new ImageIcon("DarkGrayButton.png")};
I'd simplify this greatly by putting all my ImageIcons in an ArrayList, calling java.util.Collections.shuffle(...) on the ArrayList, and then passing out the ImageIcons from the shuffled ArrayList in order. Or if your buttons allow for repeated icons, then use a java.util.Random variable, say called random and simply call random.nextInt(icons.length) to get a random index for my array.
As an aside, please for your own sake, don't use null layout and absolute positioning. Your grid of JButtons is begging to be held in a GridLayout-using JPanel. Begging.
As an aside, why are you posting questions on the same project but using different names? You've similar posts but different user names in both of your other posts here:
JButtons won't update on button click
My New Game JButton is not working?
Before you set the icons on the JButton use this shuffle function...
public ImageIcon[] shuffle(ImageIcon[] icons)
{
int index = 0;
ImageIcon temp = 0;
for(int i = icons.length -1; i > 0; i--)
{
index = r.nextInt(i + 1);
temp = icons[index];
icons[index] = icons[i];
icons[i] = temp;
}
return icons;
}
I have a GUI, from this GUI I choose an input file with the dimensions of a Booking system(new GUI) If the plane has 100 seats the GUI will be for example 10x10, if the plane has 200 seats it will be 10x20, all the seats are going to be buttons, and should store passenger information on them if they are booked.Also a booked seat shall not be booked again.
The question is the dimensions of the GUI will change according to the seat numbers and orientation, which means in one version there can be lots of buttons on another less, also more seats means the GUI will be longer or wider maybe 10 cm x 10 cm or 10 cm x 20 cm, or 15 cm x 25 cm...
I am thinking to do this with a for loop but I dont want to put buttons out of the GUI.I dont know how can I add a button next to the other button arbitrarily. I always used Eclipse Window Builder for building GUIs but I guess I need to write this one on my own... can someone help me?Some hints?Thanks for your time!
Try something like this:
// The size of the window.
Rectangle bounds = this.getBounds();
// How many rows of buttons.
int numOfRows = 100;
// How many buttons per row.
int numOfColumns = 50;
int buttonWidth = bounds.width / numOfRows;
int buttonHeight = bounds.height / numOfColumns;
int x = 0;
int y = 0;
for(int i = 0; i < numOfColumns; i++){
for(int j = 0; j < numOfRows; j++){
// Make a button
button.setBounds(x, y, buttonWidth, buttonHeight);
y += buttonHeight;
}
x += buttonWidth;
}
This will make all the buttons fit inside of your window.
Here's a link on rectangles, they come in pretty handy when doing things like this.
http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fswt%2Fgraphics%2FRectangle.html
Also, you can still use windowbuilder, infact I recommend you do. It really helps you to visualize the dimensions you want. AND you can also create stuff (buttons, lists, dropdowns... etc) manually with code and, assuming you put the variables where WindowBuilder would, it will still display them in the 'design' tab.
Hope this helps!
EDIT: I was kinda vague on how to make buttons using a loop
To make buttons with a loop you will need a buffer (to store a temporary button long enough to add to a list) and... a list :D.
This is how it should look:
Outside loop:
// The list to store your buttons in.
ArrayList<Button> buttons = new ArrayList<Button>();
// The empty button to use as a buffer.
Button button;
Inside loop (where the '//Make a button' comment is):
button = new Button(this, SWT.NONE);
buttons.add(button);
Now you have a list of all the buttons, and can easily access them and make changes such as change the buttons text like so;
buttons.get(indexOfButton).setText("SomeText");
EDIT:
Seeing as you're new to swt (and I couldn't get awt/JFrame to work) here's the full code.
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ButtonTest extends Shell {
/**
* Launch the application.
* #param args
*/
// Code starts here in main.
public static void main(String args[]) {
try {
Display display = Display.getDefault();
// Creates a window (shell) called "shell"
ButtonTest shell = new ButtonTest(display);
// These two lines start the shell.
shell.open();
shell.layout();
// Now we can start adding stuff to our shell.
// The size of the window.
Rectangle bounds = shell.getBounds();
// How many rows of buttons.
int numOfRows = 5;
// How many buttons per row.
int numOfColumns = 3;
int buttonWidth = bounds.width / numOfRows;
int buttonHeight = bounds.height / numOfColumns;
Button button;
int x = 0;
int y = 0;
for(int i = 0; i < numOfColumns; i++){
for(int j = 0; j < numOfRows; j++){
button = new Button(shell, SWT.NONE);
button.setBounds(x, y, buttonWidth, buttonHeight);
x += buttonWidth;
}
x = 0;
y += buttonHeight;
}
// This loop keeps the shell from killing itself the moment it's opened
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the shell.
* #param display
*/
public ButtonTest(Display display) {
super(display, SWT.SHELL_TRIM);
createContents();
}
/**
* Create contents of the shell.
*/
protected void createContents() {
setText("SWT Application");
setSize(800, 800);
}
#Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
Also, I made a little typo in my nested loop (and forgot to reset the x value to 0 after each row). It's fixed in this edit.
Also you will need to import swt for this to work.
Go here: http://www.eclipse.org/swt/ and download the latest version for your operating system, then go in eclipse, right click your project > Build Path > configure Build Path > Libraries tab > Add external JAR's > find the swt file you downloaded and click.
Sorry for such a long answer, hope it helps :D
Start with a GridLayout. Each time you need to change the seat layout, reapply the GridLayout.
Ie, if you need 100 seats, use something like, new GridLayout(20, 10)...
Personally, I'd use a GridBagLayout, but it might be to complex for the task at hand
Its a little more difficult to add/rmove new content. I would, personally, rebuild the UI and reapply the model to it.
As for the size, you may not have much control over it, as it will appear differently on different screens. Instead, you should provide means by which you can prevent the UI from over sizing the screen.
This is achievable by placing the seating pane within a JScrollPane. This will allow the seating pane to expand and shrink in size without it potentially over sizing on the screen
Take a look at
Creating a UI with Swing
Using Layout Managers
A Visual Guide to Layout Managers
I am taking a programming class, and I have to make an instrument "play". I want to use Math.random to create a random number between either 0-9 or 0-10 and have that number correspond to a picture in an array displayed via JOptionPane icon. My only issue is, how can I create a program that will correspond a random int to a picture and then present it using JOption Pane. Here is what I have so far:
public static String Flute(String pickYourInstrument, String instrument){
//try to assign variables to pictures in an array
ImageIcon icon = new ImageIcon("/home/james/programmingpics/A_Flute");
JOptionPane.showMessageDialog(null, "A Note", "A Note with Flute",
JOptionPane.OK_OPTION, icon);
for (int i = 0; i < 1000; i++) {
int random = 1 * (int) (Math.random() * 10);
System.out.println(random);
}
}
I am stuck, I stopped after I realized that I didn't know how to make the ImageIcon icon into an array (I have nine other pictures to make an icon for). Does anyone have an idea how I could create the program?
Simply create an array of ImageIcon, then the random number obtained can be used as an index to that array to get the corresponding icon. Something as simple as
int randomNumber = //.... get random int
ImageIcon myIcon = iconArray[randomNumber];