0

im trying to do a bar that show some messages and I got a trouble with it, check the image below to see what I have so far: https://i.stack.imgur.com/xSMtY.png

So, in the top bar, i have a panel made by myself that contains labels, each message is a label and it will roll in the panel, the problem is when the message go out of the screen i want her to go to the end of the queue, but since im using BoxLayout in my made up JPanel i can't do it, in the white bar, i got the same layout and i get the same problem, i dont know how i can keep rooling without break the chain...

(In Java)

If anyone of you can help me i will be glad for it... Thank you all in advance for your time :)

Edit: as requested i will post some code here:

this is my custom panel code:

package smstest;

import entidades.MensagemParaEcra;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import static java.lang.Thread.sleep;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @author NEMESIS
 */
public class MyPanel extends JPanel {

private JLabel label;
//private MyPanel panel;    
private LinkedList<String> texto;
private LinkedList<MensagemParaEcra> msgs;
private LinkedList<JLabel> labels;
private int x = 0, tamanho;

public MyPanel() {
    texto = new LinkedList<>();
    msgs = new LinkedList<>();
    labels = new LinkedList<>();
    //config panel
    this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    this.setBackground(Color.black);
    Dimension dim = new Dimension(1500, 30);
    tamanho = 1500;
    this.setPreferredSize(dim);
    this.repaint();
    this.addComponentListener(new ComponentListener() {
        @Override
        public void componentResized(ComponentEvent e) {
            tamanho = MyPanel.this.getWidth();
        }

        @Override
        public void componentMoved(ComponentEvent e) {
        }

        @Override
        public void componentShown(ComponentEvent e) {
        }

        @Override
        public void componentHidden(ComponentEvent e) {
        }
    });

    // start the scrolling of the labels
    start();
}



public void addMensagem(MensagemParaEcra msg) {
    labels.add(new JLabel(msg.getTexto() + "  --  "));
    refresh();
}

public void removerMsg(int id) {
    int size = msgs.size();
    for (int i = 0; i < size; i++) {
        if (msgs.get(i).getId() == id) {
            msgs.remove(i);
        }
    }
    refresh();
}

private void refresh() {

    int size = labels.size();
    labels.get(0).setLocation(0, 0);
    for (int i = 0; i < size; i++) {
        labels.get(i).setForeground(Color.white);
        labels.get(i).setFont(new Font("Tahoma", Font.BOLD, 40));
        labels.get(i).setOpaque(true);
        labels.get(i).setBackground(Color.red);
        MyPanel.this.add(labels.get(i));
        // since im using a box layout it's useless but otherwise this 
        // may add my labels one after the other
            if (i > 0) {
            int largura = labels.get(i - 1).getWidth();
            labels.get(i).setLocation(x + largura, 0);
        } else {
            labels.get(i).setLocation(x, 0);
        }
    }

}

private void start() {
    final Runnable running = new Runnable() {
        @Override
        public void run() {
            MyPanel.this.repaint();
        }
    };

    Thread t = new Thread() {
        public void run() {

            while (true) {

                for (JLabel lb : labels) {
                   // make the labels get 3 pixels to the left
                    lb.setLocation(lb.getLocation().x -3, 0);

             }

                try {
                    SwingUtilities.invokeAndWait(running);
                    sleep(30);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InvocationTargetException ex) {
                    Logger.getLogger(MyPanel.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }
    };
    t.start();
}
}

And this is the frame that have the 2 bars for the scrolling text:

package smstest;

import entidades.DadosDaAplicacao;
import entidades.MensagemParaEcra;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import static java.lang.Thread.sleep;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

/**
 *
 * @author NEMESIS
 */
public final class MonitorDeMensagensFrame extends javax.swing.JFrame {

private static final MonitorDeMensagensFrame instance = new MonitorDeMensagensFrame();
private static Point point = new Point();
private int tamanho = 1500;
private JLabel label;
private JLabel label1;


/**
 * Creates new form MonitorDeMensagensFrame
 */
public MonitorDeMensagensFrame() {
    initComponents();

    MyPanel topPanel = new MyPanel();

    // its an undecorated frame so i have the listers to move it
    this.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            point.x = e.getX();
            point.y = e.getY();
        }
    });

    this.addMouseMotionListener(new MouseMotionAdapter() {
        @Override
        public void mouseDragged(MouseEvent e) {
            Point p = getLocation();
            setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
        }
    });
    // setting the size of the frame
    setSize(getRes().width, 73);
    setLocation(0, 0);

    PanelMsg.repaint();
    // create the labels for the below bar
    criarPub();
    // add messages to the upper bar using a method in MyPanel
    // this messages now are made up for tests
    topPanel.addMensagem(new MensagemParaEcra(0, "msg 1"));
    topPanel.addMensagem(new MensagemParaEcra(1, "msg 2"));
    topPanel.addMensagem(new MensagemParaEcra(2, "msg 3"));
    topPanel.addMensagem(new MensagemParaEcra(3, "msg 4"));
    topPanel.addMensagem(new MensagemParaEcra(4, "msg 5"));
    topPanel.addMensagem(new MensagemParaEcra(5, "msg 6"));
    topPanel.addMensagem(new MensagemParaEcra(6, "msg 7"));
   // start the rolling text on the below bar
    startPub();




}

private Dimension getRes() {
    Toolkit toolkit = Toolkit.getDefaultToolkit();

    // Get the current screen size
    Dimension scrnsize = toolkit.getScreenSize();
    return scrnsize;
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    PanelMsg = new javax.swing.JPanel();
    PanelPublicidade = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setUndecorated(true);
    getContentPane().setLayout(new java.awt.GridLayout(2, 0));

    PanelMsg.setBackground(new java.awt.Color(255, 0, 0));
    PanelMsg.setMinimumSize(new java.awt.Dimension(173, 20));
    PanelMsg.setLayout(new java.awt.BorderLayout());
    getContentPane().add(PanelMsg);

    PanelPublicidade.setBackground(new java.awt.Color(102, 255, 102));
    PanelPublicidade.setMinimumSize(new java.awt.Dimension(403, 25));

    javax.swing.GroupLayout PanelPublicidadeLayout = new javax.swing.GroupLayout(PanelPublicidade);
    PanelPublicidade.setLayout(PanelPublicidadeLayout);
    PanelPublicidadeLayout.setHorizontalGroup(
        PanelPublicidadeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 806, Short.MAX_VALUE)
    );
    PanelPublicidadeLayout.setVerticalGroup(
        PanelPublicidadeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 26, Short.MAX_VALUE)
    );

    getContentPane().add(PanelPublicidade);

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new MonitorDeMensagensFrame().setVisible(true);

        }
    });
}

public static MonitorDeMensagensFrame getInstance() {
    return instance;
}

public void criarPub() {
    String msg = DadosDaAplicacao.getInstance().getMsgPublicidade();

    PanelPublicidade.setLayout(new BoxLayout(PanelPublicidade, BoxLayout.X_AXIS));
    PanelPublicidade.setBackground(Color.black);
    Dimension dim = new Dimension(1500, 30);
    PanelPublicidade.setPreferredSize(dim);
    PanelPublicidade.repaint();
    PanelPublicidade.addComponentListener(new ComponentListener() {
        @Override
        public void componentResized(ComponentEvent e) {
            tamanho = PanelMsg.getWidth();
        }

        @Override
        public void componentMoved(ComponentEvent e) {
        }

        @Override
        public void componentShown(ComponentEvent e) {
        }

        @Override
        public void componentHidden(ComponentEvent e) {
        }
    });

    label = new JLabel("");
    label1 = new JLabel("");
    label.setText(msg + " ");
    label1.setText(msg + " ");
    label.setForeground(Color.black);
    label.setFont(new Font("Tahoma", Font.PLAIN, 40));
    label.setOpaque(true);
    label.setBackground(Color.white);
    label1.setForeground(Color.black);
    label1.setFont(new Font("Tahoma", Font.PLAIN, 40));
    label1.setOpaque(true);
    label1.setBackground(Color.white);
    PanelPublicidade.add(label);
    PanelPublicidade.add(label1);
    label.setLocation(PanelPublicidade.getLocation().x, PanelPublicidade.getLocation().y);
    label1.setLocation(label.getWidth(), label.getLocation().y);
    PanelPublicidade.repaint();


}

public void startPub() {

    final int tamanho = label.getWidth();
    final Runnable running = new Runnable() {
        @Override
        public void run() {
            PanelPublicidade.repaint();
        }
    };

    Thread t = new Thread() {
        @Override
        public void run() {
            while (true) {
                label.setLocation(label.getLocation().x - 3,0);
                label1.setLocation(label1.getLocation().x - 3, 0);
//                    if(label.getLocation().x + tamanho == 0){
//                        label.setLocation(label1.getLocation().x, 0);
//                    } 


                try {
                    SwingUtilities.invokeAndWait(running);
                    sleep(28);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InvocationTargetException ex) {
                    Logger.getLogger(MonitorDeMensagensFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    };
    t.start();
}
// Variables declaration - do not modify                     
private javax.swing.JPanel PanelMsg;
private javax.swing.JPanel PanelPublicidade;
// End of variables declaration                   
}

There is the code... Thank you for the help :)

João Silva
  • 531
  • 4
  • 21
  • 40
  • I think this is what are you looking for: [Marquee effect in Java Swing](http://stackoverflow.com/questions/3617326/marquee-effect-in-java-swing). Isn't it? – dic19 Sep 20 '13 at 18:46
  • not really because this one have a break, for exemple, the text just start again when the whole label is showed... i will add multiple labels and they must go to the end o the queue for here isn't any blank spaces... – João Silva Sep 20 '13 at 19:17
  • Could you please add some code? I get a better idea in which your problem is but I don't completely understand yet. – dic19 Sep 20 '13 at 20:09
  • 1
    Ok, i will add my custom panel and my main class – João Silva Sep 20 '13 at 20:23
  • question edited, now with some code – João Silva Sep 20 '13 at 20:39
  • Try with `new FlowLayout(FlowLayout.LEADING)` as layout instead `BoxLayout`. When a `JLabel` is no longer visible, just remove it from its panel, add this label again (it should be appended at the last position) and call panel's `validate` method. See what happens. I would try myself but your code is pretty complex and sure you'll figure out faster than me – dic19 Sep 20 '13 at 21:11
  • That do the work but really badly... when it cast validate or revalidade, there is a "rollback" and a break, so for exemple, the message 1 got removed and added again and the message 2 is almost off the screen, when the message 1 is added, the message 2 goes back to left edge of the panel :\ – João Silva Sep 20 '13 at 21:46
  • What is happening (I almost sure) is your panel is moving to the left with your message 1 label. When you remove this label, then message 2 label moves to label1 location but as your panel also moved you will see it is almost off the screen. You need to set the panel to its original location (or simple remove-add this panel to your frame) when remove label1. – dic19 Sep 20 '13 at 22:02
  • The panel isnt moving and i know that because i have the frame with 2 panels, (one upper and one below) and they are painted for my tests, the MyPanel (my custom panel) is painted black, the one under him is red, since they have the same size i can see if he is moving or not and what only moves are the labels... – João Silva Sep 20 '13 at 22:33

0 Answers0