# Making text blink in a JPanel?

• 10-31-2008, 01:46 PM
blackcloud72
Making text blink in a JPanel?
Need help trying to figure out how to make text blink or flash. I am trying to make the drawstring text "Which Way" do this. Can someone please help or point me in the right direction. I am a student just learning java so any help would be appreciated.

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.GeneralPath;
import java.util.Random;
import java.awt.Font;
import javax.swing.*;

public class Shapes extends JPanel {

public void init() {
setBackground(Color.BLACK);
}

//TM Sets X,Y Grid as Integer
public void drawShapes(int w, int h, Graphics2D z) {
GeneralPath draw = new GeneralPath(GeneralPath.WIND_EVEN_ODD);

//TM Sets Random generator
Random rx = new Random();

//Starts drawing an Arrow
draw.moveTo(w * .5f, h * .25f);
draw.lineTo(w * .4f, h * .50f);
draw.lineTo(w * .45f, h * .50f);
draw.lineTo(w * .45f, h * .75f);

draw.lineTo(w * .55f, h * .75f);
draw.lineTo(w * .55f, h * .50f);
draw.lineTo(w * .6f, h * .50f);
draw.lineTo(w * .5f, h * .25f);
//TM Ends drawing an Arrow

//TM Fills interior of arrow with color
z.fill(draw);

//TM Color Chosen by random generator
z.setColor(new Color(rx.nextInt(256),
rx.nextInt(256), rx.nextInt(256)));

//TM Loop for chosing XY location, font and color for text

int y = 1;
while (y < 11) {

//TM Sets Fonts
String fonts[] = {"Serif", "Monospaced", "Serif", "Bold", "Serif", "Italic",
};

//TM Colors
z.setColor(new Color(rx.nextInt(256),
rx.nextInt(256), rx.nextInt(256)));
//TM Font chosen + size
z.setFont(new Font(fonts[rx.nextInt(5)], rx.nextInt(10), 26));

//TM Outputs msg within specified range
z.drawString("Which Way? ", rx.nextInt(400), rx.nextInt(500));

y++;

}
}

public void paint(Graphics g) {
Graphics2D z = (Graphics2D) g;
Dimension d = getSize();
z.setBackground(getBackground());
z.clearRect(0, 0, d.width, d.height);
z.setRenderingHint(RenderingHints.KEY_ANTIALIASING ,
RenderingHints.VALUE_ANTIALIAS_ON);
drawShapes(d.width, d.height, z);
}

public static void main(String arg[]) {
final Shapes x = new Shapes();
x.init();
JFrame f = new JFrame("Tom's 2d Shape Assignment"); //TM Adds title to JPanel

public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

//TM Set Size of JPanel & Centers
f.pack();
f.setSize(new Dimension(600, 600));
f.show();
}
}
• 10-31-2008, 03:07 PM
Norm
Blinking would be to show a string and then to show nothing, repeated. Use a Timer to control when repaint is called to show whatever and a boolean flag to control what is shown.

BTW use CODE tags (from icon above input window) when entering code.
• 10-31-2008, 04:01 PM
serjant
Here the code with timer
Code:

