001package edu.pdx.cs410J.grader.poa.ui; 002 003import com.google.inject.Inject; 004import com.google.inject.Singleton; 005import edu.pdx.cs410J.grader.poa.GradeBookView; 006 007import javax.swing.*; 008import javax.swing.filechooser.FileNameExtensionFilter; 009import java.awt.*; 010 011@Singleton 012public class GradeBookWidget extends JPanel implements GradeBookView { 013 private final JLabel gradeBookName; 014 private final JButton loadGradeBookButton; 015 private final JButton saveGradeBookButton; 016 private final Component parentComponent; 017 018 @Inject 019 public GradeBookWidget(TopLevelJFrame parentFrame) { 020 this.parentComponent = parentFrame; 021 gradeBookName = new JLabel(); 022 loadGradeBookButton = new JButton("Load Book"); 023 saveGradeBookButton = new JButton("Save Book"); 024 saveGradeBookButton.setEnabled(false); 025 026 this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); 027 this.add(gradeBookName); 028 this.add(Box.createHorizontalStrut(3)); 029 this.add(loadGradeBookButton); 030 this.add(Box.createHorizontalStrut(3)); 031 this.add(saveGradeBookButton); 032 this.add(Box.createHorizontalGlue()); 033 } 034 035 @Override 036 public void setGradeBookName(String className) { 037 this.gradeBookName.setText(className); 038 } 039 040 @Override 041 public void addGradeBookFileListener(FileSelectedListener listener) { 042 this.loadGradeBookButton.addActionListener(e -> displayFileChooser(listener)); 043 } 044 045 @Override 046 public void canSaveGradeBook(boolean canSaveGradeBook) { 047 this.saveGradeBookButton.setEnabled(canSaveGradeBook); 048 } 049 050 @Override 051 public void addSaveGradeBookListener(SaveGradeBookListener listener) { 052 this.saveGradeBookButton.addActionListener(e -> listener.saveGradeBook()); 053 } 054 055 private void displayFileChooser(FileSelectedListener listener) { 056 JFileChooser chooser = new JFileChooser(); 057 chooser.setDialogTitle("Select Grade Book file"); 058 chooser.setApproveButtonMnemonic('l'); 059 chooser.setApproveButtonText("Load"); 060 chooser.setApproveButtonToolTipText("Load Grade Book from file"); 061 chooser.setFileFilter(new FileNameExtensionFilter("Grade Book XML files", "xml")); 062 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); 063 064 int result = chooser.showOpenDialog(parentComponent); 065 if (result == JFileChooser.APPROVE_OPTION) { 066 listener.fileSelected(chooser.getSelectedFile()); 067 } 068 } 069}