Add delay of 1 second between each arc of a RainBow - java

Hi I am here add delay BETWEEN the formation of each arc of a Rainbow using Thread.delay() so that it look like an animation. When I am using Thread.delay() it delays the whole process. Is there any other method or I am doing it wrong. Please help me solve the problem
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
public class RainBow2{
static int x,y,z;
static RainBowPanel rainBow = new RainBowPanel();
static StdRainBow stdRainBow = new StdRainBow();
static JTextField xCo = new JTextField(4);
static JTextField yCo = new JTextField(4);
static JTextField angle = new JTextField(4);
static JFrame frame;
public static void main(String[] args){
Color color = new Color(135,206,250);
frame = new JFrame("Rainbow");
JPanel panel = new JPanel();
JButton draw = new JButton("Draw RainBow");
draw.addActionListener(new ListenButton());
JLabel lab1 = new JLabel("X-Coordinate");
JLabel spaceLab = new JLabel(" ");
JLabel lab2 = new JLabel("Y-Coordinate");
JLabel angleLab = new JLabel("Initial Angle");
JButton chButton = new JButton("Change Color");
chButton.addActionListener(new ListenButton());
panel.setBackground(color);
panel.add(angleLab);
panel.add(angle);
panel.add(lab1);
panel.add(xCo);
panel.add(spaceLab);
panel.add(lab2);
panel.add(yCo);
panel.add(draw);
panel.add(spaceLab);
panel.add(chButton);
frame.getContentPane().add(BorderLayout.SOUTH,panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1366,740);
frame.setVisible(true);
rainBow.addMouseListener(new RainBowList());
frame.getContentPane().add(rainBow);
}
static class RainBowList extends MouseAdapter implements MouseMotionListener{
public void mouseClicked(MouseEvent e){
x = e.getX();
y = e.getY();
rainBow.drawing(x, y, 0);
}
}
static class ListenButton implements ActionListener{
public void actionPerformed(ActionEvent a){
if(a.getActionCommand().equals("Draw RainBow")){
x = Integer.parseInt(xCo.getText());
y = Integer.parseInt(yCo.getText());
z = Integer.parseInt(angle.getText());
rainBow.drawing(x, y,z);
}
if(a.getActionCommand().equals("Change Color")){
rainBow.drawing(x, y,z);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
public class RainBowPanel extends JPanel{
int x,y,z;
public void drawing(int xx, int yy, int zz){
Color color = new Color(135,206,250);
setBackground(color);
z = zz;
x = xx;
y = yy;
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
int length = 300;
int width = 300;
x = x-length/2;
y = y-width/2;
for(int i =0 ; i< 7;i++){
Color color = new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255));
g.setColor(color);
g.fillArc(x,y,length ,width ,z,180 );
x=x+15;
y=y+15;
length = (length-30);
width = (width-30);
try{
Thread.sleep(200);
}catch(Exception e){
}
}
}
}
}

When I am using Thread.delay() it delays the whole process.
A painting method is for painting only. You should not be causing the Thread to delay. This will prevent the GUI from repainting itself until the entire loop is finished executing.
Instead you can use a Swing Timer to schedule the repainting.
Instead of doing the painting in the paintComponent() you should maybe paint to a BufferedImage. Then you can display the Image in an ImageIcon on a JLabel.
So when the Timer event is generated you paint a color of the rainbow. After all 7 colors are painted you stop the Timer.
Read the section from the Swing tutorial on How to Use Swing Timers for more information and examples.

Related

my app stops working when I put a while loop

im creating a app with java for making app easyer than coding it but when i started i created two inputs for height and width and a button to create a frame with that informatiion. then i made a while loop to if the number of the height or width changes, change the width and height of the new frame. after that my app stops working and freeze.
i tried to making a jpanel not a jframe or creating a method for that but still freesing.
what do i do to not freeze?
Main.java
public class Main {
public static void main(String[] args) {
new Frame();
}
}
Frame.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Frame extends JFrame implements ActionListener {
SpinnerNumberModel modelheight;
JSpinner heightinp;
SpinnerNumberModel modelwidth;
JSpinner widthinp;
JButton newframebutton;
private int heightdyn;
private int height;
private int widthdyn;
private int width;
private boolean framerunning= false;
Frame(){
//-inputs------------------------------------------------------
modelheight = new SpinnerNumberModel(500,0,2000,1);
modelwidth = new SpinnerNumberModel(500,0,2000,1);
heightinp = new JSpinner(modelheight);
heightinp.setBounds(25,25,250,50);
widthinp = new JSpinner(modelwidth);
widthinp.setBounds(25,100,250,50);
//--give-value-------------------------------------------------
heightdyn = (int) heightinp.getValue();
height = heightdyn;
widthdyn = (int) widthinp.getValue();
width = widthdyn;
//--button-manager---------------------------------------------
newframebutton = new JButton("New Frame");
newframebutton.setBounds(25,175,50,50);
newframebutton.addActionListener(this);
//--frame-manager----------------------------------------------
JPanel framepanel = new JPanel();
framepanel.setPreferredSize(new Dimension(600,600));
framepanel.setLayout(null);
framepanel.add(heightinp);
framepanel.add(widthinp);
framepanel.add(newframebutton);
this.add(framepanel);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(3);
this.getContentPane().setBackground(new Color(255, 255, 255));
this.setLocationRelativeTo(null);
this.setResizable(false);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==newframebutton){
JFrame frame = new JFrame();
height = heightdyn;
width = widthdyn;
framerunning = true;
frame.setSize(width,height);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
while (framerunning){
heightdyn = (int) heightinp.getValue();
widthdyn = (int) widthinp.getValue();
if (height != heightdyn || width != widthdyn){
frame.setSize(widthdyn,heightdyn);
height = heightdyn;
width = widthdyn;
}
}
}
}
}
while (framerunning) after setting framerunning=true. Also, you are not modifying framerunning variable inside the while loop. So, the system will go in an infinite loop. So, ultimately your thread will get blocked at that point.

Trying to use actionListener to turn a String upside down

From my textbook:
"Write an application that extends JFrame and that displays a phrase upside down when the user click a button. The phrase is displayed normally when the user clicks the button again."
Currently I have a String that is drawn using the paint() method and a Graphic object. The String is visible in the JUpsideDown frame and it's upside down and positioned in about the middle of the panel. I've added my button and a actionListener but I think the code in my actionPerformed method is wrong because I'm trying to make the negative font size a positive by multiplying by -1 but it doesn't seem to take effect when I repaint. The String positioned is moved to x = 100 ad y = 100 but the String is still upside down.
Any kind of guidance is appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class JUpsideDown extends JFrame implements ActionListener
{
int x = 350;
int y = 100;
int fontSize = -26;
Font font = new Font("Serif", Font.PLAIN, fontSize);
JButton press = new JButton("Flip Text");
String label = "Look at this text, it will flip!";
public JUpsideDown()
{
setTitle("JUpsideDown");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(press);
press.addActionListener(this);
}
public void paint(Graphics g)
{
super.paint(g);
g.setFont(font);
g.drawString(label, x, y);
}
public void actionPerformed(ActionEvent e)
{
fontSize = fontSize * -1;
x = 100;
y = 100;
repaint();
}
public static void main(String[] args)
{
JUpsideDown frame = new JUpsideDown();
frame.setSize(450, 200);
frame.setVisible(true);
}
}
Your logic is right, although you need to instantiate again a new Font object which will encapsulate the new fontsize. This should be performed after the button is clicked inside actionPerformed() method. In this way the behavior of the application will be the expected.
Below you may find a possible solution:
public void actionPerformed(ActionEvent e)
{
fontSize = fontSize * -1;
x = 100;
y = 100;
font = new Font("Serif", Font.PLAIN, fontSize); //added line
repaint();
}

JLabel duplicates itself

I'm trying to replicate an existing game for learning purposes. The code below creates a JFrame with squares that will be filled with labels and images, however, the "Start" label seems to replicate itself. I have some experience with Java, but I'm still a student. (Nearly no experience with Swing). I added the label to the frame instead of the panel because the squares I drew hide the label. Thanks :D
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test{
public static void main(String[] args){
JFrame frame = new JFrame("Miau");
MyPanel panel = new MyPanel();
frame.setVisible(true);
frame.setSize(600,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
JLabel labelstart = new JLabel("Start");
frame.add(labelstart);
labelstart.setLocation(100, 100);
labelstart.setSize(30,14);
}
}
class MyPanel extends JPanel {
public void paint(Graphics g) {
g.setColor(Color.black);
//g.fillRect(10,10,570,100);
int posx = 10;
int posy = 120;
g.drawRect(10,10,570,100);
g.drawRect(posx,posy,570,430);
int size = 5;
int width = 570/size;
int height = 430/size;
for(int m=0;m<size;m++){
for(int n=0;n<size;n++){
g.drawRect(posx,posy,width,height);
posx += width;
}
posx = 10;
posy += height;
}
}
}
I found a valid solution to my problem. I used label.setBounds(positionx,positiony,boundx,boundy). I'm trying to make a simple game that uses a refreshing JPanel, and it's working.

java paint applet - need help adding action on radio buttons

I need to make a java applet that allows the user to paint with the mouse. When the applet is launched, a second window opens that allows the user to select one of 6 different colors to paint with.
First, I wrote code to construct a toolbar window which contains a getcurrentcolor method. I can't seem to link the button press with the color change.
If I launch the applet, the toolbarwindow opens successfully and I'm able to paint in black, so my only problem is selecting a color on the toolbar window and painting in that color.
toolbar code:https://gist.github.com/anonymous/3c053c69112f46d17440
painting applet code: https://gist.github.com/anonymous/aca7929dbcfc08008f30
I gave an approach here for 3 buttons, you can add the rest. The idea is that you keep a currently selected color field and update it each time a button is selected via the ActionListener. A map from the button to the color it represents is not necessary, but makes the code more manageable.
public class ToolBarWindow extends JFrame {
private static Map<JRadioButton, Color> colors = new HashMap<>();
private static Color currentColor = Color.BLACK;
public static void main(String[] args) {
ToolBarWindow frame = new ToolBarWindow();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Colors");
frame.setVisible(true);
}
public ToolBarWindow() {
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(3, 1));
// put the other colors
JRadioButton red = new JRadioButton("red");
JRadioButton black = new JRadioButton("black");
JRadioButton magenta = new JRadioButton("magenta");
red.addActionListener(new MyActionListener());
black.addActionListener(new MyActionListener());
magenta.addActionListener(new MyActionListener());
jpRadioButtons.add(red);
jpRadioButtons.add(black);
jpRadioButtons.add(magenta);
colors.put(red, Color.RED);
colors.put(black, Color.BLACK);
colors.put(magenta, Color.MAGENTA);
add(jpRadioButtons, BorderLayout.WEST);
ButtonGroup bg = new ButtonGroup();
bg.add(red);
bg.add(black);
bg.add(magenta);
}
Color getCurrentColor() {
return currentColor;
}
private class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
currentColor = colors.get(e.getSource());
}
}
}
I get the feeling your professor wants you to make your own. Here is an example I threw together in 10 minutes or so. its very rough and lacking good coding style but if you need to know what is involved, it should be useful. The example code prints out the color whenever you have selected it.
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
public class MyColorChooser extends Component
{
private Color[] colors;
private Color selectedColor;
public MyColorChooser(Color ... colors)
{
this.colors = colors;
this.selectedColor = colors[0];
this.addMouseListener
(
new MouseAdapter()
{
#Override public void mouseClicked(MouseEvent e)
{
int tileWidth = MyColorChooser.this.getWidth();
tileWidth /= MyColorChooser.this.colors.length;
int index = e.getX()/(tileWidth);
MyColorChooser.this.selectedColor = MyColorChooser.this.colors[index];
}
}
);
}
#Override public void paint(Graphics renderer)
{
int width = this.getWidth()/this.colors.length;
int height = this.getHeight();
for(int i = 0; i < this.colors.length; i++)
{
renderer.setColor(this.colors[i]);
renderer.fillRect(width*i,0,width,height);
}
}
public Color getSelectedColor()
{
return this.selectedColor;
}
public static void main(String ... args) throws Throwable
{
JFrame f = new JFrame();
f.setSize(200,100);
f.getContentPane().setLayout(null);
MyColorChooser chooser = new MyColorChooser
(
Color.RED,
Color.GREEN,
Color.BLUE,
Color.YELLOW,
Color.WHITE,
Color.BLACK
);
f.getContentPane().add(chooser);
chooser.setBounds(0,0,200,50);
f.setVisible(true);
Color lastColor = chooser.getSelectedColor();
for(;;)
{
if(!chooser.getSelectedColor().equals(lastColor))
{
lastColor = chooser.getSelectedColor();
System.out.printf("Selected Color:%s\n",lastColor.toString());
}
Thread.sleep(100);
}
}
}

