English 中文(简体)
• 更新贾瓦省其他班级的JLabel文本
原标题:Make JButton update JLabel text in other class in Java

I m writing a program for my company that references an excel file for project information. I ve organized the program into 4 JPanels, each in it s own class. i.e. Panel_1, Panel_2, etc. I have a button in panel_1 that allows the user to select the project info file and that works just fine. what I want to do is have that button apply the info from the project to the JLabels in the other JPanels 2, 3, & 4.

UI等级


public class UI extends JFrame implements ActionListener {
    
    //Variables declared outside constructor, and to be used in multiple Panels
    static String JobNo = "";
    static String JobName = "";
    static String Attention = "";
    static String Contractor = "";
    public UI() {
        
        //Define JFrame
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.getContentPane().setLayout(new GroupLayout(this.getContentPane()));
        this.setSize(FW + 36, FH);
        this.getContentPane().setBackground(col1);
        
        //Add panels to JFrame
        Panel_1 panel1 = new Panel_1();
        this.add(panel1);
        Panel_2 panel2 = new Panel_2();
        this.add(panel2);
        Panel_3 panel3 = new Panel_3();
        this.add(panel3);
        Panel_4 panel4 = new Panel_4();
        this.add(panel4);
        
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        
    }
    
    
}

小组1人

public class Panel_1 extends JPanel implements ActionListener{
    
     Panel_1() {
        
        //Define Panel_1
        this.setBounds(UI.offSet, UI.offSet, UI.p1W, UI.p1H);
        this.setBackground(UI.col2);
        this.setLayout(new GroupLayout(this));
        
        JLabel title = new JLabel("Please select Project Folder:");
        title.setBounds(20, 10, 300, 15);
        title.setForeground(UI.colText);
        this.add(title);
        
        //Text field to display project file location
        UI.field1 = new JTextField();
        UI.field1.setBounds(20, 35, 570, 20);
        UI.field1.setBackground(UI.colTF);
        UI.field1.setForeground(UI.colText);
        UI.field1.setText(UI.sDefPath);
        UI.field1.setCaretColor(UI.colText);
        UI.field1.setBorder(BorderFactory.createLoweredBevelBorder());
        UI.field1.addActionListener(this);
        this.add(UI.field1);
        
        //Browse for project file
        UI.butBrowse1 = new JButton("Browse");
        UI.butBrowse1.setBounds(600, 35, 80, 20);
        UI.butBrowse1.setBackground(UI.colBut);
        UI.butBrowse1.setForeground(UI.colBT);
        UI.butBrowse1.setBorder(BorderFactory.createEmptyBorder());
        UI.butBrowse1.setFocusable(false);
        UI.butBrowse1.addActionListener(this);
        this.add(UI.butBrowse1);
    }
     
     @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            if (e.getSource()==UI.butBrowse1) {
                
                //Choose project file location
                JFileChooser fileChoose1 = new JFileChooser(UI.sDefPath);
                fileChoose1.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                Action details = fileChoose1.getActionMap().get("viewTypeDetails");
                details.actionPerformed(null);
                fileChoose1.setPreferredSize(new Dimension(500, 600));
                fileChoose1.showOpenDialog(null);
                UI.sPath = fileChoose1.getSelectedFile().getAbsolutePath();
                
                //Assign file paths from selected folder
                UI.field1.setText(UI.sPath);
                UI.sPIPath = UI.sPath + UI.sPIadd;
                UI.sPDFPath = UI.sPath + UI.sPDFadd;
                UI.sSubPath = UI.sPath + UI.sSubadd;
                
                //Test assigned file paths
                System.out.println(UI.sPIPath);
                System.out.println(UI.sPDFPath);
                System.out.println(UI.sSubPath);
                
                //Assigning data from xlsx
                //These are the variable that I need to display in Panel_4
                UI.JobNo = XLSX_Reader.XLSX_Reader(UI.sPIPath, 0, 1);
                UI.JobName = XLSX_Reader.XLSX_Reader(UI.sPIPath, 1, 1) + "
" + XLSX_Reader.XLSX_Reader(UI.sPIPath, 2, 1);
                UI.Contractor = XLSX_Reader.XLSX_Reader(UI.sPIPath, 4, 1);
                UI.Attention = XLSX_Reader.XLSX_Reader(UI.sPIPath, 8, 1);
                
                //testing xlsx reader
                System.out.println(UI.JobNo);
                System.out.println(UI.JobName);
                System.out.println(UI.Contractor);
                System.out.println(UI.Attention);

                
            }
        }

