1

I am working on a java program, what I want to implement is once the window loads, the set of text in a JTextPane to change. I have the below code that creates the JTextPane;

JTextPane txtpnReady = new JTextPane();
        txtpnReady.setText("Ready");
        txtpnReady.setEditable(false);
        txtpnReady.setBounds(181, 39, 169, 20);
        contentPane.add(txtpnReady);

I am unsure of how to add a timer that will change the text of this JTextPane, after 2 seconds, I need it to say Ready once the program loads, then after 2 seconds Steady and then after 2 seconds, Go.

Thanks.

dic19
  • 17,821
  • 6
  • 40
  • 69

1 Answers1

3

You may want to take a look to How to Use Swing Timers trail. You can do something like this:

    Timer timer = new Timer(2000, new ActionListener() {

        private String nextText = "Steady";

        @Override
        public void actionPerformed(ActionEvent e) {
            txtpnReady.setText(nextText);
            if(!nextText.equals("Go")) {                    
                nextText = "Go";
            } else {
                ((Timer)e.getSource()).stop();
            }
        }
    });

    timer.setRepeats(true);
    timer.setDelay(2000);
    timer.start();

Off-topic

About this:

txtpnReady.setBounds(181, 39, 169, 20);

The use of setBounds() is not a good practice since swing applications must be able to run on different platforms and Look & feels. You should let layout managers do their job and avoid the use of setBounds() and set(Preferred|Maximum|Minimum)Size.

Suggested readings:

Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69
  • Hi, What can i use instead of setBounds to position the compononents on a window. Thanks for helping me out btw, that was exactly what I needed. Hi, just another quick question, does the swing library have built in shapes, what I need is a triangle, or do I need to import an image. – user3253675 Jan 30 '14 at 16:32
  • @user3253675 glad to help. 1) Components positioning and sizing are tasks handled by layout managers: see the link I've posted. 2) You can import an image or you can learn about [Performing Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/) on Swing components. 3) If my answer worked for you then don't forget to "accept" it: [How does accepting an answer work?](http://meta.stackexchange.com/a/5235). – dic19 Jan 30 '14 at 16:54