How to take ints from Action Event into an array to create a circle in Java?

I am having a huge problem in Java creating a GUI that takes input from a user and creates a circle based on that input. I am taking input from the user and holding the values within the getUserX, getUserY, getRadius and circleColor, however I have no idea how to pass these variables into an array that's used by the paint component to make a circle.
How do I properly take the value of the getUserX, getUserY and getRadius variables and put them into the circleValues array? How do I take the circleColor taken from the user's input and put it as the page.setColor value for the created circle?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CircleMaker
{
public static void main (String[] args)
{
BuildsFrame();
}
public static void BuildsFrame()
{
JFrame frame = new JFrame ("Circle Drawer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tp = new JTabbedPane();
tp.addTab ("Intro", new IntroPanel());
tp.addTab("Your Circle!", new CirclePanel());
frame.getContentPane().add(tp);
frame.pack();
frame.setVisible(true);
}
}
class IntroPanel extends JPanel
{
public IntroPanel()
{
final JTextField xCoorTF, yCoorTF, radiusTF;
int userXcoor, userYcoor, userRadius;
JButton makeButton = new JButton("Create!");
final JColorChooser colorChooser;
setLayout (new FlowLayout());
setBackground (Color.gray);
setPreferredSize (new Dimension(700, 500));
JLabel l1 = new JLabel ("Enter your desired coordinates and radius for your circle.");
JLabel l2 = new JLabel ("Please type the X coordinate in the first box, the");
JLabel l3 = new JLabel ("Y coordinates in the second box,");
JLabel l4 = new JLabel ("and the radius of your circle");
JLabel l5 = new JLabel ("in the final box.");
xCoorTF = new JTextField(5);
yCoorTF = new JTextField(5);
radiusTF = new JTextField(5);
colorChooser = new JColorChooser();
colorChooser.setBorder(BorderFactory.createTitledBorder("Choose Circle Color:"));
makeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e){
int getUserX = Integer.parseInt(xCoorTF.getText());
int getUserY = Integer.parseInt(yCoorTF.getText());
int getRadius = Integer.parseInt(radiusTF.getText());
Color circleColor = colorChooser.getColor();
System.out.println(getUserX);
System.out.println(getUserY);
System.out.println(getRadius);
}
});
add (l1);
add (l2);
add (l3);
add (l4);
add (l5);
add (xCoorTF);
add (yCoorTF);
add (radiusTF);
add (colorChooser);
add (makeButton);
}
}
class CirclePanel extends JPanel
{
int[] circleValues = {50, 50, 100};
circleValues[0] = getUserX;
circleValues[1] = getUserY;
circleValues[2] = getRadius;
public CirclePanel()
{
setBackground (Color.WHITE);
}
public void paintComponent (Graphics page)
{
super.paintComponent (page);
page.setColor (Color.BLACK);
page.fillOval((circleValues[0] - 2), (circleValues[1] - 2), (circleValues[2] + 4), (circleValues[2] + 4));
page.setColor (Color.GRAY);
page.fillOval (circleValues[0], circleValues[1], (circleValues[2]), (circleValues[2]));
}
}
Unlike many other languages, commands cannot be "floating in space" in Java.
You will need to raise the scope of that data as well as move your circleValues array fill to a segment of code that will be executed.

Categories

Resources