小组4级

public class Panel_4 extends JPanel implements ActionListener{
    
     Panel_4() {
        
        //Define Panel_4
        this.setBounds((UI.offSet * 2) + UI.p1W, UI.offSet, UI.p4W, UI.p4H);
        this.setBackground(UI.col2);
        this.setLayout(new GroupLayout(this));
        
        //Doesn t update when Panel_1 assigns value to UI.Contractor
        JLabel to = new JLabel("To: " + UI.Contractor);
        to.setBounds(50, 190, 200, 30);
        to.setForeground(UI.colText);
        this.add(to);
        
        //Doesn t update when Panel_1 assigns value to UI.JobNo
        JLabel Job = new JLabel("Job No. " + UI.JobNo);
        Job.setBounds(500, 110, 100, 15);
        Job.setForeground(UI.colText);
        this.add(Job);
        
        //Doesn t update when Panel_1 assigns value to UI.Attention
        JLabel Att = new JLabel("Attention " + UI.Attention);
        Att.setBounds(350, 150, 100, 15);
        Att.setForeground(UI.colText);
        this.add(Att);
        
        //Doesn t update when Panel_1 assigns value to UI.JobName
        JLabel Re = new JLabel("Re: " + UI.JobName);
        Re.setBounds(350, 190, 100, 15);
        Re.setForeground(UI.colText);
        this.add(Re);

如果他们是同一类的,我通常会做这样的事情:

String pName = "Sam";

JLabel name = new JLabel(pName);
name.setBounds(...);
this.add(name);

JButton button = new JButton();
button.addActionListener(this);
this.add(button);
}
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource()==UI.butBrowse1) {
        pName = "Dave";
        name.setText(pName);

但是,我不知道这能否跨越各个班级。

问题回答

首先,你想 de你们的法典。 你的“投入”倡议与你的“产出”倡议之间不应有直接关系。 这将使重新使用和维持守则更加容易。

为此,你应当利用“管理者”概念。 也就是说,该模型提供数据,并以某种有意义的方式提供数据。

Add in the "observer pattern" and objects can monitor the model and take action when some state changes.

例如......

public interface Model {
    public interface Observer {
        public void modelDidChange(Model model);
    }
    
    public void addObserver(Observer observer);
    public void removeObserver(Observer observer);
    public LocalDateTime getDate();
}

这是一个非常简单的示范,但Model LocalDatetime价值的集装箱。 它还通过使用<条码>Model. 观察员提供“可观测性”,这样,在模型修改时,可以向感兴趣的各方通报情况。

At some point, we re probably going to want to change the value of the model, in this case, we can make use of a specialised model...

public interface MutableModel extends Model {
    public void setDate(LocalDateTime date);
}

这基本上描述了能够改变价值的模式。

为什么如此重要? 这种孤立的责任,并不是模型的所有消费者都希望或应当允许改变模式的状况,在此我们支持“分配关切/责任”原则。

我本人,如<代码>interface,因为它们对合同作了说明,但没有说明履约情况,因而使合同具有令人信服的灵活性。

其次,我们需要实施这些模式。 你们怎么做可能很重要,但我开始使用<条码>。 摘要Model。

public abstract class AbstractModel implements Model {
    private List<Observer> observers = new ArrayList<>();

    protected List<Observer> getObservers() {
        return observers;
    }

    @Override
    public void addObserver(Observer observer) {
        getObservers().add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        getObservers().remove(observer);
    }
    
    protected void fireModelDidChange() {
        for (Observer observer : getObservers()) {
            observer.modelDidChange(this);
        }
    }
}

采用所有其他模式都需要的核心“锅炉板”功能。 注,我没有采用<代码>getDate方法,这是故意的,因为这一数值的管理方式应当降至实际执行。

其次,我实施了“可变”模式的概念。

public class DefaultMutableModel extends AbstractModel implements MutableModel {
    private LocalDateTime date;

    @Override
    public LocalDateTime getDate() {
        return date;
    }
    
    public void setDate(LocalDateTime date) {
        this.date = date;
        fireModelDidChange();
    }
}

我认为这不言而喻。

这一切都是好的,但我们如何实际使用?

基本上,我们可以树立模式的榜样,并把它传递需要它的各种物体,这是一个“独立注射”的概念,例如......。

ActionPane

public class ActionPane extends JPanel {
    private MutableModel model;

    public ActionPane(MutableModel model) {
        this.model = model;
        setLayout(new GridBagLayout());
        setBorder(new EmptyBorder(32, 32, 32, 32));
        
        JButton btn = new JButton("Tick");
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                getModel().setDate(LocalDateTime.now());
            }
        });
        add(btn);
    }

    public MutableModel getModel() {
        return model;
    }
}