``` import java.awt.*; import java.awt.event.*; import java.awt.geom.GeneralPath; import java.util.Random; import java.awt.Font; import javax.swing.*; public class Shapes extends JPanel { String s="Which Way? "; Timer t; private final int DELAY=200; public void init() { setBackground(Color.BLACK); t=new Timer(DELAY,new BlinkText()); t.start(); } //TM Sets X,Y Grid as Integer public void drawShapes(int w, int h, Graphics2D z) { GeneralPath draw = new GeneralPath(GeneralPath.WIND_EVEN_ODD); //TM Sets Random generator Random rx = new Random(); //Starts drawing an Arrow draw.moveTo(w * .5f, h * .25f); draw.lineTo(w * .4f, h * .50f); draw.lineTo(w * .45f, h * .50f); draw.lineTo(w * .45f, h * .75f); draw.lineTo(w * .55f, h * .75f); draw.lineTo(w * .55f, h * .50f); draw.lineTo(w * .6f, h * .50f); draw.lineTo(w * .5f, h * .25f); //TM Ends drawing an Arrow //TM Fills interior of arrow with color z.fill(draw); //TM Color Chosen by random generator z.setColor(new Color(rx.nextInt(256), rx.nextInt(256), rx.nextInt(256))); //TM Loop for chosing XY location, font and color for text int y = 1; while (y < 11) { //TM Sets Fonts String fonts[] = {"Serif", "Monospaced", "Serif", "Bold", "Serif", "Italic", "SansSerif", "Dialog", "DialogInput" }; //TM Colors z.setColor(new Color(rx.nextInt(256), rx.nextInt(256), rx.nextInt(256))); //TM Font chosen + size z.setFont(new Font(fonts[rx.nextInt(5)], rx.nextInt(10), 26)); //TM Outputs msg within specified range z.drawString(s, rx.nextInt(400), rx.nextInt(500)); y++; } } public void paint(Graphics g) { Graphics2D z = (Graphics2D) g; Dimension d = getSize(); z.setBackground(getBackground()); z.clearRect(0, 0, d.width, d.height); z.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON); drawShapes(d.width, d.height, z); } private class BlinkText implements ActionListener{         int x=0;         int y=1;         public void actionPerformed(ActionEvent e){                 x+=y;                 if(x==10000){                         s="";                         y=-1;                 }                 if(x==0){                         y=1;                         s="Which Way? ";                 }                 repaint();         } } public static void main(String arg[]) { final Shapes x = new Shapes(); x.init(); JFrame f = new JFrame("Tom's 2d Shape Assignment"); //TM Adds title to JPanel f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); //TM Set Size of JPanel & Centers f.getContentPane().add("Center", x); f.pack(); f.setSize(new Dimension(600, 600)); f.show(); } }```
The problem is that you defined Random position of the text
• 10-31-2008, 04:31 PM
blackcloud72
Thanks
Thank you all so much for your assistance. I cant wait to get home and try out the revised code serjant posted. Its my 3rd Java class and am having so much despite the great challenge it is to learn java programming.
• 10-31-2008, 04:34 PM
Norm
@serjant:
What are all the hardcoded numbers in your code for?
For example 11, 26 and 10000
• 10-31-2008, 05:02 PM
Supamagier
26 is the size of the font
11 is the length of the font array

Btw... why do you re-declare the font-array every time? Just declare it outside the loop.
• 10-31-2008, 05:15 PM
serjant
i didn't write the numbers 26,11,that's not mine,as for 100000 ,you can make it also 10,it doesn't matter
• 10-31-2008, 07:39 PM
hardwired
I tried to reduce some of the randomizing activity to help focus on
```import java.awt.*; import java.awt.event.*; import java.awt.geom.GeneralPath; import java.util.Random; import javax.swing.*; public class ShapesRx extends JPanel {     Blinker blinker = new Blinker(this);     //TM Sets Fonts     String fonts[] = {         "Serif", "Monospaced", "Serif", "Bold", "Serif", "Italic",         "SansSerif", "Dialog", "DialogInput"     };     //TM Sets Random generator     Random rx = new Random();     GeneralPath draw;     Font font;     Color[] colors = new Color[2];     Point loc;     boolean firstTime = true;     boolean showText = true;     public ShapesRx() {         setBackground(Color.BLACK);     }     //TM Sets X,Y Grid as Integer     public void drawShapes(int w, int h, Graphics2D z) {         if(firstTime) {             // You can use Path2D class in j2se 1.6+             // GeneralPath is a legacy class.             draw = new GeneralPath(GeneralPath.WIND_EVEN_ODD);             //Starts drawing an Arrow             draw.moveTo(w * .5f, h * .25f);             draw.lineTo(w * .4f, h * .50f);             draw.lineTo(w * .45f, h * .50f);             draw.lineTo(w * .45f, h * .75f);             draw.lineTo(w * .55f, h * .75f);             draw.lineTo(w * .55f, h * .50f);             draw.lineTo(w * .6f, h * .50f);             draw.lineTo(w * .5f, h * .25f);             //TM Ends drawing an Arrow             colors[0] = new Color(rx.nextInt(256),                 rx.nextInt(256), rx.nextInt(256));         }         //TM Color Chosen by random generator         z.setColor(colors[0]);         //TM Fills interior of arrow with color         z.fill(draw);         if(firstTime) {             //TM Loop for chosing XY location, font and color for text             //TM Colors             colors[1] = new Color(rx.nextInt(256),                 rx.nextInt(256), rx.nextInt(256));             //TM Font chosen + size             font = new Font(fonts[rx.nextInt(5)], rx.nextInt(10), 26);             loc = new Point(rx.nextInt(400), rx.nextInt(500));         }         if(showText) {             z.setColor(colors[1]);             z.setFont(font);             //TM Outputs msg within specified range             z.drawString("Which Way? ", loc.x, loc.y);         }         if(firstTime) {             firstTime = false;             // Safe to start after gui is realized/drawn             // and all variables have been initialized.             blinker.start();         }     }     protected void paintComponent(Graphics g) {         Graphics2D z = (Graphics2D) g;         Dimension d = getSize();         z.setBackground(getBackground());         z.clearRect(0, 0, d.width, d.height);         z.setRenderingHint(RenderingHints.KEY_ANTIALIASING,                           RenderingHints.VALUE_ANTIALIAS_ON);         drawShapes(d.width, d.height, z);     }     public void blink(boolean show) {         this.showText = show;         repaint();     }     public static void main(String arg[]) {         final ShapesRx x = new ShapesRx();         JFrame f = new JFrame("Tom's 2d Shape Assignment");         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         f.getContentPane().add("Center", x);         // You only need one of these two lines. //        f.pack();         f.setSize(new Dimension(600, 600));         f.setVisible(true);     } } class Blinker implements Runnable {     ShapesRx component;     Thread thread;     long delayOn = 1000;     long delayOff = 1000;     boolean blinking = false;     public Blinker(ShapesRx sr) {         component = sr;     }     public void run() {         while(blinking) {             component.blink(true);             try {                 Thread.sleep(delayOn);             } catch(InterruptedException e) {                 stop();             }             component.blink(false);             try {                 Thread.sleep(delayOff);             } catch(InterruptedException e) {                 stop();             }         }     }     public void start() {         if(!blinking) {             blinking = true;             thread = new Thread(this);             thread.setPriority(Thread.NORM_PRIORITY);             thread.start();         }     }     private void stop() {         blinking = false;         if(thread != null) {             thread.interrupt();         }         thread = null;     } }```
```import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; import javax.swing.border.LineBorder; public class PulsingColor {   private static final int STEPS = 60;   private static final int GREEN_VALUE = 0;   private static final Font LABEL_FONT = new Font(Font.DIALOG, Font.BOLD, 48);   private static final int DELAY = 20;   private static final String TEXT = "Pulsing Color";   private static final Dimension MAIN_SIZE = new Dimension(500, 300);   private Color[] colors = new Color[STEPS];   private JLabel label = new JLabel(TEXT);   private JButton colorBtn = new JButton("Color Button");   private MyLineBorder lineBorder = new MyLineBorder(Color.lightGray, 3, false);     private JPanel mainPanel = new JPanel();   public JPanel getMainPanel()   {     return mainPanel;   }   public PulsingColor()   {     initColors();     label.setFont(LABEL_FONT);     label.setForeground(colors[0]);         mainPanel.setBackground(Color.black);     mainPanel.setPreferredSize(MAIN_SIZE);     mainPanel.add(label);     mainPanel.add(new JLabel("  "));         final JPanel btnPanel = new JPanel(new BorderLayout());     btnPanel.setBorder(lineBorder);     btnPanel.add(colorBtn);     mainPanel.add(btnPanel);     TimerListener timerListener = new TimerListener();     timerListener.addColorChanger(new ColorChanger()     {       public void setColor(Color c)       {         label.setForeground(c);         lineBorder.setLineColor(c);         btnPanel.repaint();       }     });     new Timer(DELAY, timerListener).start();       }   private void initColors()   {     for (int i = 0; i < colors.length; i++)     {       int value = (int)(255 * (Math.cos(2 * Math.PI * (double)(i) / colors.length)+1)/2);       colors[i] = new Color(value, GREEN_VALUE, 255 - value);     }   }     private class MyLineBorder extends LineBorder   {     public MyLineBorder(Color c, int width, boolean rounded)     {       super(c, width, rounded);     }         @Override     public void paintBorder(Component c, Graphics g, int x, int y, int width,         int height)     {       super.paintBorder(c, g, x, y, width, height);     }         public void setLineColor(Color c)     {       lineColor = c;     }   }   private class TimerListener implements ActionListener   {     private int counter = 0;     private List<ColorChanger> colorChangerList = new ArrayList<ColorChanger>();         public void actionPerformed(ActionEvent e)     {       for (ColorChanger cc : colorChangerList)       {         cc.setColor(colors[counter]);       }       counter++;       counter %= colors.length;     }         public void addColorChanger(ColorChanger cc)     {       colorChangerList.add(cc);     }   }     private interface ColorChanger   {     void setColor(Color c);   }     private static void createAndShowUI()   {     JFrame frame = new JFrame("Sine Wave Blink");     frame.getContentPane().add(new PulsingColor().getMainPanel());     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     frame.pack();     frame.setLocationRelativeTo(null);     frame.setVisible(true);   }   public static void main(String[] args)   {     java.awt.EventQueue.invokeLater(new Runnable()     {       public void run()       {         createAndShowUI();       }     });   } }```