Results 1 to 9 of 9
  1. #1
    blackcloud72 is offline Member
    Join Date
    Oct 2008
    Location
    Illinois
    Posts
    2
    Rep Power
    0

    Default 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",
    "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("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
    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();
    }
    }

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,410
    Rep Power
    25

    Default

    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.

  3. #3
    serjant's Avatar
    serjant is offline Senior Member
    Join Date
    Jun 2008
    Location
    Ukraine,Zaporozhye
    Posts
    487
    Rep Power
    7

    Default

    Here the code with timer
    Java 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

  4. #4
    blackcloud72 is offline Member
    Join Date
    Oct 2008
    Location
    Illinois
    Posts
    2
    Rep Power
    0

    Default 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.

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,410
    Rep Power
    25

    Default

    @serjant:
    What are all the hardcoded numbers in your code for?
    For example 11, 26 and 10000

  6. #6
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    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.
    I die a little on the inside...
    Every time I get shot.

  7. #7
    serjant's Avatar
    serjant is offline Senior Member
    Join Date
    Jun 2008
    Location
    Ukraine,Zaporozhye
    Posts
    487
    Rep Power
    7

    Default

    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

  8. #8
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Blinking text seems pretty advanced for a third class in java.
    I tried to reduce some of the randomizing activity to help focus on
    the blinking part.
    Suggestions appear as code changes.
    Swing timers and threads can do the same work but require different
    design/setup; your choice.
    Java Code:
    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;
        }
    }

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Just to muddy the water, here's some code from a while back that causes component colors to pulsate:
    Java Code:
    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();
          }
        });
      }
    }

Similar Threads

  1. Replies: 2
    Last Post: 07-30-2008, 12:33 PM
  2. Can't refresh a JPanel/text
    By nickbeacroft in forum AWT / Swing
    Replies: 8
    Last Post: 06-23-2008, 05:23 PM
  3. Replies: 2
    Last Post: 12-01-2007, 07:48 AM
  4. Replies: 5
    Last Post: 08-11-2007, 03:14 AM
  5. How To:Use a JSlider to adjust Text size in a JPanel
    By louiebagz in forum AWT / Swing
    Replies: 2
    Last Post: 07-01-2007, 07:37 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •