Обновлен текст JLabel, добавленный на другой ярлык - PullRequest
0 голосов
/ 31 января 2019

Я пытаюсь изменить текст Jlabel, который добавляется к другой метке, если условие выполнено.Но обновленный текст накладывается на предыдущий текст.

public class FGtest extends JFrame {

    public FGtest() {

        JLabel fg_layout = new JLabel();

        ImageIcon fgImageIcon = new ImageIcon(getClass().getResource("images/overall layout.JPG"));
        fg_layout.setIcon(fgImageIcon);

        Gradient gradient_layout = new Gradient();
        gradient_layout.add(fg_layout);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FGtest();
            }
        });
    }


    @SuppressWarnings("serial")
    class Gradient extends JPanel {

        private String wpl_test = "";
        private String wpl1_status = "";
        private String wpl2_status = "";

        private Jedis jedis;

        public Gradient() {
            new Timer(1000, new TimerListener()).start();
        }

        private class TimerListener implements ActionListener {


            @Override
            public void actionPerformed(ActionEvent ae) {


                try {
                    jedis = new Jedis("192.168.0.140");
                    wpl_test = jedis.get("wpl_test");
                    wpl1_status = jedis.get("wpl1_status");
                    wpl2_status = jedis.get("wpl2_status");

                    repaint();


                } catch (Exception e) {

                }
            }
        }
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2D = (Graphics2D) g;
            AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.7 f);
            g2D.setComposite(alphaComposite);



            //-------wpl test----
            JLabel label11 = new JLabel();
            label11.setFont(new Font("Times New Roman", Font.BOLD, 30));
            label11.setBounds(800, 229, 300, 100);

            label11.setForeground(Color.orange);
            fg_layout.add(label11);



            if (wpl_test.equals("1")) {

                //              label2.setVisible(false);  
                //              fg_layout.remove(label2); 
                //              label2.setBounds(800,229,0,0); 

                //            JLabel label1 = new JLabel();
                //            label1.setFont(new Font("Times New Roman",Font.BOLD,30));
                //            label1.setBounds(800,229,300,100);
                //            label1.setText("wpl 1:1");             
                //            label1.setForeground(Color.orange);
                //            fg_layout.add(label1);

                label11.setText("wpl 1:1");


                if (wpl1_status.equals("pass")) {

                    g2D.setColor(Color.green);
                    int x1[] = {
                        610,
                        1057,
                        1017,
                        520
                    };
                    int y1[] = {
                        120,
                        350,
                        485,
                        220
                    };
                    g2D.fillPolygon(x1, y1, 4);
                } else if (wpl1_status.equals("fail")) {
                    g2D.setColor(Color.red);
                    int x1[] = {
                        610,
                        1057,
                        1017,
                        520
                    };
                    int y1[] = {
                        120,
                        350,
                        485,
                        220
                    };
                    g2D.fillPolygon(x1, y1, 4);
                }

            } else if (wpl_test.equals("2")) {

                //            label1.setVisible(false); 
                //            fg_layout.remove(label11); 
                //            label1.setBounds(800,229,0,0);

                //            JLabel label2 = new JLabel();
                //            label2.setFont(new Font("Times New Roman",Font.BOLD,30));
                //            label2.setBounds(800,229,300,100);
                //            label2.setText("wpl as such"); 
                //            label2.setForeground(Color.orange);
                //            fg_layout.add(label2);

                label11.setText("wpl as such");

                if (wpl2_status.equals("pass")) {

                    g2D.setColor(Color.green);
                    int x1[] = {
                        610,
                        1057,
                        1017,
                        520
                    };
                    int y1[] = {
                        120,
                        350,
                        485,
                        220
                    };
                    g2D.fillPolygon(x1, y1, 4);
                } else if (wpl2_status.equals("fail")) {
                    g2D.setColor(Color.red);
                    int x1[] = {
                        610,
                        1057,
                        1017,
                        520
                    };
                    int y1[] = {
                        120,
                        350,
                        485,
                        220
                    };
                    g2D.fillPolygon(x1, y1, 4);
                }

            }

        }
    }
}

1 Ответ

0 голосов
/ 31 января 2019

Общий подход к таким проблемам - парадигма модель-представление-контроллер или модель-представление-презентатор.

В вашем коде я вижу

class Gradient extends JPanel {

    private String wpl_test = "";
    private String wpl1_status = "";
    private String wpl2_status = "";
    ...

, т.е.непосредственно в вашем представлении.

Обычно лучше разделить такие аспекты, как данные (модель) и представление (JLabel, ...) и логика (контроллер / презентатор).

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class Model {

    public static final String KEY_WPL_TEST = "wpl_test";
    public static final String KEY_WPL1_STATUS = "wpl1_status";
    public static final String KEY_WPL2_STATUS = "wpl2_status";

    private String wpl_test = "";
    private String wpl1_status = "";
    private String wpl2_status = "";

    private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    /**
     * The default constructor. 
     */
    public Model() {
        super();
    }

    public String getWpl_test() {
        return wpl_test;
    }

    public void setWpl_test(String wpl_test) {
        PropertyChangeEvent event = new PropertyChangeEvent(this, KEY_WPL_TEST, this.wpl_test, wpl_test);
        this.wpl_test = wpl_test;
        pcs.firePropertyChange(event);
    }

    public String getWpl1_status() {
        return wpl1_status;
    }

    public void setWpl1_status(String wpl1_status) {
        PropertyChangeEvent event = new PropertyChangeEvent(this, KEY_WPL1_STATUS, this.wpl1_status, wpl1_status);
        this.wpl1_status = wpl1_status;
        pcs.firePropertyChange(event);
    }

    public String getWpl2_status() {
        return wpl2_status;
    }

    public void setWpl2_status(String wpl2_status) {
        PropertyChangeEvent event = new PropertyChangeEvent(this, KEY_WPL2_STATUS, this.wpl2_status, wpl2_status);
        this.wpl2_status = wpl2_status;
        pcs.firePropertyChange(event);
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        pcs.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        pcs.removePropertyChangeListener(listener);
    }

    public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
        pcs.addPropertyChangeListener(propertyName, listener);
    }

    public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
        pcs.removePropertyChangeListener(propertyName, listener);
    }

}

Тогда, есть View

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class View extends JPanel {
    private final JLabel jlWpl1_status;
    private final JLabel jlWpl2_status;
    private final JLabel jlWpl_test;
    private final JButton jbUpdate;

    /**
     * The default constructor.
     */
    public View() {
        super();

        jlWpl1_status = new JLabel();
        jlWpl2_status = new JLabel();
        jlWpl_test = new JLabel();
        jbUpdate = new JButton("push me");
        // arrange the view
        this.setLayout(new BorderLayout());
        this.add(jlWpl1_status, BorderLayout.EAST);
        this.add(jlWpl_test, BorderLayout.CENTER);
        this.add(jlWpl2_status, BorderLayout.WEST);
        this.add(jbUpdate, BorderLayout.SOUTH);
    }

    public void display(Model model) {
        jlWpl1_status.setText(model.getWpl1_status());
        jlWpl2_status.setText(model.getWpl2_status());
        jlWpl_test.setText(model.getWpl_test());
    }

    public JButton getJbUpdate() {
        return jbUpdate;
    }
}

И, наконец, контроллер или презентатор, как

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

public class Controller implements PropertyChangeListener {
    /**
     * The Constant WHAT.
     */
    public static final String WHAT = "$Id$";

    private final Model model;

    private View view;

    /**
     * The default constructor.
     */
    public Controller(Model model, View view) {
        super();
        this.model = model;
        this.model.addPropertyChangeListener(this);
        this.view = view;
        this.view.display(model);
        this.view.getJbUpdate().addActionListener(x -> {
            model.setWpl_test("button pressed");
        });
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        view.display(model);
    }

}

Теперь, если есть основной метод / Application

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Application {

    /**
     * The default constructor. 
     */
    public Application() {
        super();
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        View view = new View();
        Model model = new Model();
        frame.add(view);
        frame.setSize(200, 200);
        new Controller(model, view);

        new Thread(() -> {
            try {
                Thread.sleep(5000L);

                SwingUtilities.invokeLater(() -> {
                    model.setWpl1_status("somewpl1status");
                    model.setWpl2_status("somewpl2status");
                    model.setWpl_test("sometest");
                });
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        frame.setVisible(true);
    }
}

значенияавтоматически обновляются при вызове любого установщика модели, независимо от того, вызван ли он из потока или нажатием кнопки.

...