开发者

Issue with adding statusbar to a JFrame

I have a class that extends JFrame and packs two Jpanels onto it one being a statusbar JPanel and other being a contentDisplay Panel.

Based on the changes made in the contentDisplay panel, I need to dynamically change the label text in the status bar Jpanel. To achieve this, I've created a separate class for statusbar Panel with the following code.

public class StatusBar extends JPanel {
    JLabel status;
    /** Creates a new instance of StatusBar */
    public StatusBar() {
        super();
        status = new J开发者_如何学JAVALabel("Ready and Running");
        this.add(status);       
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);            
        g.drawString(status.getText(), 10,10);
      }

    public void setMessage(String message) {
        status.setText("Status : " + message);          
        repaint();
    }
}

I have created an object of this class and added it onto the JFrame. The panel is added but when I call the setMessage() method in the subsequent implementation of the frame, the message is not getting repainted i.e. the status panel is not refreshing the status message. How can I solve this issue?

PS: I donot want to revalidate() and repaint() my parent JFrame for every change in status. I just want the status panel to be refreshed every time as the above code. Is there a way to do this?


You shouldn't need the paintComponent call... This should do:

public class StatusBar extends JPanel {
    JLabel status;

    public StatusBar() {
        this.setLayout( new FlowLayout(FlowLayout.LEFT, 5, 0 ) ) ;
        status = new JLabel("Ready and Running");
        this.add(status);       
    }

    public void setMessage(String message) {
        status.setText("Status : " + message);          
    }
}

Or indeed you could just use a class that extends JLabel

public class StatusBar extends JLabel {

    public StatusBar() {
        setMessage( "Ready and Running" );
    }

    public void setMessage( String message ) {
        setText( message ) ;        
    }        
}


not updating of the gui is a general know issue, in this tutorial is explained exactly what is causing your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