OutputPane

public class OutputPane extends JPanel {
    private Model model;
    private JLabel label;

    public OutputPane(Model model) {
        this.model = model;
        setLayout(new GridBagLayout());
        setBorder(new EmptyBorder(32, 32, 32, 32));
        
        add(getLabel());
        
        model.addObserver(new Model.Observer() {
            @Override
            public void modelDidChange(Model model) {
                label.setText(DateTimeFormatter.ISO_LOCAL_TIME.format(model.getDate()));
            }
        });
    }
    
    protected JLabel getLabel() {
        if (label != null) {
            return label;
        }
        label = new JLabel("------------");
        return label;
    }

    public Model getModel() {
        return model;
    }
}

两个小组是完美的,没有相互了解,但通过模型可以沟通。

Now, we simple create a model and the UI...

MutableModel model = new DefaultMutableModel();

add(new ActionPane(model));
add(new OutputPane(model));

而这是这样。 当模型状态发生变化时,将更新该调查。

Runnable example...

“entergraph

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
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.border.EmptyBorder;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new MainPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MainPane extends JPanel {
        public MainPane() {
            MutableModel model = new DefaultMutableModel();
            setLayout(new GridLayout(1, 2));

            add(new ActionPane(model));
            add(new OutputPane(model));
        }
    }

    public interface Model {
        public interface Observer {
            public void modelDidChange(Model model);
        }

        public void addObserver(Observer observer);

        public void removeObserver(Observer observer);

        public LocalDateTime getDate();
    }

    public interface MutableModel extends Model {
        public void setDate(LocalDateTime date);
    }

    public abstract class AbstractModel implements Model {
        private List<Observer> observers = new ArrayList<>();

        protected List<Observer> getObservers() {
            return observers;
        }

        @Override
        public void addObserver(Observer observer) {
            getObservers().add(observer);
        }

        @Override
        public void removeObserver(Observer observer) {
            getObservers().remove(observer);
        }

        protected void fireModelDidChange() {
            for (Observer observer : getObservers()) {
                observer.modelDidChange(this);
            }
        }
    }

    public class DefaultMutableModel extends AbstractModel implements MutableModel {
        private LocalDateTime date;

        @Override
        public LocalDateTime getDate() {
            return date;
        }

        public void setDate(LocalDateTime date) {
            this.date = date;
            fireModelDidChange();
        }
    }

    public class ActionPane extends JPanel {
        private MutableModel model;

        public ActionPane(MutableModel model) {
            this.model = model;
            setLayout(new GridBagLayout());
            setBorder(new EmptyBorder(32, 32, 32, 32));

            JButton btn = new JButton("Tick");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    getModel().setDate(LocalDateTime.now());
                }
            });
            add(btn);
        }

        public MutableModel getModel() {
            return model;
        }
    }

    public class OutputPane extends JPanel {
        private Model model;
        private JLabel label;

        public OutputPane(Model model) {
            this.model = model;
            setLayout(new GridBagLayout());
            setBorder(new EmptyBorder(32, 32, 32, 32));

            add(getLabel());

            model.addObserver(new Model.Observer() {
                @Override
                public void modelDidChange(Model model) {
                    label.setText(DateTimeFormatter.ISO_LOCAL_TIME.format(model.getDate()));
                }
            });
        }

        protected JLabel getLabel() {
            if (label != null) {
                return label;
            }
            label = new JLabel("------------");
            return label;
        }

        public Model getModel() {
            return model;
        }
    }
}

请注意,为了更新标签,我无需打上<代码>revalidate、invalidaterepaint。 除了给“合理”的长期价值确定初步价值外,标签(一般)是自我更新。

我提到了许多“概念”和“术语”,我强烈建议你花时间进一步研究这些概念,因为这些概念对你解决未来问题非常宝贵。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签