Iterating through a list and drawing a colored squareHow do I efficiently iterate over each entry in a Java Map?How do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow to make a flat list out of list of lists?Iterate through a HashMapHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to clone or copy a list?Loop through an array in JavaScript
Why doesn't Gödel's incompleteness theorem apply to false statements?
Why do Radio Buttons not fill the entire outer circle?
Can a Knock spell open the door to Mordenkainen's Magnificent Mansion?
How do I lift the insulation blower into the attic?
Put the phone down / Put down the phone
Can you take a "free object interaction" while incapacitated?
Are hand made posters acceptable in Academia?
Connection Between Knot Theory and Number Theory
Friend wants my recommendation but I don't want to give it to him
Why didn’t Eve recognize the little cockroach as a living organism?
Checking @@ROWCOUNT failing
Started in 1987 vs. Starting in 1987
A seasonal riddle
How do you justify more code being written by following clean code practices?
C++ lambda syntax
Air travel with refrigerated insulin
Relations between homogeneous polynomials
When is the exact date for EOL of Ubuntu 14.04 LTS?
Extract substring according to regexp with sed or grep
What is the meaning of "You've never met a graph you didn't like?"
Travelling in US for more than 90 days
1 John in Luther’s Bibel
Is this saw blade faulty?
"Oh no!" in Latin
Iterating through a list and drawing a colored square
How do I efficiently iterate over each entry in a Java Map?How do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow to make a flat list out of list of lists?Iterate through a HashMapHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?How to clone or copy a list?Loop through an array in JavaScript
I have a colored box, I want it to change color every 1/2 second, however I want my code to run as well.
I'm using Java AWT's Graphic Api to draw using g.fillRect(568, 383, 48, 48); where g is wrapped to 'Graphics.'
So you'd think that its simple right?
Color[] colors
colors = new Color[4];
colors[0] = new Color(Color.red);
colors[1] = new Color(Color.blue);
colors[2] = new Color(Color.green);
colors[3] = new Color(Color.yellow);
for(int i = 0; i < colors.length; i++)
g.setColor(colors[i]);
g.fillRect(568, 383, 48, 48);
This is all cool but the problem is that none of my program runs when this for loop is running...
I think I can make the game 'Multi-Threaded' which means it can do more than one thing at a time but I have no idea how to do this and it sounds hard, all help appreciated!
java arrays list colors awt
add a comment |
I have a colored box, I want it to change color every 1/2 second, however I want my code to run as well.
I'm using Java AWT's Graphic Api to draw using g.fillRect(568, 383, 48, 48); where g is wrapped to 'Graphics.'
So you'd think that its simple right?
Color[] colors
colors = new Color[4];
colors[0] = new Color(Color.red);
colors[1] = new Color(Color.blue);
colors[2] = new Color(Color.green);
colors[3] = new Color(Color.yellow);
for(int i = 0; i < colors.length; i++)
g.setColor(colors[i]);
g.fillRect(568, 383, 48, 48);
This is all cool but the problem is that none of my program runs when this for loop is running...
I think I can make the game 'Multi-Threaded' which means it can do more than one thing at a time but I have no idea how to do this and it sounds hard, all help appreciated!
java arrays list colors awt
1
You will have to make it multi threaded if you want more then 1 thing to happen at the time. Look for example at tutorialspoint.com/java/java_multithreading.htm for a simple example of threading.
– Norbert van Nobelen
Jul 18 '15 at 0:04
1
@NorbertvanNobelen Or use a Swing Timer, which makes it safer to update the Ui from within as it won't violate the singe threaded nature of the Swing API
– MadProgrammer
Jul 18 '15 at 0:28
add a comment |
I have a colored box, I want it to change color every 1/2 second, however I want my code to run as well.
I'm using Java AWT's Graphic Api to draw using g.fillRect(568, 383, 48, 48); where g is wrapped to 'Graphics.'
So you'd think that its simple right?
Color[] colors
colors = new Color[4];
colors[0] = new Color(Color.red);
colors[1] = new Color(Color.blue);
colors[2] = new Color(Color.green);
colors[3] = new Color(Color.yellow);
for(int i = 0; i < colors.length; i++)
g.setColor(colors[i]);
g.fillRect(568, 383, 48, 48);
This is all cool but the problem is that none of my program runs when this for loop is running...
I think I can make the game 'Multi-Threaded' which means it can do more than one thing at a time but I have no idea how to do this and it sounds hard, all help appreciated!
java arrays list colors awt
I have a colored box, I want it to change color every 1/2 second, however I want my code to run as well.
I'm using Java AWT's Graphic Api to draw using g.fillRect(568, 383, 48, 48); where g is wrapped to 'Graphics.'
So you'd think that its simple right?
Color[] colors
colors = new Color[4];
colors[0] = new Color(Color.red);
colors[1] = new Color(Color.blue);
colors[2] = new Color(Color.green);
colors[3] = new Color(Color.yellow);
for(int i = 0; i < colors.length; i++)
g.setColor(colors[i]);
g.fillRect(568, 383, 48, 48);
This is all cool but the problem is that none of my program runs when this for loop is running...
I think I can make the game 'Multi-Threaded' which means it can do more than one thing at a time but I have no idea how to do this and it sounds hard, all help appreciated!
java arrays list colors awt
java arrays list colors awt
edited Mar 7 at 0:55
Cœur
19k9112154
19k9112154
asked Jul 18 '15 at 0:00
RobinlemonRobinlemon
12313
12313
1
You will have to make it multi threaded if you want more then 1 thing to happen at the time. Look for example at tutorialspoint.com/java/java_multithreading.htm for a simple example of threading.
– Norbert van Nobelen
Jul 18 '15 at 0:04
1
@NorbertvanNobelen Or use a Swing Timer, which makes it safer to update the Ui from within as it won't violate the singe threaded nature of the Swing API
– MadProgrammer
Jul 18 '15 at 0:28
add a comment |
1
You will have to make it multi threaded if you want more then 1 thing to happen at the time. Look for example at tutorialspoint.com/java/java_multithreading.htm for a simple example of threading.
– Norbert van Nobelen
Jul 18 '15 at 0:04
1
@NorbertvanNobelen Or use a Swing Timer, which makes it safer to update the Ui from within as it won't violate the singe threaded nature of the Swing API
– MadProgrammer
Jul 18 '15 at 0:28
1
1
You will have to make it multi threaded if you want more then 1 thing to happen at the time. Look for example at tutorialspoint.com/java/java_multithreading.htm for a simple example of threading.
– Norbert van Nobelen
Jul 18 '15 at 0:04
You will have to make it multi threaded if you want more then 1 thing to happen at the time. Look for example at tutorialspoint.com/java/java_multithreading.htm for a simple example of threading.
– Norbert van Nobelen
Jul 18 '15 at 0:04
1
1
@NorbertvanNobelen Or use a Swing Timer, which makes it safer to update the Ui from within as it won't violate the singe threaded nature of the Swing API
– MadProgrammer
Jul 18 '15 at 0:28
@NorbertvanNobelen Or use a Swing Timer, which makes it safer to update the Ui from within as it won't violate the singe threaded nature of the Swing API
– MadProgrammer
Jul 18 '15 at 0:28
add a comment |
2 Answers
2
active
oldest
votes
Most UI frameworks aren't thread safe, so you need to beware of that. For example, in Swing, you could use a Swing Timer
to act as a pseudo loop. Because the Timer
notifies the ActionListener
from within the context of the Event Dispatching Thread, it makes it safe to update the UI or the state of the UI from within, without risking thread race conditions
Take a look at Concurrency in Swing and How to use Swing Timers for more details
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class JavaApplication430
public static void main(String[] args)
new JavaApplication430();
public JavaApplication430()
EventQueue.invokeLater(new Runnable()
@Override
public void run() UnsupportedLookAndFeelException ex)
ex.printStackTrace();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
);
public class TestPane extends JPanel
private Color[] colors;
private int whichColor = 0;
public TestPane()
colors = new Color[4];
colors[0] = Color.red;
colors[1] = Color.blue;
colors[2] = Color.green;
colors[3] = Color.yellow;
Timer timer = new Timer(500, new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
whichColor++;
repaint();
if (whichColor >= colors.length)
whichColor = colors.length - 1;
((Timer)(e.getSource())).stop();
);
timer.start();
@Override
public Dimension getPreferredSize()
return new Dimension(200, 200);
@Override
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(colors[whichColor]);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
add a comment |
I cannot imagine how you could create an interactive game if your code is single thread. To change the box color periodically you will have to put your thread to sleep. If your game is not multi-thread, then this will freeze your application, preventing user interaction. You will find a lot of interesting materials about programming with threads in Java:
http://docs.oracle.com/javase/tutorial/essential/concurrency/
http://www.ibm.com/developerworks/library/j-thread/
http://moderntone.blogspot.com.br/2013/02/a-simple-java-multithreading-example.html
Just google it!
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31486395%2fiterating-through-a-list-and-drawing-a-colored-square%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Most UI frameworks aren't thread safe, so you need to beware of that. For example, in Swing, you could use a Swing Timer
to act as a pseudo loop. Because the Timer
notifies the ActionListener
from within the context of the Event Dispatching Thread, it makes it safe to update the UI or the state of the UI from within, without risking thread race conditions
Take a look at Concurrency in Swing and How to use Swing Timers for more details
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class JavaApplication430
public static void main(String[] args)
new JavaApplication430();
public JavaApplication430()
EventQueue.invokeLater(new Runnable()
@Override
public void run() UnsupportedLookAndFeelException ex)
ex.printStackTrace();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
);
public class TestPane extends JPanel
private Color[] colors;
private int whichColor = 0;
public TestPane()
colors = new Color[4];
colors[0] = Color.red;
colors[1] = Color.blue;
colors[2] = Color.green;
colors[3] = Color.yellow;
Timer timer = new Timer(500, new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
whichColor++;
repaint();
if (whichColor >= colors.length)
whichColor = colors.length - 1;
((Timer)(e.getSource())).stop();
);
timer.start();
@Override
public Dimension getPreferredSize()
return new Dimension(200, 200);
@Override
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(colors[whichColor]);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
add a comment |
Most UI frameworks aren't thread safe, so you need to beware of that. For example, in Swing, you could use a Swing Timer
to act as a pseudo loop. Because the Timer
notifies the ActionListener
from within the context of the Event Dispatching Thread, it makes it safe to update the UI or the state of the UI from within, without risking thread race conditions
Take a look at Concurrency in Swing and How to use Swing Timers for more details
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class JavaApplication430
public static void main(String[] args)
new JavaApplication430();
public JavaApplication430()
EventQueue.invokeLater(new Runnable()
@Override
public void run() UnsupportedLookAndFeelException ex)
ex.printStackTrace();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
);
public class TestPane extends JPanel
private Color[] colors;
private int whichColor = 0;
public TestPane()
colors = new Color[4];
colors[0] = Color.red;
colors[1] = Color.blue;
colors[2] = Color.green;
colors[3] = Color.yellow;
Timer timer = new Timer(500, new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
whichColor++;
repaint();
if (whichColor >= colors.length)
whichColor = colors.length - 1;
((Timer)(e.getSource())).stop();
);
timer.start();
@Override
public Dimension getPreferredSize()
return new Dimension(200, 200);
@Override
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(colors[whichColor]);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
add a comment |
Most UI frameworks aren't thread safe, so you need to beware of that. For example, in Swing, you could use a Swing Timer
to act as a pseudo loop. Because the Timer
notifies the ActionListener
from within the context of the Event Dispatching Thread, it makes it safe to update the UI or the state of the UI from within, without risking thread race conditions
Take a look at Concurrency in Swing and How to use Swing Timers for more details
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class JavaApplication430
public static void main(String[] args)
new JavaApplication430();
public JavaApplication430()
EventQueue.invokeLater(new Runnable()
@Override
public void run() UnsupportedLookAndFeelException ex)
ex.printStackTrace();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
);
public class TestPane extends JPanel
private Color[] colors;
private int whichColor = 0;
public TestPane()
colors = new Color[4];
colors[0] = Color.red;
colors[1] = Color.blue;
colors[2] = Color.green;
colors[3] = Color.yellow;
Timer timer = new Timer(500, new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
whichColor++;
repaint();
if (whichColor >= colors.length)
whichColor = colors.length - 1;
((Timer)(e.getSource())).stop();
);
timer.start();
@Override
public Dimension getPreferredSize()
return new Dimension(200, 200);
@Override
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(colors[whichColor]);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
Most UI frameworks aren't thread safe, so you need to beware of that. For example, in Swing, you could use a Swing Timer
to act as a pseudo loop. Because the Timer
notifies the ActionListener
from within the context of the Event Dispatching Thread, it makes it safe to update the UI or the state of the UI from within, without risking thread race conditions
Take a look at Concurrency in Swing and How to use Swing Timers for more details
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class JavaApplication430
public static void main(String[] args)
new JavaApplication430();
public JavaApplication430()
EventQueue.invokeLater(new Runnable()
@Override
public void run() UnsupportedLookAndFeelException ex)
ex.printStackTrace();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
);
public class TestPane extends JPanel
private Color[] colors;
private int whichColor = 0;
public TestPane()
colors = new Color[4];
colors[0] = Color.red;
colors[1] = Color.blue;
colors[2] = Color.green;
colors[3] = Color.yellow;
Timer timer = new Timer(500, new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
whichColor++;
repaint();
if (whichColor >= colors.length)
whichColor = colors.length - 1;
((Timer)(e.getSource())).stop();
);
timer.start();
@Override
public Dimension getPreferredSize()
return new Dimension(200, 200);
@Override
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(colors[whichColor]);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
answered Jul 18 '15 at 0:39
MadProgrammerMadProgrammer
301k17155271
301k17155271
add a comment |
add a comment |
I cannot imagine how you could create an interactive game if your code is single thread. To change the box color periodically you will have to put your thread to sleep. If your game is not multi-thread, then this will freeze your application, preventing user interaction. You will find a lot of interesting materials about programming with threads in Java:
http://docs.oracle.com/javase/tutorial/essential/concurrency/
http://www.ibm.com/developerworks/library/j-thread/
http://moderntone.blogspot.com.br/2013/02/a-simple-java-multithreading-example.html
Just google it!
add a comment |
I cannot imagine how you could create an interactive game if your code is single thread. To change the box color periodically you will have to put your thread to sleep. If your game is not multi-thread, then this will freeze your application, preventing user interaction. You will find a lot of interesting materials about programming with threads in Java:
http://docs.oracle.com/javase/tutorial/essential/concurrency/
http://www.ibm.com/developerworks/library/j-thread/
http://moderntone.blogspot.com.br/2013/02/a-simple-java-multithreading-example.html
Just google it!
add a comment |
I cannot imagine how you could create an interactive game if your code is single thread. To change the box color periodically you will have to put your thread to sleep. If your game is not multi-thread, then this will freeze your application, preventing user interaction. You will find a lot of interesting materials about programming with threads in Java:
http://docs.oracle.com/javase/tutorial/essential/concurrency/
http://www.ibm.com/developerworks/library/j-thread/
http://moderntone.blogspot.com.br/2013/02/a-simple-java-multithreading-example.html
Just google it!
I cannot imagine how you could create an interactive game if your code is single thread. To change the box color periodically you will have to put your thread to sleep. If your game is not multi-thread, then this will freeze your application, preventing user interaction. You will find a lot of interesting materials about programming with threads in Java:
http://docs.oracle.com/javase/tutorial/essential/concurrency/
http://www.ibm.com/developerworks/library/j-thread/
http://moderntone.blogspot.com.br/2013/02/a-simple-java-multithreading-example.html
Just google it!
edited Jul 18 '15 at 0:39
answered Jul 18 '15 at 0:33
Fernando CostaFernando Costa
357416
357416
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31486395%2fiterating-through-a-list-and-drawing-a-colored-square%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
You will have to make it multi threaded if you want more then 1 thing to happen at the time. Look for example at tutorialspoint.com/java/java_multithreading.htm for a simple example of threading.
– Norbert van Nobelen
Jul 18 '15 at 0:04
1
@NorbertvanNobelen Or use a Swing Timer, which makes it safer to update the Ui from within as it won't violate the singe threaded nature of the Swing API
– MadProgrammer
Jul 18 '15 at 0:28