繁体   English   中英

刷新JLabel

[英]refresh a JLabel

就像标题所说的那样,我需要您的帮助来刷新JLabel的内容。

我解释我的担心。 我有第一个JFarm或我有一个日历(一个DatePicker),可以选择一个日期和一个按钮。 当我单击按钮时,它将打开一个新窗口,在这个著名的窗口中,我有我的JLabel或我想查看我的日期。

在最后一个窗口中,我写道:

System.out.println(datePicker.getDate());
labelDate.setText(datePicker.getDate());

当我第一次打开我的窗口时,一切正常,但是如果我关闭它,则可以在DatePicker中更改日期,然后通过单击按钮重新打开窗口,日期不会改变! 它始终保留在发送的第一个日期。

但是我的:

System.out.println(datePicker.getDate());

每次正确返回正确的日期。

你有想法吗 ? 谢谢你们。

我发布了完整的代码,但是它很长而且不是很干净...对不起。

主窗口:

public class App extends JFrame{

    private JPanel contentPane;
    static final int rowMultiplier = 4;
    private DatePicker datePicker;


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    App frame = new App();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public App()  throws SQLException{
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        this.setTitle("Absences Management");
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);


// =================== PanelTitle ===================================       
        JPanel panelTitle = new JPanel();
        contentPane.add(panelTitle, BorderLayout.NORTH);

        JLabel labelTitle = new JLabel("Absence Management");
        panelTitle.add(labelTitle);

// ================== PanelMenu =====================================
        JPanel panelMenu = new JPanel();
        contentPane.add(panelMenu, BorderLayout.WEST);
        panelMenu.setLayout(new BoxLayout(panelMenu, BoxLayout.Y_AXIS));


        // Border and name for the panel
        panelMenu.setBorder(BorderFactory.createTitledBorder(" Menu "));


        // create buttons and set the actions for the menu
        JButton buttonAddClass = new JButton(new ActionButtonClassManagement(this,"Class management"));
        JButton buttonQuit = new JButton(new ActionButtonQuit(this,"     Quit     "));


        // add different components in the Panel Menu
        panelMenu.add(buttonAddClass);
        panelMenu.add(buttonQuit);



// ================= PanelCalendar ==================================       

        JPanel panelCalendar = new JPanel();
        contentPane.add(panelCalendar, BorderLayout.CENTER);
        panelCalendar.setAlignmentX(CENTER_ALIGNMENT);

        // black border for the panel
        panelCalendar.setBorder(BorderFactory.createTitledBorder(" Calendar "));

        JLabel labelCalendar = new JLabel("CALENDAR :");        
        panelCalendar.add(labelCalendar);

        // ===== create the calendar
        // settings
        DatePickerSettings dateSettings = new DatePickerSettings();
        dateSettings.setVisibleClearButton(false);
        // set the current date by default
        dateSettings.setAllowEmptyDates(false);

        datePicker = new DatePicker(dateSettings);


        // create a icon
        URL dateImageURL = FullDemo.class.getResource("/img/calendar20x20.png");
        Image calendarImage = Toolkit.getDefaultToolkit().getImage(dateImageURL);
        ImageIcon calendarIcon = new ImageIcon(calendarImage);

        // create button and set the icon
        JButton datePickerButton = datePicker.getComponentToggleCalendarButton();
        datePickerButton.setText("");
        datePickerButton.setIcon(calendarIcon);

        // add the calendar to the PanelCalendar
        panelCalendar.add(datePicker);
        // create a button Show absences
        JButton buttonAbsence = new JButton(new ActionButtonAbsences(this,"Absences", datePicker));

        //add the button to the panelCalendar
        panelCalendar.add(buttonAbsence);

    }

}

我的按钮缺席的课程:

public class ActionButtonAbsences extends AbstractAction{

    private App windowAbsence;
    private DatePicker datePicker = new DatePicker();
    private String dateString = new String();

    public ActionButtonAbsences(App app, String textButton, DatePicker datePicker) {
        // TODO Auto-generated constructor stub
        super(textButton);  
        this.datePicker = datePicker;
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub  
        dateString = datePicker.getText();
        WindowAbsence fen = new WindowAbsence(windowAbsence, datePicker, dateString);
    }
}

当我按下“缺勤”按钮时打开的窗口:

public class WindowAbsence extends JDialog implements ActionListener{


    private static JPanel panelWindow = new JPanel(new BorderLayout());
    private JPanel panelTitle = new JPanel();
    private JPanel panelWindowLeft = new JPanel();
    private JPanel panelWindowRight = new JPanel(); 

    private JComboBox comboBoxClass;
    private JComboBox comboBoxStudent;
    private DatePicker datePicker;
    private JLabel labelDate = new JLabel();
    private String dateString = new String();

    private ModelTable modelTableAbsence = new ModelTable();
    private JTable tableAbsence = new JTable(modelTableAbsence);


    public WindowAbsence(Frame frame, DatePicker datePicker, String date){
        //super call the constructor of the main window
        // the first argument is the mother window
        // the second argument disable this window
        super(frame,true);

        labelDate.setText(datePicker.getText());

        this.dateString = date;


        // add BorderLayout in this Window
        this.setLayout(new BorderLayout());

        // name of the window
        this.setTitle("Absences");
        // size of the window
        this.setSize(700, 600);
        // effect for the red cross
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setLocationRelativeTo(null);

        this.datePicker = datePicker;

        // =================== Data bases connection ============================               
        /**
        * download mysql-connector-java-5.1.40.tar.gz
        * https://dev.mysql.com/downloads/file/?id=470332
        * Clic droit sur le dossier du projet
        * Clic right on the folder of the project
        * Build Path
        * Add external Archive
        */

        DataBase database = new DataBase();
        String url = "jdbc:mysql://localhost:3306/AbsenceManagement";
        String user = "root";
        String pass = "";
        String driver = "com.mysql.jdbc.Driver";

        try {
            database.connectionDataBase(url, user, pass, driver);


    // ================== PANEL TITLE ==================================
            //JLabel labelDate = new JLabel();
            panelTitle.add(labelDate);
            //labelDate.setText(datePicker.getText());
            date = datePicker.getText();

            System.out.println("date: "+date);
            labelDate.setText(date);


            panelWindow.add(panelTitle, BorderLayout.NORTH);

        // ================ PANEL LEFT =====================================
        panelWindowLeft.setBorder(BorderFactory.createTitledBorder(" Absences "));
            // =========== panelComboBoxLabelClass ======================
        JPanel panelLabelComboBoxClass = new JPanel();
        panelLabelComboBoxClass.setLayout(new BoxLayout(panelLabelComboBoxClass, BoxLayout.LINE_AXIS));
        JLabel labelComboBoxClass = new JLabel("Class :");
        comboBoxClass = new JComboBox();
        comboBoxClass.addItem("");
        panelLabelComboBoxClass.add(labelComboBoxClass);
        panelLabelComboBoxClass.add(comboBoxClass);     


        Statement statementClass = DataBase.connection.createStatement();
        ResultSet resultClass = statementClass.executeQuery("SELECT class FROM Class");

        //receive the MetaData
        ResultSetMetaData resultMetaClass = (ResultSetMetaData) resultClass.getMetaData();

        // add the data in the row
        while(resultClass.next()){
            comboBoxClass.addItem(resultClass.getObject(1));
        }

        comboBoxClass.addActionListener(this);


        resultClass.close();
        statementClass.close();

            // =========== panelComboBoxLabelStudent ======================
        JPanel panelLabelComboBoxStudent = new JPanel();
        panelLabelComboBoxStudent.setLayout(new BoxLayout(panelLabelComboBoxStudent, BoxLayout.LINE_AXIS));
        JLabel labelComboBoxStudent = new JLabel("Student :");
        comboBoxStudent = new JComboBox();
        panelLabelComboBoxStudent.add(labelComboBoxStudent);
        panelLabelComboBoxStudent.add(comboBoxStudent); 

        // ========== panelComboBoxHour ===============================
        int rowMultiplier = 4;
        int row = rowMultiplier;

        TimePickerSettings timeSettings = new TimePickerSettings();
        timeSettings.setDisplayToggleTimeMenuButton(true);
        timeSettings.setDisplaySpinnerButtons(false);



        JPanel panelComboBoxHour = new JPanel();
        panelComboBoxHour.setLayout(new BoxLayout(panelComboBoxHour, BoxLayout.LINE_AXIS));


        JLabel labelComboBoxFrom = new JLabel("From :");
        panelComboBoxHour.add(labelComboBoxFrom);

        TimePicker timePickerFrom = new TimePicker(timeSettings);
        timePickerFrom = new TimePicker();
        panelComboBoxHour.add(timePickerFrom, getConstraints(1, (row * rowMultiplier), 1));
        //panelComboBoxHour.addLabel(panelComboBoxHour, 1, (row++ * rowMultiplier), "Time 1, Default Settings:");


        JLabel labelComboBoxTo = new JLabel("To :");
        panelComboBoxHour.add(labelComboBoxTo);

        TimePicker timePickerTo = new TimePicker();
        timePickerTo = new TimePicker();
        panelComboBoxHour.add(timePickerTo, getConstraints(1, (row * rowMultiplier), 1));

        // ========== panel button add absence ==============
        JPanel panelButtonAddAbsence = new JPanel();
        panelButtonAddAbsence.setLayout(new BoxLayout(panelButtonAddAbsence, BoxLayout.LINE_AXIS));

        JButton buttonAddAbsence = new JButton("Add Absence");
        panelButtonAddAbsence.add(buttonAddAbsence);
        // ========================================

        panelWindowLeft.setLayout(new BoxLayout(panelWindowLeft, BoxLayout.PAGE_AXIS));
        panelWindowLeft.add(panelLabelComboBoxClass);
        panelWindowLeft.add(panelLabelComboBoxStudent);
        panelWindowLeft.add(panelComboBoxHour);
        panelWindowLeft.add(panelButtonAddAbsence);

        panelWindow.add(panelWindowLeft, BorderLayout.WEST);
        // ====================== PANEL RIGHT ================================


        panelWindowRight.setBorder(BorderFactory.createTitledBorder(" Absences "));


        //=================== TABLE =======================================

        Statement statementAbsence = DataBase.connection.createStatement();
        // requet SQL
        ResultSet resultAbsence;
        ResultSetMetaData resultMetaAbsence;        

        modelTableAbsence.addColumn("Student");
        modelTableAbsence.addColumn("Date");
        modelTableAbsence.addColumn("To");
        modelTableAbsence.addColumn("From");

        // requete SQL 
        resultAbsence = statementAbsence.executeQuery("SELECT * FROM Absence WHERE `dateAbsence`='"+datePicker.getDate().toString()+"'");

        //receive the MetaData
        resultMetaAbsence = (ResultSetMetaData) resultAbsence.getMetaData();
        modelTableAbsence.fireTableDataChanged();

        if(!resultAbsence.next()){
            System.out.println("null");
        }else{
            // add the data in the row
            do{
                  modelTableAbsence.addRow(new Object[]{
                          resultAbsence.getObject(2).toString(),
                          resultAbsence.getObject(3).toString(),
                          resultAbsence.getObject(4).toString(),
                          resultAbsence.getObject(5).toString()
                  });
            }while(resultAbsence.next());
            // close the statementClass
            statementAbsence.close();
            resultAbsence.close();


            // =========  replace id student by firstName and lastName
            Statement statementNameStudent = DataBase.connection.createStatement();
            ResultSet resultNameStudent = null;

            int nbRow = modelTableAbsence.getRowCount();
            for(int i = 0; i < nbRow; i++){

                resultNameStudent = statementNameStudent.executeQuery("SELECT firstName, lastName FROM Student WHERE `id`='"+modelTableAbsence.getValueAt((i), 0)+"'");
                // add the data in the row
                  while(resultNameStudent.next()){
                      modelTableAbsence.setValueAt(
                              (resultNameStudent.getObject(1)+" "+resultNameStudent.getObject(2)),i,0);
                  }
            }
            statementNameStudent.close();
            resultNameStudent.close();

        }

        // =================================================================
        JScrollPane scrollPane = new JScrollPane(tableAbsence);

        panelWindowRight.add(scrollPane);
        panelWindow.add(panelWindowRight, BorderLayout.CENTER);

        this.setContentPane(panelWindow);
        this.setVisible(true);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth) {
        GridBagConstraints gc = new GridBagConstraints();
        gc.fill = GridBagConstraints.NONE;
        gc.anchor = GridBagConstraints.WEST;
        gc.gridx = gridx;
        gc.gridy = gridy;
        gc.gridwidth = gridwidth;
        return gc;
}
    // model table for table schedule
    public class ModelTableSchedule extends DefaultTableModel {
        ModelTableSchedule(Object[][] dataStudent, String[] columnNamesStudent) {
            super(dataStudent, columnNamesStudent);
        }
        // the function return always false, the table is never editable
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    }

    public void actionPerformed(ActionEvent arg0) {


        modelTableAbsence.fireTableDataChanged();


        // =================== Data bases connection ============================               
        /**
        * download mysql-connector-java-5.1.40.tar.gz
        * https://dev.mysql.com/downloads/file/?id=470332
        * Clic droit sur le dossier du projet
        * Clic right on the folder of the project
        * Build Path
        * Add external Archive
        */

        DataBase database = new DataBase();
        String url = "jdbc:mysql://localhost:3306/AbsenceManagement";
        String user = "root";
        String pass = "";
        String driver = "com.mysql.jdbc.Driver";

            try {
                database.connectionDataBase(url, user, pass, driver);

                // add value in ComboBox
                Statement statementStudent;
                comboBoxStudent.removeAllItems();
                statementStudent = DataBase.connection.createStatement();
                ResultSet resultStudent = statementStudent.executeQuery("SELECT * FROM `Student` WHERE `class` LIKE '"+comboBoxClass.getSelectedItem().toString()+"'");
                //receive the MetaData
                ResultSetMetaData resultMetaStudent = (ResultSetMetaData) resultStudent.getMetaData();      
                // add the data in the row
                while(resultStudent.next()){
                    comboBoxStudent.addItem((resultStudent.getObject(2)+" "+resultStudent.getObject(3)));
                }
                comboBoxStudent.revalidate();
                resultStudent.close();
                statementStudent.close();

            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
    }   
}

谢谢您的帮助。

我也是

我发现我的错误! 在我的WindowAbsence中:

private static JPanel panelWindow = new JPanel(new BorderLayout());

静态的面板...我希望能为某人服务!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM