2017-05-10 1 views
0

제목에서 알 수 있듯이 JLabel의 내용을 새로 고침해야합니다.새로 고침 JLabel

나는 내 걱정거리를 설명합니다. 첫 번째 JFarm이 있거나 날짜 및 버튼을 선택할 수있는 캘린더 (DatePicker)가 있습니다. 버튼을 클릭하면 새 창을 열어이 유명한 창에서 JLabel을 갖거나 내 날짜를보고 싶습니다. 이 마지막 창에서

내가 쓴 :

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

내가 먼저 내 창 모든 것이 잘 작동하지만 내가 그것을 닫으면, 내 DatePicker에서의 날짜를 변경 열고 내 버튼을 클릭하여 창을 다시 열면 날짜가 변하지 않습니다 !!! 전송 된 첫 번째 날짜는 항상 유지됩니다.

그러나 내 :

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

제대로 정확한 날짜마다 돌려줍니다.

아이디어가 있으십니까? 감사합니다.

+0

창을 여는 코드를 추가 할 수 있습니까? – bradimus

+0

많은 일이 발생할 수 있습니다. 즉, jLabel이 동일하다고 잘못 생각하는 대신 새로운 것을 초기화하는 것입니다. 우리가 더 잘 이해할 수 있도록 좀 더 많은 코드를 보여줄 수 있습니까? – AndreaTaroni86

답변

0

다시 저,

오류가 발견되었습니다. 내 WindowAbsence에서 :

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

가 정적이었다 패널 ... 내가 누군가를 위해 봉사 희망 !

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

감사합니다 :

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

그리고 열리는 창 나는 버튼 부재를 누를 때 너의 도움으로.

관련 문제