I need help with random number in GUI
hello
i have home work about the random number with gui. and i hope that you can help me doin this application. and thank you very much
Q1)
Write an application that generates random numbers. The application consists of one JFrame,
with two text fields (see the figures) and a button. When the user clicks on the button, the
program should generate a random number between the minimum and the maximum numbers
entered in the text fields. The font of the number should be in red, size 100, bold and italic.
Moreover, if the user clicks on the generated number (or around it), the color of the background
should be changed to another random color. The possible colors are red, green blue , black ,cyan
and gray.
Notes:
�The JFrame size is 40 by 200
�The text fields size is 10
this is a sample how should the programe look like.
http://img235.imageshack.us/img235/9680/outputgo3.jpg
Message was edited by:
jave_cool
see java.util.Random
Similar Messages
-
Need Help with random numbers, please help
Hi guys;
I need your help for a school project. I need to generate a random number from 1.0 to 2.0. How would I do that?
Regards,http://java.sun.com/j2se/1.3/docs/api/java/util/Random.html#nextFloat()
-
Need help with random string arrays
Hi, I could really use some specific advice about how to randomize and display strings. I'm trying to create an applet that displays a list of 12 chores and a list of four people for whom the chores should be distributed to. So far I have set up the code to display the chores list in the first column and what I'm tring to do is then randomly assign each persons name 3 times in the second column. I'm not getting any error messages but the problem is that I can't seem to get the names to appear only 3 times.
// Random generator = new Random();
// JButton assignChores = new Button("Assign Chores")'
// JTextArea outputArea = new JTextArea("");
// ect....
public void actionPerformed(ActionEvent e) {
String[] chores = {"Living Room",
"Dining Room",
"Kitchen",
"Boy's Room",
"Garbage",
"Backyard",
"Pets",
"Front Bathroom",
"Back Bathroom",
"Laundry",
"Computer Room",
"Parent's Room"};
String[] person = {"Mom",
"Dad",
"Son",
"Daughter"};
int[] numIndex = new int[13];
String output = "Chores" + "\t" + "Person";
output += "\n________________________________\n";
// I feel relatively certain that a while statement should go
// here but I'm lost as to how I should go about this.
for (int i = 1; i < numIndex.length; i++) {
int arrayIndex = generator.nextInt(person.length); // generate a random number based on the number of people
output += "\n" + chores[numIndex[0]++] // display the chores list in column 1
+ "\t" + person[arrayIndex]; // then randomly display the names in column 2
output += "\n________________________________\n";
outputArea.setText(output);
JOptionPane.showMessageDialog (null, outputArea,
"Chores List", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);Hi,
Here's even a more elegant twist on the problem.
import java.util.*;
class FamilyMember
private String name;
private ArrayList chores;
private final int MAX_CHORES = 3;
public FamilyMember( String name )
this( name, null );
public FamilyMember( String name, Collection chores )
this.name = name;
setChores( chores );
public String getName()
return( name );
public Collection getChores()
return( chores );
private void initArray()
if( chores == null )
chores = new ArrayList();
public void setChores( Collection newChores )
if( newChores != null )
initArray();
if( newChores.size() <= MAX_CHORES )
Iterator it = newChores.iterator();
while( it.hasNext() )
chores.add( it.next() );
public boolean addChore( String newChore )
boolean outBool = false;
initArray();
if( chores.size() < MAX_CHORES )
chores.add( newChore );
outBool = true;
return( outBool );
public void setName( String newName )
name = newName;
class Chore
private String name;
private boolean assigned;
public Chore( String name )
this.name = name;
public String getName()
return( name );
public void setName()
this.name = name;
public void setAssigned( boolean newAssigned )
assigned = newAssigned;
public boolean isAssigned()
return( assigned );
public class ChoreLister
public static void main(String[] args)
Chore[] chores = { new Chore( "Living Room" ),
new Chore( "Dining Room" ),
new Chore( "Kitchen" ),
new Chore( "Boy's Room" ),
new Chore( "Garbage" ),
new Chore( "Backyard" ),
new Chore( "Pets" ),
new Chore( "Front Bathroom" ),
new Chore( "Back Bathroom" ),
new Chore( "Laundry" ),
new Chore( "Computer Room" ),
new Chore( "Parent's Room" ) };
FamilyMember[] fm = { new FamilyMember( "Mom" ),
new FamilyMember( "Dad" ),
new FamilyMember( "Son" ),
new FamilyMember( "Daughter" ) };
Random generator = new Random();
System.out.println( "Chores\tPerson" );
System.out.println( "________________________________" );
// Loop through all chores assigning them as we go.
for( int j = 0; j < chores.length; ++j )
int arrayIndex = generator.nextInt( fm.length );
while( !chores[j].isAssigned() )
while( !fm[arrayIndex].addChore( chores[j].getName() ) )
arrayIndex = generator.nextInt( fm.length );
chores[j].setAssigned( true );
System.out.print( chores[j].getName() + "\t" );
if( chores[j].getName().length() < 8 )
System.out.print( "\t" );
System.out.println( fm[arrayIndex].getName() );
System.out.println( "________________________________" );
}Enjoy,
Manfred. -
Really need help with re-number rows
I am trying to update the Precedence value for each row based on its order in the ORDER BY clause. What I am doing is I allow users to insert rows above or below other rows. This is done by adding 0.5 or -0.5 to the PRECEDANCE value of the row they are inserting above or blow. Once this is done I need to update all rows with a new hole number PRECIDANCE value getting ready for the next insert.
Any help would be great, even an entirely different way!
UPDATE
TABLE_A TBL_A
SET
TBL_A.PRECEDENCE = (ROWNUM * 10)
WHERE
TBL_A.EMP_ID in
select
EMP_ID,
PRECEDENCE
from(
select
TBL_A.EMP_ID,
TBL_A.PRECEDENCE
from
TABLE_A TBL_A
where
TBL_A.OTHER_ID = :THIS_ID
order by
2,
1
)On average, though, Andrew's procedure will update half the rows in the table on every insert (assuming that your inserts occur between two rows at random). If there are a lot of rows in the table or if there are a lot of inserts, this may not scale particularly well. It may also cause problems if you have an optimistic locking mechanism in place to handle multiple users updating the table simultaneously.
I'd still do something like
CREATE OR REPLACE PROCEDURE insert_after( p_prior_precedence IN NUMBER,
p_row IN <<table name>>%rowtype )
AS
l_next_precedence NUMBER;
BEGIN
SELECT MIN(precedence)
INTO l_next_precedence
FROM <<table>>
WHERE precedence > p_prior_precedence;
p_row.precedence := (p_prior_preceddence + l_next_precedence) / 2;
INSERT INTO <<table>> VALUES p_row;
END;This way, you don't have to update any rows when you do an insert. You don't get integer precedence values, but this strikes me as a reasonable trade-off. If you want to re-number things either at query time
SELECT <<columns>>
RANK() OVER (PARTITION BY <<something>> ORDER BY precedence) pretty_precedence
FROM <table name>>or as a nightly job, that would work.
Justin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
Desperate HELP with Random Numbes in an Array & Do / While
Please somebody help, I have been working this problem for over 7 days now and can't get it. I have tried everything from a while to a do while to this and that. I need to have an Array of 8 that when run will produce random numbers for output between 15 to 25. I CAN"T GET IT PLEASE HELP. I am new to JAVA and have done everything I can think of to resolve this. I even have purchased a new book and looked at every site trying to find a solution. PLEASE HELP! Here it is:
import javax.swing.*;
public class RandomArray{
public static void main (String [ ] args) {
JTextArea outputArea = new JTextArea ( );
int myArray [ ]; //array declaration
myArray = new int [ 8 ]; //allocating memory
String output = "Array values at initializatioon ";
output += "\nIndex\tValues";
for ( int i = 0; i < myArray.length; i ++)
output += "\n" + i + "\t" + myArray [ i ];
output += "\n\nArray values after assigning values within the range of 15 and 25";
do {( int i = 0; i <myArray.length; i++)
while myArray [ i ] = 15 + (int) (Math.random ( ) * 25);
output += "\n" + i + "\t" + myArray [ i ];}
outputArea.setText (output);
JOptionPane.showMessageDialog (null, outputArea,
"Array Value before and after",
JOptionPane.INFORMATION_MESSAGE);
System.exit ( 0 );
The output that I need is in two columns one with the initial array 0-7 and the second should be random numbers 15-25. Please help, pleasehere you are :
import javax.swing.*;
public class RandomArray
public static void main (String [ ] args)
JTextArea outputArea = new JTextArea();
int myArray [] = new int[8];
String output = "Array values at initializatioon ";
output += "\nIndex\tValues";
for (int i = 0; i < myArray.length; i ++)
output += "\n" + i + "\t" + myArray [ i ];
output += "\n\nArray values after assigning values within the range of 15 and 25";
for (int i = 0; i < myArray.length; i++)
myArray [ i ] = 15 + (int) (Math.random ( ) * 10);
output += "\n" + i + "\t" + myArray [ i ];
outputArea.setText(output);
JOptionPane.showMessageDialog (null, outputArea,
"Array Value before and after",
JOptionPane.INFORMATION_MESSAGE);
System.exit(0); -
Need help with threading in Swing GUI !!!
I've written an app that parses and writes
files. I'm using a Swing GUI. The app
could potenially be used to parse hundreds or even
thousands of files. I've included a JProgressBar
to monitor progress. The problem is when I parse
a large number of files the GUI freezes and only
updates the values of the progress bar when the
parsing and writing process is finished.
I assume I need to start the process in a seperate thread. But, I'm new to threads and I'm not sure
whether to start the Progressbar code in a seperate
thread or the parsing code. As a matter of fact I really
don't have any idea how to go about this.
I read that Swing requires repaints be done in the
event dispatch thread. If I start the parsing in a seperate
thread how do I update the progressbar from the other
thread? I'm a thread neophyte.
I need a cigarette.In other words do this:
Inside event Thread:
handle button action
start thread
return from action listener
Inside worker Thread:
lock interface
loop
perform action
update progress bar
unlock interface
return from worker ThreadDoesn't updating the progress bar (and locking/unlocking the interface components) from within the worker thread violate the rule that you shouldn't mess with Swing components outside the event thread? (Do I have that rule right?)
In any case, is there any way to just post some kind of event to the progress bar to update it from within the worker thread, thereby insuring that the GUI progress bar update is being invoked from the event thread? This would also obviate the need to use a timer to poll for an update, which I think is a waste especially when the monitored progress is at a variable rate, (or for number crunching, is executing on different speed machines).
Also, doesn't using invokeLater() or invokeAndWait() still block the event dispatching thread? I don't understand how having a chunk of code started in the event thread doesn't block the event thread unless the code's executed in a "sub-thread", which would then make it not in the event thread.
I'm also looking to have a progress bar updated to monitor a worker thread, but also want to include a "Stop" button, etc. and need the event queue not to be blocked.
The last thing I can think of is to implement some kind of original event-listener class that listens to events that I define, then register it with the system event queue somehow, then have the worker thread post events to this listener which then calls setValue() in the progress bar to insure that the bar is updated from the event queue and when I want it to be updated. I don't know yet if it's possible to create and register these kinds of classes (I'm guessing it is).
Thanks,
Derek -
hi i need to generate 2 random numbers from array list . and then take out that two numbers from list.
String[] plcard = { "AC", "KC", "QC", "JC",
"10C", "9C", "8C", "7C","6C","5C","4C","3C","2C", "AD", "KD", "QD", "JD",
"10D", "9D", "8D", "7D","6D","5D","4D","3D","2D", "AS", "KS", "QS", "JS",
"10S", "9S", "8S", "7S","6S","5S","4S","3S","2S", "AH", "KH", "QH", "JH",
"10H", "9H", "8H", "7H","6H","5H","4H","3H","2H",};
this is the list if someone can help me i would appreciate
thanks in advancehaha, never noticed the .shuffle(List) method!
maybe java is getting too convenient (just kidding)?
i never wrote a card game.
how would the more programmingly gifted of us do this?
this is my shot at it for what its worth...
public class Card{
public Card(int rank, int suit){
this.rank = rank;
this.suit = suit;
int rank (or String i suppose)
int suit;
static final club = 1;
static final spade = 2;
static final heart = 3;
static final diamond = 4;
public class Shuffler{
public Shuffler(){
int NumOfDecks = 1;
Vector ShuffledDeck;
// num of decks
for(int i = 0; i < NumOfDecks){
// 4 suits
for(int j = 0; j < 4; j++){
// 13 ranks
for(int k = 0; k < 13; k++){
ShuffledDeck.add(new Card(k, j));
} // suits
} // num of decks
Collections.shuffle(ShuffledDeck);
// Done?
} -
Need help with integrating chat into Gui
Hello Guys,
I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class Client
extends JPanel {
public static void main(String[] args) throws IOException {
String name = args[0];
String host = args[1];
int port = Integer.parseInt(args[2]);
final Socket s = new Socket(host, port);
final Client c = new Client(name, s);
JFrame f = new JFrame("Client : " + name);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
c.shutDown();
System.exit(0);
f.setSize(300, 300);
f.setLocation(100, 100);
f.setContentPane(c);
f.setVisible(true);
private String mName;
private JTextArea mOutputArea;
private JTextField mInputField;
private PrintWriter mOut;
public Client(final String name, Socket s)
throws IOException {
mName = name;
createUI();
wireNetwork(s);
wireEvents();
public void shutDown() {
mOut.println("");
mOut.close();
protected void createUI() {
setLayout(new BorderLayout());
mOutputArea = new JTextArea();
mOutputArea.setLineWrap(true);
mOutputArea.setEditable(false);
add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
mInputField = new JTextField(20);
JPanel controls = new JPanel();
controls.add(mInputField);
add(controls, BorderLayout.SOUTH);
mInputField.requestFocus();
protected void wireNetwork(Socket s) throws IOException {
mOut = new PrintWriter(s.getOutputStream(), true);
final String eol = System.getProperty("line.separator");
new Listener(s.getInputStream()) {
public void processLine(String line) {
mOutputArea.append(line + eol);
mOutputArea.setCaretPosition(
mOutputArea.getDocument().getLength());
protected void wireEvents() {
mInputField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String line = mInputField.getText();
if (line.length() == 0) return;
mOut.println(mName + " : " + line);
mInputField.setText("");I think the easiest way to do it would be to cut an paste most of that code into your program. Then all you have to do is change some names so that it uses your textfield and textarea.
-
Need Help with Random Events in Actionscript 2
I'm working on a game in flash right now, written in actionscript 2, where bottles fall from above at random speeds, and the object is to shoot the bottles as they fall, and every time you hit a bottle a different message appears on the screen for a brief period of time before disappearing. So far I'm able to make the bottles fall and I'm able to shoot and break them, but I don't know how to work it so a different message appears each time you shoot a bottle.
Can anyone help me with this problem? I'm attaching the file of what I have so far.My first question would be, when you say "different message appears" each time you hit a bottle.
What are the messages and do you want them to be random, and where will they appear.
After looking at your code, the best place I can see to place your message trigger is within the hit test. From there its a somple case of calling a function to display your message. -
Need help with phone number keypad please
I have found when using my iPhone to call certain phone numbers requiring me to enter an extension number, I'll get a message that it's an invalid extension and try again, I try at least 2-3 times and still get the same message. Well I'll call back on a different phone and enter the exact same extension and it goes through. It's not always the same phone number/extension but it happens everytime I make a call on my iPhone that requires an extension to be keyed in.
Does anyone have any suggestions or idea what I can do? I've reset the phone several times but it doesn't help.
Thanks in advance,
iPhoNettieTime to give AT&T a call.
-
I need help with phone number transfer
I just purchased the iphone and I can not get service yet. My cell phone is without service now, but the iphone does not have service yet. How can I check to see if I entered everything correctly, I did not get any errors.
Time to give AT&T a call.
-
Need help with codings on generating random words
hi guys.. i need help with generating random words from a list of array. please help me with the codings.. let me know the other variables that are needed if required as well.. thanks a million..
private String wordList[] = { "abstraction", "command", "arithmetic", "backslash" };Hi,
You can use the Random class to generate Random number between 0 to the array length and use the generated random number as index in to the Strign array.
To generate Random number use the following code
Random r = new Random();
num = ((r.nextInt() >>> 1) % wordList.length);
num will have the randomly generated number. -
I need help with my serial number. I downloaded soundbooth cs3 to restore my downloaded purchase, but my serial number is not being accepted. I have 16 more days to resolve this. I don't need tech support, I just need the software I purchased to work for me. That's not to much to ask, is it? Can anyone from adobe help me please?
ChrisError "The serial number is not valid for this product" | Creative Suite
-
Need help to share Number/Pages file visa Mail option. Cannot do with iPad Air
Oh, okay. After selecting the format I want to send, it says "creating... ". Then irrespective of the format I choose the message e.g. "creating spreadsheet" disappears, and so does the choice window (where I earlier chose Mail). I am taken back to the Numbers (or Page) where I had started from. Diavonex's note indicated that after "creating ... " stage I should be taken to an option where I can type in email address where I want to send the file, if I want to copy it to another address etc. I cannot arrive at that page - no matter whether I am working with Pages or Number, or which format I choose for the file to share !
I will try to close as you have suggested and try. However, I have switched on and off several times by now, but nothing changed!
Will look forward to any ideas to solve this !!!
Thanks much!
Best -
Need help!!!! GUI problems with netbeans
i have a problem with the interface i created using netbeans.
i created a JFrame, inside it a JDesktopPane, and inside that 3 JInternalFrames. the problem is in one of the JinternalFrames, i have 4 radio buttons which i forgot to add to a buttongroup and whenever i try to do that, the GUI doesn't work anymore. The bigger problem is that if i undo the changes, the thing still doesn't work and i have to copy my backup project folder over the one i work on to get an output.
i tried to edit the source code to add the 4 buttons to a button group but netbeans won't let me since i created the buttons thru it not by writing it myself
please i really need help with this and i hope its a stupid thing i'm just overlooking.
If u need the code, i will gladly post it.
thanks in advanceif you're not using a netbeans-specific layout manager, copy the working code
into notepad, make the changes, then compile and run from the command prompt.
if all works OK, dump netbeans
Maybe you are looking for
-
Migration assistent/Time capsule/mail
I just bought a Macbook Pro and wanted to migrate all my data from my iMac to the new Macbook Pro. First time I tried to migrate all my data from a time capsule backup everything went well, but Mail didn't respond. I thought it was because I had Snow
-
while entering tds surcharge rate 0.2 at Define withholing tax codes display the error "Enter a Numaric value" what can i do for it
-
When I use the Create Page > Tabular Form wizard to create a form based on a table with a zero in the name, I receive this error: ORA-20001: Unable to create updateable report. ORA-20001: ParseErr: ORA-00904: "T11_ACCOUNT": invalid identifier Here is
-
Possible to read input directly to double?
i know how to parse double/ int and all that stuff from a string, but i was wondering (for future reference) if there is a quicker way to just go from input to double. i know this way string1 = stdin.readLine( ); int1 = Integer.parseInt (string1);
-
9i Forms Does it run under tradetional runtime?
i need to know if the oracle 9i forms do run as developer 2000 or 6i at a runtime window out of the browser cuse it works with my only under browser and served by OC4J AS and i thought it might have any configuration needed for some thing like that..