刷新JLabel

时间:2017-05-10 15:19:25

标签: java jtable

正如标题所说,我需要你的帮助来刷新JLabel的内容。

我解释了我的担忧。 我有一个第一个JFarm或者我有一个日历(一个DatePicker),它允许我选择一个日期和一个按钮。 当我点击按钮时,它会打开一个新窗口,在这个着名的窗口中,我有我的JLabel,或者我希望看到我的日期。

在最后一个窗口我写道:

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

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

然而我的:

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

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

你知道吗? 谢谢大家。

2 个答案:

答案 0 :(得分:0)

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

主窗口:

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();
            }   
    }   
}

感谢您的帮助。

答案 1 :(得分:0)

再次我,

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

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

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