/** Set the contents of the field selector list. */
  private void setupFieldSelector() {
    fieldListModel.clear();
    SortedSet<String> contents = new TreeSet<String>();
    for (String s : metaData) {
      if (s.startsWith(Globals.SELECTOR_META_PREFIX)) {
        contents.add(s.substring(Globals.SELECTOR_META_PREFIX.length()));
      }
    }
    if (contents.size() == 0) {
      // if nothing was added, put the default fields (as described in the help)
      fieldListModel.addElement("author");
      fieldListModel.addElement("journal");
      fieldListModel.addElement("keywords");
      fieldListModel.addElement("publisher");
    } else {
      for (String s : contents) {
        fieldListModel.addElement(s);
      }
    }

    if (currentField == null) {
      // if dialog is created for the whole database,
      // select the first field to avoid confusions in GUI usage
      fieldList.setSelectedIndex(0);
    } else {
      // a specific field has been chosen at the constructur
      // select this field
      int i = fieldListModel.indexOf(currentField);
      if (i != -1) {
        // field has been found in list, select it
        fieldList.setSelectedIndex(i);
      }
    }
  }
  public SplitPaneDemo() {

    // Create the list of images and put it in a scroll pane.

    list = new JList(imageNames);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(this);

    JScrollPane listScrollPane = new JScrollPane(list);
    picture = new JLabel();
    picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
    picture.setHorizontalAlignment(JLabel.CENTER);

    JScrollPane pictureScrollPane = new JScrollPane(picture);

    // Create a split pane with the two scroll panes in it.
    splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScrollPane, pictureScrollPane);
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(150);

    // Provide minimum sizes for the two components in the split pane.
    Dimension minimumSize = new Dimension(100, 50);
    listScrollPane.setMinimumSize(minimumSize);
    pictureScrollPane.setMinimumSize(minimumSize);

    // Provide a preferred size for the split pane.
    splitPane.setPreferredSize(new Dimension(400, 200));
    updateLabel(imageNames[list.getSelectedIndex()]);
  }
Exemple #3
0
 public NodeSelectionDialog(Frame owner, NodeLibrary library, NodeLibraryManager manager) {
   super(owner, "New Node", true);
   getRootPane().putClientProperty("Window.style", "small");
   JPanel panel = new JPanel(new BorderLayout());
   this.library = library;
   this.manager = manager;
   filteredNodeListModel = new FilteredNodeListModel(library, manager);
   searchField = new JTextField();
   searchField.putClientProperty("JTextField.variant", "search");
   EscapeListener escapeListener = new EscapeListener();
   searchField.addKeyListener(escapeListener);
   ArrowKeysListener arrowKeysListener = new ArrowKeysListener();
   searchField.addKeyListener(arrowKeysListener);
   SearchFieldChangeListener searchFieldChangeListener = new SearchFieldChangeListener();
   searchField.getDocument().addDocumentListener(searchFieldChangeListener);
   nodeList = new JList(filteredNodeListModel);
   DoubleClickListener doubleClickListener = new DoubleClickListener();
   nodeList.addMouseListener(doubleClickListener);
   nodeList.addKeyListener(escapeListener);
   nodeList.addKeyListener(arrowKeysListener);
   nodeList.setSelectedIndex(0);
   nodeList.setCellRenderer(new NodeRenderer());
   JScrollPane nodeScroll =
       new JScrollPane(
           nodeList,
           JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
           JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
   nodeScroll.setBorder(null);
   panel.add(searchField, BorderLayout.NORTH);
   panel.add(nodeScroll, BorderLayout.CENTER);
   setContentPane(panel);
   setSize(500, 400);
   SwingUtils.centerOnScreen(this);
 }
Exemple #4
0
  protected void init() {
    super.init();

    java.util.List<Macro> macros = new ArrayList<Macro>(MacroManager.getInstance().getMacros());
    Collections.sort(
        macros,
        new Comparator<Macro>() {
          public int compare(Macro macro1, Macro macro2) {
            String name1 = macro1.getName();
            String name2 = macro2.getName();
            if (!StringUtil.startsWithChar(name1, '/')) {
              name1 = ZERO + name1;
            }
            if (!StringUtil.startsWithChar(name2, '/')) {
              name2 = ZERO + name2;
            }
            return name1.compareToIgnoreCase(name2);
          }

          private final String ZERO = new String(new char[] {0});
        });
    for (Macro macro : macros) {
      myMacrosModel.addElement(new MacroWrapper(macro));
    }

    addListeners();
    if (myMacrosModel.size() > 0) {
      myMacrosList.setSelectedIndex(0);
    } else {
      setOKActionEnabled(false);
    }
  }
Exemple #5
0
 private void showStack(ThreadInfo tinfo, int selectFrame) {
   StackTraceListModel model = new StackTraceListModel(tinfo);
   stackModel = model;
   list.setModel(stackModel);
   list.setSelectedIndex(selectFrame);
   list.ensureIndexIsVisible(selectFrame);
 }
  /**
   * @param owner the parent Window (Dialog or Frame)
   * @param frame the JabRef Frame
   * @param panel the currently selected BasePanel
   * @param modal should this dialog be modal?
   * @param metaData The metadata of the current database
   * @param fieldName the field this selector is initialized for. May be null.
   */
  public ContentSelectorDialog2(
      Window owner,
      JabRefFrame frame,
      BasePanel panel,
      boolean modal,
      MetaData metaData,
      String fieldName) {
    super(owner, Globals.lang("Setup selectors"));
    this.setModal(modal);
    this.metaData = metaData;
    this.frame = frame;
    this.panel = panel;
    this.currentField = fieldName;

    // help = new JButton(Globals.lang("Help"));
    // help.addActionListener(new HelpAction(frame.helpDiag, GUIGlobals.contentSelectorHelp,
    // "Help"));
    // help = new HelpAction(frame.helpDiag, GUIGlobals.contentSelectorHelp, "Help");
    initLayout();
    //  wordSelector.addItem(WORD_EMPTY_TEXT);

    setupFieldSelector();
    setupWordSelector();
    setupActions();
    Util.bindCloseDialogKeyToCancelAction(this.rootPane, cancel.getAction());
    int fieldInd = fieldListModel.indexOf(currentField);
    if (fieldInd >= 0) fieldList.setSelectedIndex(fieldInd);

    pack();
  }
  private void removeSdk() {
    final Sdk currentSdk = getSelectedSdk();
    if (currentSdk != null) {
      final Sdk sdk = myProjectSdksModel.findSdk(currentSdk);
      final PySdkService sdkService = PySdkService.getInstance();
      sdkService.removeSdk(currentSdk);
      DumbService.allowStartingDumbModeInside(
          DumbModePermission.MAY_START_MODAL, () -> SdkConfigurationUtil.removeSdk(sdk));

      myProjectSdksModel.removeSdk(sdk);
      myProjectSdksModel.removeSdk(currentSdk);

      if (myModificators.containsKey(currentSdk)) {
        SdkModificator modificator = myModificators.get(currentSdk);
        myModifiedModificators.remove(modificator);
        myModificators.remove(currentSdk);
      }
      refreshSdkList();
      mySdkListChanged = true;
      // TODO select initially selected SDK
      if (mySdkList.getSelectedIndex() < 0) {
        mySdkList.setSelectedIndex(0);
      }
    }
  }
Exemple #8
0
 /** Called to populate the List of users */
 private void populateUsers() {
   listModel.clear();
   users = control.list_users();
   for (int i = 0; i < users.length; i++) {
     listModel.addElement(users[i]);
   }
   userList.setSelectedIndex(0);
 }
Exemple #9
0
 private void moveUp() {
   int index = nodeList.getSelectedIndex();
   index--;
   if (index < 0) {
     index = nodeList.getModel().getSize() - 1;
   }
   nodeList.setSelectedIndex(index);
 }
Exemple #10
0
  private void initFrame() {
    this.setLocationRelativeTo(null);

    try {
      if (!Files.exists(saveName)) Files.createFile(saveName);

      laden(saveName);
    } catch (IOException e) {
      e.printStackTrace();
    }

    nUebSchr.setSelected(true);
    if (!quellListModel.isEmpty()) quellJList.setSelectedIndex(0);
    if (!zielListModel.isEmpty()) zielJList.setSelectedIndex(0);

    starteLaufwerkspruefung();
  }
Exemple #11
0
 private void moveDown() {
   int index = nodeList.getSelectedIndex();
   index++;
   if (index >= nodeList.getModel().getSize()) {
     index = 0;
   }
   nodeList.setSelectedIndex(index);
 }
 public static void fresh_taskname() {
   task_name = new String[Runner.count_task];
   for (int i = 0; i < Runner.count_task; i++) {
     task_name[i] = Runner.task[i].get_taskname();
   }
   jl_taskname.setListData(task_name);
   jl_taskname.setSelectedIndex(0);
   jta_taskdescription.setText(MainFrame.str_description[0]);
 }
Exemple #13
0
  private void setSelectedIndex(int index) {
    if (index == -1) {
      list.getSelectionModel().clearSelection();
    } else if (list.getModel().getSize() != 0) {
      list.setSelectedIndex(index);

      list.ensureIndexIsVisible(index);
    }
  }
 private void removeSelectedConfiguration() {
   int oldSelection = myList.getSelectedIndex();
   myModel.removeElement(mySelection);
   int size = myList.getModel().getSize();
   int newSelection = oldSelection < size ? oldSelection : size - 1;
   if (newSelection >= 0 && newSelection < size) {
     myList.setSelectedIndex(newSelection);
   }
 }
  private boolean ensureSelectionExists() {
    if (myList.getSelectedIndex() < 0 || myList.getSelectedIndex() >= myList.getModel().getSize()) {
      if (myList.getModel().getSize() >= 0) {
        myList.setSelectedIndex(0);
        return false;
      }
    }

    return true;
  }
Exemple #16
0
  private void showContextMenu(JList characterList, MouseEvent mouseEvent) {
    // TODO: handle right-click outside of selected range correctly (should treat as single
    // selection, but not deselect)
    boolean multipleSelected = herolabsCharacterList.getSelectedValues().length > 1;
    if (mouseEvent.isPopupTrigger() && mouseEvent.getClickCount() == 1) {
      if (!multipleSelected) {
        herolabsCharacterList.setSelectedIndex(
            herolabsCharacterList.locationToIndex(mouseEvent.getPoint()));
      }

      if (contextMenuEnabled) {
        JPopupMenu menu = new JPopupMenu();
        JMenuItem menuItem;

        menuItem = new JMenuItem("Configure character" + (multipleSelected ? "s" : "") + "...");
        menuItem.addActionListener(
            new ActionListener() {
              public void actionPerformed(ActionEvent actionEvent) {
                configureSelectedCharacters();
              }
            });
        menu.add(menuItem);

        menuItem = new JMenuItem("Configure using portfolio defaults");
        menuItem.addActionListener(
            new ActionListener() {
              public void actionPerformed(ActionEvent actionEvent) {
                resetToDefaultsForSelectedCharacters();
              }
            });
        menu.add(menuItem);

        menuItem = new JMenuItem("Export character" + (multipleSelected ? "s" : ""));
        menuItem.addActionListener(
            new ActionListener() {
              public void actionPerformed(ActionEvent actionEvent) {
                exportSelectedCharacters();
              }
            });
        menu.add(menuItem);

        menuItem = new JMenuItem("Clear configuration" + (multipleSelected ? "s" : ""));
        menuItem.addActionListener(
            new ActionListener() {
              public void actionPerformed(ActionEvent actionEvent) {
                clearConfigForSelectedCharacters();
              }
            });
        menu.add(menuItem);

        menu.show(characterList, mouseEvent.getX(), mouseEvent.getY());
      }
    }
  }
Exemple #17
0
  public void setLoaders(final List<PluginLoader> loaders) {
    this.loaders = loaders;
    plugins.setModel(
        new AbstractListModel() {
          @Override
          public int getSize() {
            return loaders.size();
          }

          @Override
          public Object getElementAt(int i) {
            return loaders.get(i).getName();
          }
        });
    plugins.setSelectedIndex(0);
    plugins.revalidate();
  }
  public ListDemo() {
    super(new BorderLayout());

    listModel = new DefaultListModel();

    // Create the list and put it in a scroll pane.
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(this);
    list.setVisibleRowCount(5);
    JScrollPane listScrollPane = new JScrollPane(list);

    JButton hireButton = new JButton(hireString);
    HireListener hireListener = new HireListener(hireButton);
    hireButton.setActionCommand(hireString);
    hireButton.addActionListener(hireListener);
    hireButton.setEnabled(false);

    loadButton = new JButton(loadString);
    loadButton.setActionCommand(loadString);
    loadButton.addActionListener(new loadListener());

    employeeName = new JTextField(10);
    employeeName.addActionListener(hireListener);
    employeeName.getDocument().addDocumentListener(hireListener);
    String name;
    if (listModel.size() > 0) {
      name = listModel.getElementAt(list.getSelectedIndex()).toString();
    }
    // Create a panel that uses BoxLayout.
    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
    buttonPane.add(loadButton);
    buttonPane.add(Box.createHorizontalStrut(5));
    buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
    buttonPane.add(Box.createHorizontalStrut(5));
    buttonPane.add(employeeName);
    buttonPane.add(hireButton);
    buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    add(listScrollPane, BorderLayout.CENTER);
    add(buttonPane, BorderLayout.PAGE_END);
  }
Exemple #19
0
  public JListDemo() {
    super("List Source Demo");
    contentpane = getContentPane();
    contentpane.setLayout(new FlowLayout());
    list = new JList(listColorNames);
    list.setSelectedIndex(0);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    contentpane.add(new JScrollPane(list));
    list.addListSelectionListener(
        new ListSelectionListener() {

          public void valueChanged(ListSelectionEvent e) {

            contentpane.setBackground(listColorValues[list.getSelectedIndex()]);
          }
        });
    setSize(200, 200);
    setVisible(true);
  }
Exemple #20
0
  @Override
  public void init() {

    JPanel pane = new JPanel();
    PointOnCircle point = new PointOnCircle();

    JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 15);
    Hashtable labelTable = new Hashtable();
    labelTable.put(new Integer(0), new JLabel("Stop"));
    labelTable.put(new Integer(15), new JLabel("Slow"));
    labelTable.put(new Integer(50), new JLabel("Fast"));
    slider.setLabelTable(labelTable);
    slider.setPaintLabels(true);
    slider.addChangeListener(
        e -> {
          int speed;
          JSlider source = (JSlider) e.getSource();
          speed = source.getValue();
          point.setSpeed(speed);
        });

    DefaultListModel<String> model = new DefaultListModel<>();
    model.addElement("Right");
    model.addElement("Left");
    JList list = new JList(model);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(
        e -> {
          if (list.getSelectedIndex() == 0) {
            point.setRight(true);
          } else {
            point.setRight(false);
          }
        });

    pane.add(slider);
    pane.add(list);

    add(point, BorderLayout.CENTER);
    add(pane, BorderLayout.NORTH);
  }
Exemple #21
0
  /** Create the UI */
  private void init() {
    mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    lst = new JList();
    DefaultListModel model = new DefaultListModel();
    for (int i = 0; i < names.length; i++) {
      model.addElement(names[i]);
    }
    lst.setModel(model);
    lst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    lst.addListSelectionListener(
        new ListSelectionListener() {
          @Override
          public void valueChanged(ListSelectionEvent lse) {
            onThumbnailChange(lse);
          }
        });

    lst.setSelectedIndex(0);
    mainPanel.add(new JScrollPane(lst), BorderLayout.WEST);
    mainPanel.add(imageLabel, BorderLayout.EAST);
  }
 /** Builds the UI. */
 private void initUI() {
   // Initialize the JList
   DefaultListModel model = new DefaultListModel();
   for (int i = 0; i < names.length; i++) {
     model.addElement(names[i]);
   }
   lst = new JList(model);
   // Add a selection listener
   lst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
   lst.addListSelectionListener(
       new ListSelectionListener() {
         @Override
         public void valueChanged(ListSelectionEvent lse) {
           onThumbnailChange(lse);
         }
       });
   lst.setSelectedIndex(0); // calls onThumbnailChange(lse)
   // Add components.
   mainPanel = new JPanel(new BorderLayout());
   mainPanel.add(new JScrollPane(lst), BorderLayout.WEST);
   mainPanel.add(imageLabel, BorderLayout.CENTER);
 }
  public CvsConfigurationsListEditor(List<CvsRootConfiguration> configs, Project project) {
    super(true);
    myCvs2SettingsEditPanel = new Cvs2SettingsEditPanel(project);
    setTitle(CvsBundle.message("operation.name.edit.configurations"));
    myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    selectNone();
    fillModel(configs);

    myCvs2SettingsEditPanel.addCvsRootChangeListener(
        new CvsRootChangeListener() {
          public void onCvsRootChanged() {
            if (mySelection == null) return;
            myCvs2SettingsEditPanel.saveTo(mySelection, false);
            myList.repaint();
          }
        });

    setTitle(CvsBundle.message("dialog.title.cvs.roots"));

    if (!configs.isEmpty()) {
      myList.setSelectedIndex(0);
    }
    init();
  }
Exemple #24
0
  public ModuleTypeStep(boolean createNewProject) {
    myPanel = new JPanel(new GridBagLayout());
    myPanel.setBorder(BorderFactory.createEtchedBorder());

    myModuleDescriptionPane = new JEditorPane();
    myModuleDescriptionPane.setContentType(UIUtil.HTML_MIME);
    myModuleDescriptionPane.addHyperlinkListener(
        new HyperlinkListener() {
          public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
              try {
                BrowserUtil.launchBrowser(e.getURL().toString());
              } catch (IllegalThreadStateException ex) {
                // it's nnot a problem
              }
            }
          }
        });
    myModuleDescriptionPane.setEditable(false);

    final ModuleType[] allModuleTypes = ModuleTypeManager.getInstance().getRegisteredTypes();

    myTypesList = new JList(allModuleTypes);
    myTypesList.setSelectionModel(new PermanentSingleSelectionModel());
    myTypesList.setCellRenderer(new ModuleTypesListCellRenderer());
    myTypesList.addListSelectionListener(
        new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
              return;
            }
            final ModuleType typeSelected = (ModuleType) myTypesList.getSelectedValue();
            myModuleType = typeSelected;
            //noinspection HardCodedStringLiteral
            myModuleDescriptionPane.setText(
                "<html><body><font face=\"verdana\" size=\"-1\">"
                    + typeSelected.getDescription()
                    + "</font></body></html>");
            myEventDispatcher.getMulticaster().moduleTypeSelected(typeSelected);
          }
        });
    myTypesList.setSelectedIndex(0);
    myTypesList.addMouseListener(
        new MouseAdapter() {
          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
              if (myDoubleClickAction != null) {
                if (myTypesList.getSelectedValue() != null) {
                  myDoubleClickAction.run();
                }
              }
            }
          }
        });

    myRbCreateNewModule = new JRadioButton(IdeBundle.message("radio.create.new.module"), true);
    myRbImportModule = new JRadioButton(IdeBundle.message("radio.import.existing.module"));
    myButtonGroup = new ButtonGroup();
    myButtonGroup.add(myRbCreateNewModule);
    myButtonGroup.add(myRbImportModule);
    ModulesRbListener listener = new ModulesRbListener();
    myRbCreateNewModule.addItemListener(listener);
    myRbImportModule.addItemListener(listener);

    JTextField tfModuleFilePath = new JTextField();
    final String productName = ApplicationNamesInfo.getInstance().getProductName();
    myModulePathFieldPanel =
        createFieldPanel(
            tfModuleFilePath,
            IdeBundle.message("label.path.to.module.file", productName),
            new BrowseFilesListener(
                tfModuleFilePath,
                IdeBundle.message("prompt.select.module.file.to.import", productName),
                null,
                new ModuleFileChooserDescriptor()));
    myModulePathFieldPanel.setEnabled(false);

    if (createNewProject) {
      final JLabel moduleTypeLabel = new JLabel(IdeBundle.message("label.select.module.type"));
      moduleTypeLabel.setFont(UIUtil.getLabelFont().deriveFont(Font.BOLD));
      myPanel.add(moduleTypeLabel, LABEL_CONSTRAINT);
    } else {
      myPanel.add(
          myRbCreateNewModule,
          new GridBagConstraints(
              0,
              GridBagConstraints.RELATIVE,
              1,
              1,
              0.0,
              0.0,
              GridBagConstraints.NORTHWEST,
              GridBagConstraints.NONE,
              new Insets(8, 10, 8, 10),
              0,
              0));
    }
    final JLabel descriptionLabel = new JLabel(IdeBundle.message("label.description"));
    descriptionLabel.setFont(UIUtil.getLabelFont().deriveFont(Font.BOLD));
    myPanel.add(
        descriptionLabel,
        new GridBagConstraints(
            1,
            GridBagConstraints.RELATIVE,
            1,
            1,
            0.0,
            0.0,
            GridBagConstraints.SOUTHWEST,
            GridBagConstraints.NONE,
            new Insets(0, 0, 0, 0),
            0,
            0));

    final JScrollPane typesListScrollPane = ScrollPaneFactory.createScrollPane(myTypesList);
    final Dimension preferredSize = calcTypeListPreferredSize(allModuleTypes);
    typesListScrollPane.setPreferredSize(preferredSize);
    typesListScrollPane.setMinimumSize(preferredSize);
    myPanel.add(
        typesListScrollPane,
        new GridBagConstraints(
            0,
            GridBagConstraints.RELATIVE,
            1,
            1,
            0.2,
            (createNewProject ? 1.0 : 0.0),
            GridBagConstraints.NORTHWEST,
            GridBagConstraints.BOTH,
            new Insets(0, createNewProject ? 10 : 30, 0, 10),
            0,
            0));

    final JScrollPane descriptionScrollPane =
        ScrollPaneFactory.createScrollPane(myModuleDescriptionPane);
    descriptionScrollPane.setPreferredSize(
        new Dimension(preferredSize.width * 3, preferredSize.height));
    myPanel.add(
        descriptionScrollPane,
        new GridBagConstraints(
            1,
            GridBagConstraints.RELATIVE,
            1,
            1,
            0.8,
            (createNewProject ? 1.0 : 0.0),
            GridBagConstraints.CENTER,
            GridBagConstraints.BOTH,
            new Insets(0, 0, 0, 10),
            0,
            0));

    if (!createNewProject) {
      myPanel.add(
          myRbImportModule,
          new GridBagConstraints(
              0,
              GridBagConstraints.RELATIVE,
              2,
              1,
              1.0,
              0.0,
              GridBagConstraints.NORTHWEST,
              GridBagConstraints.NONE,
              new Insets(16, 10, 0, 10),
              0,
              0));
      myPanel.add(
          myModulePathFieldPanel,
          new GridBagConstraints(
              0,
              GridBagConstraints.RELATIVE,
              2,
              1,
              1.0,
              1.0,
              GridBagConstraints.NORTHWEST,
              GridBagConstraints.HORIZONTAL,
              new Insets(8, 30, 0, 10),
              0,
              0));
    }
  }
  private void init(Font font) {
    JPanel content = new JPanel(new BorderLayout());
    content.setBorder(new EmptyBorder(12, 12, 12, 12));
    setContentPane(content);

    JPanel listPanel = new JPanel(new GridLayout(1, 3, 6, 6));

    String[] fonts;
    try {
      fonts = getFontList();
    } catch (Exception e) {
      Log.log(Log.ERROR, this, "Broken Java implementation!");

      Log.log(Log.ERROR, this, e);

      fonts = new String[] {"Broken Java implementation!"};
    }

    JPanel familyPanel =
        createTextFieldAndListPanel(
            "font-selector.family", familyField = new JTextField(), familyList = new JList(fonts));
    listPanel.add(familyPanel);

    String[] sizes = {"9", "10", "12", "14", "16", "18", "24"};
    JPanel sizePanel =
        createTextFieldAndListPanel(
            "font-selector.size", sizeField = new JTextField(), sizeList = new JList(sizes));
    listPanel.add(sizePanel);

    String[] styles = {
      jEdit.getProperty("font-selector.plain"),
      jEdit.getProperty("font-selector.bold"),
      jEdit.getProperty("font-selector.italic"),
      jEdit.getProperty("font-selector.bolditalic")
    };

    JPanel stylePanel =
        createTextFieldAndListPanel(
            "font-selector.style", styleField = new JTextField(), styleList = new JList(styles));
    styleField.setEditable(false);
    listPanel.add(stylePanel);

    familyList.setSelectedValue(font.getFamily(), true);
    familyField.setText(font.getFamily());
    sizeList.setSelectedValue(String.valueOf(font.getSize()), true);
    sizeField.setText(String.valueOf(font.getSize()));
    styleList.setSelectedIndex(font.getStyle());
    styleField.setText((String) styleList.getSelectedValue());

    ListHandler listHandler = new ListHandler();
    familyList.addListSelectionListener(listHandler);
    sizeList.addListSelectionListener(listHandler);
    styleList.addListSelectionListener(listHandler);

    content.add(BorderLayout.NORTH, listPanel);

    preview =
        new JLabel(jEdit.getProperty("font-selector.long-text")) {
          public void paintComponent(Graphics g) {
            if (fontSelector != null) fontSelector.setAntiAliasEnabled(g);
            super.paintComponent(g);
          }
        };
    preview.setBorder(new TitledBorder(jEdit.getProperty("font-selector.preview")));

    updatePreview();

    Dimension prefSize = preview.getPreferredSize();
    prefSize.height = 50;
    preview.setPreferredSize(prefSize);

    content.add(BorderLayout.CENTER, preview);

    JPanel buttons = new JPanel();
    buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
    buttons.setBorder(new EmptyBorder(12, 0, 0, 0));
    buttons.add(Box.createGlue());

    ok = new JButton(jEdit.getProperty("common.ok"));
    ok.addActionListener(new ActionHandler());
    getRootPane().setDefaultButton(ok);
    buttons.add(ok);

    buttons.add(Box.createHorizontalStrut(6));

    cancel = new JButton(jEdit.getProperty("common.cancel"));
    cancel.addActionListener(new ActionHandler());
    buttons.add(cancel);

    buttons.add(Box.createGlue());

    content.add(BorderLayout.SOUTH, buttons);

    pack();
    setLocationRelativeTo(getParent());
    setVisible(true);
  }
  public ListDataEventDemo() {
    super(new BorderLayout());

    // Create and populate the list model.
    listModel = new DefaultListModel();
    listModel.addElement("Whistler, Canada");
    listModel.addElement("Jackson Hole, Wyoming");
    listModel.addElement("Squaw Valley, California");
    listModel.addElement("Telluride, Colorado");
    listModel.addElement("Taos, New Mexico");
    listModel.addElement("Snowbird, Utah");
    listModel.addElement("Chamonix, France");
    listModel.addElement("Banff, Canada");
    listModel.addElement("Arapahoe Basin, Colorado");
    listModel.addElement("Kirkwood, California");
    listModel.addElement("Sun Valley, Idaho");
    listModel.addListDataListener(new MyListDataListener());

    // Create the list and put it in a scroll pane.
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(this);
    JScrollPane listScrollPane = new JScrollPane(list);

    // Create the list-modifying buttons.
    addButton = new JButton(addString);
    addButton.setActionCommand(addString);
    addButton.addActionListener(new AddButtonListener());

    deleteButton = new JButton(deleteString);
    deleteButton.setActionCommand(deleteString);
    deleteButton.addActionListener(new DeleteButtonListener());

    ImageIcon icon = createImageIcon("Up16");
    if (icon != null) {
      upButton = new JButton(icon);
      upButton.setMargin(new Insets(0, 0, 0, 0));
    } else {
      upButton = new JButton("Move up");
    }
    upButton.setToolTipText("Move the currently selected list item higher.");
    upButton.setActionCommand(upString);
    upButton.addActionListener(new UpDownListener());

    icon = createImageIcon("Down16");
    if (icon != null) {
      downButton = new JButton(icon);
      downButton.setMargin(new Insets(0, 0, 0, 0));
    } else {
      downButton = new JButton("Move down");
    }
    downButton.setToolTipText("Move the currently selected list item lower.");
    downButton.setActionCommand(downString);
    downButton.addActionListener(new UpDownListener());

    JPanel upDownPanel = new JPanel(new GridLayout(2, 1));
    upDownPanel.add(upButton);
    upDownPanel.add(downButton);

    // Create the text field for entering new names.
    nameField = new JTextField(15);
    nameField.addActionListener(new AddButtonListener());
    String name = listModel.getElementAt(list.getSelectedIndex()).toString();
    nameField.setText(name);

    // Create a control panel, using the default FlowLayout.
    JPanel buttonPane = new JPanel();
    buttonPane.add(nameField);
    buttonPane.add(addButton);
    buttonPane.add(deleteButton);
    buttonPane.add(upDownPanel);

    // Create the log for reporting list data events.
    log = new JTextArea(10, 20);
    JScrollPane logScrollPane = new JScrollPane(log);

    // Create a split pane for the log and the list.
    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, listScrollPane, logScrollPane);
    splitPane.setResizeWeight(0.5);

    // Put everything together.
    add(buttonPane, BorderLayout.PAGE_START);
    add(splitPane, BorderLayout.CENTER);
  }
  // FUNCTION TO SIMULATE A STEP IN THE SIMULATION ON THE FRAME
  public void step() {

    /**
     * EACH TIME THE NEXT BUTTON IS PRESSED, ALL THE STATES THAT OCURRED UPTO THE CURRENT STATE ARE
     * EVALUATED. THERE IS A while STATEMENT THAT PERFORMS THIS FUNCTION AND CONTAINS A switch
     * STATEMENT WITHIN IT TO EVALUATE EACH STEP AS IT OCCURS.
     */

    ////////////////////// INITIALIZATION ///////////////////////////////////////

    // UPDATE THE STATE OF THE CACHE AND MEMORY
    for (int i = 0; i < 16; i++) {
      cachePanel.stringBlocks[i] = "";
      cachePanel.boolBlocks[i] = false;
      cachePanel.tag[i] = "";
      cachePanel.boolTags[i] = false;

      statusCacheEmpty[i] = true;
      statusCacheLRU[i] = 0;
    }
    for (int i = 0; i < 8; i++) {
      cachePanel.boolWords[i] = false;
      memoryPanel.boolWords[i] = false;
    }
    for (int i = 0; i < 32; i++) memoryPanel.boolBlocks[i] = false;

    // UPDATE THE BITS IN MAIN MEMORY ADDRESS
    tTag.setText("");
    tWord.setText("");
    tTag.setBackground(new Color(205, 205, 205));
    tWord.setBackground(new Color(205, 205, 205));

    // UPDATE THE CACHE HITS AND MISSES FIELDS
    cacheHits = 0;
    cacheMisses = 0;
    tCacheHits.setText("  0");
    tCacheMisses.setText("  0");

    // UPDATE THE VALUES USED FOR BRINGING MEMORY BLOCKS IN CACHE
    statusLRU = 0;
    memInCache = -1;
    lruCacheBlock = -1;

    // RESET THE VALUE OF addSel
    evaluateIndex = 0;

    // DISABLE ADDRESS GENERATION BUTTONS
    autoGen.setEnabled(false);
    selfGen.setEnabled(false);

    ////////////////////// END INITIALIZATION /////////////////////////////////////

    // IF Next WAS CLICKED, INCREMENT moveStatus
    if (nextClicked) moveStatus++;
    else {
      // DECREMENT moveStatus AND ENABLE NEXT SINCE IT MIGHT BE DISABLED
      moveStatus--;
      next.setEnabled(true);
    }

    // IF NO MORE back MOVES CAN BE MADE, DISABLE back BUTTON
    if (moveStatus == 0) {
      back.setEnabled(false);
      tProgress.setText(
          "You cannot go back any further."
              + "\nPlease click on \"Next\" or \"Restart\" to continue.");
      tProgress.setCaretPosition(0);

      // CLEAR THE SELECTED ADDRESS REFERENCE STRING
      addRefStrList.clearSelection();
    } else
      // ENABLE back BUTTON ONCE THE FIRST MOVE IS MADE
      back.setEnabled(true);

    // INITIALIZE THE VARIABLE THAT KEEPS TRACK OF THE STATE WE ARE CURRENTLY EVALUATING.
    int tempState = 1;

    // CONTINUE TO EVALUATE EACH STATE TILL WE REACH THE CURRENT STATE
    while (tempState <= moveStatus) {

      switch (tempState % 6) {
        case 1: // IF A NEW CYCLE IS BEGINNING, OBTAIN NEXT ADDRESS REFERENCE

          // OBTAIN THE ADDRESS REFERENCE STRING
          addRefStrList.setSelectedIndex(evaluateIndex);

          // ENSURE THAT THE LIST SCROLLS AND SELECTED INDEX IS VISIBLE
          // DUE TO REPAINTING CONSTRAINTS, ONLY DO THIS IN THE CURRENT STATE
          if (tempState == moveStatus) addRefStrList.ensureIndexIsVisible(evaluateIndex);

          // EVALUATE THE TAG, BLOCK AND WORD
          hexAddress = (String) addRefStrList.getSelectedValue();
          int intAddress = Integer.parseInt(hexAddress, 16);
          binAddress = Integer.toBinaryString(intAddress);

          // USING CLASS INTEGER'S parseInt FUNCTION RETURNS A BINARY STRING WITHOUT LEADING 0'S
          // ENSURE THAT binAddress is 8 bits
          if (binAddress.length() < 8) {
            int zeroes = 8 - binAddress.length();
            for (int i = 0; i < zeroes; i++) binAddress = '0' + binAddress;
          }

          tag = binAddress.substring(0, 5);
          word = binAddress.substring(5);

          // CALCULATE THE ACTUAL CACHE AND MEMORY BLOCKS AND WORDS IN QUESTION
          intWordDec = Integer.parseInt(word, 2);
          intBlockDecMem = Integer.parseInt(tag, 2);

          // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
          if (tempState == moveStatus) {
            tProgress.setText(
                "The memory address we want is obtained from the Address Reference String."
                    + "\nIt is (in hexadecimal): "
                    + hexAddress
                    + ".");
            tProgress.setCaretPosition(0);
          }

          break;

        case 2: // EVALUATE THE BITS IN MAIN MEMORY ADDRESS AND HIGHLIGHT THEM

          // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
          if (tempState == moveStatus) {
            tProgress.setText(
                "The hexadecimal address "
                    + hexAddress
                    + " evaluates to its binary equivalent "
                    + binAddress
                    + "."
                    + "\nHence the bits in the Main Memory Address are divided into the following fields\n"
                    + tag
                    + " --> Tag,  "
                    + word
                    + " --> Word."
                    + "\nThe tag bits identify the memory block, "
                    + "and the word bits identify the word within the block.");
            tProgress.setCaretPosition(0);

            // HIGHLIGHT THE BITS IN MAIN MEMORY ADDRESS IN GREEN
            tTag.setBackground(Color.green);
            tWord.setBackground(Color.green);
          }

          tTag.setText("      " + tag);
          tWord.setText("  " + word);

          break;

        case 3: // FIND THE CACHE BLOCK IN QUESTION AND HIGHLIGHT IT

          // UNDO HIGHLIGHTS OF PREVIOUS STEP
          tTag.setBackground(new Color(205, 205, 205));
          tWord.setBackground(new Color(205, 205, 205));

          // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
          if (tempState == moveStatus) {
            tProgress.setText(
                "Every time a memory block is placed in cache, its tag field is stored with it as well."
                    + "\nSo, to find the required memory block in cache, its tag, "
                    + tag
                    + " is compared to all the valid tag fields in cache.");
            tProgress.setCaretPosition(0);
          }

          // GET THE BLOCK IN CACHE WHERE MEMORY BLOCK EXISTS, IF AT ALL
          memInCache = getCacheBlock(tag);

          // IF MEMORY BLOCK IS NOT IN CACHE...
          if (memInCache == -1) {
            if (tempState == moveStatus) {
              tProgress.append(
                  "\n\nSince the memory block is not in cache, there is a cache miss."
                      + "\nSo the block needs to be brought in from memory.");
              tProgress.setCaretPosition(0);
            }

            // GET FIRST EMPTY CACHE BLOCK, IF AVAILABLE
            emptyCacheBlock = getFirstEmptyCacheBlock();

            // IF EMPTY CACHE BLOCK IS AVAILABLE, THIS IS WHERE THE MEMORY WILL BE BROUGHT SO
            // DISPLAY IT
            if (!(emptyCacheBlock == -1)) {

              // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
              if (tempState == moveStatus) {
                tProgress.append(
                    "\nSince the cache has empty space, the first available block will be filled."
                        + "\nSee the highlighted cache block.");
                tProgress.setCaretPosition(0);
              }

              // HIGHLIGHT THE CACHE BLOCK IN YELLOW
              cachePanel.boolBlocks[emptyCacheBlock] = true;
              cachePanel.boolTags[emptyCacheBlock] = true;

              // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
              intBlockDec = emptyCacheBlock;
            }

            // ELSE DISPLAY THE LRU CACHE BLOCK WHICH WILL BE REPLACED
            else {

              // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
              if (tempState == moveStatus) {
                tProgress.append(
                    "\nSince the cache is full, the least recently used cache block will be replaced."
                        + "\nSee the highlighted cache block.");
                tProgress.setCaretPosition(0);
              }

              lruCacheBlock = getLRUCacheBlock();

              // HIGHLIGHT THE CACHE BLOCK IN YELLOW
              cachePanel.boolBlocks[lruCacheBlock] = true;
              cachePanel.boolTags[lruCacheBlock] = true;

              // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
              intBlockDec = lruCacheBlock;
            }

            // UPDATE COUNT OF CACHE MISSES
            cacheMisses++;
            tCacheMisses.setText("  " + cacheMisses);
          } else {

            if (tempState == moveStatus) {
              tProgress.append(
                  "\n\nSince the required memory block is in cache block "
                      + memInCache
                      + " there is a cache hit.");
              tProgress.setCaretPosition(0);
            }

            // HIGHLIGHT THE CACHE BLOCK IN YELLOW
            // TO CAUSE HIGHLIGHTING ON THE CACHE, WE NEED TO MODIFY IT'S STATE, i.e. IT'S DATA
            // MEMBERS
            cachePanel.boolBlocks[memInCache] = true;
            cachePanel.boolWords[intWordDec] = true;
            cachePanel.boolTags[memInCache] = true;

            // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
            intBlockDec = memInCache;

            // UPDATE COUNT OF CACHE HITS
            cacheHits++;
            tCacheHits.setText("  " + cacheHits);
          }

          break;

        case 4: // EVALUATE THE MEMORY BLOCK IN QUESTION AND HIGHLIGHT IT

          // UNDO THE HIGHLIGHTS OF THE PREVIOUS STEP
          cachePanel.boolBlocks[intBlockDec] = false;
          cachePanel.boolWords[intWordDec] = false;
          cachePanel.boolTags[intBlockDec] = false;

          // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
          if (tempState == moveStatus) {
            tProgress.setText(
                "Highlighted is the memory block in question. Since the tag bits are "
                    + tag
                    + ", the memory block, in decimal, is "
                    + intBlockDecMem
                    + ".");
            tProgress.setCaretPosition(0);
          }

          // SET THE MEMORY STATE SO AS TO HIGHLIGHT THE REQUIRED MEMORY BLOCK
          memoryPanel.boolBlocks[intBlockDecMem] = true;

          // SET THE MEMORY STATE SO AS TO HIGHLIGHT THE REQUIRED WORD
          memoryPanel.boolWords[intWordDec] = true;

          break;

        case 5: // HIGHLIGHT THE CACHE BLOCK WITH THE MEMORY BLOCK NOW IN IT

          // UNDO HIGHLIGHTS OF PREVIOUS STEP
          memoryPanel.boolBlocks[intBlockDecMem] = false;
          memoryPanel.boolWords[intWordDec] = false;

          /*
           * NOW, THERE ARE 3 WAYS TO GO FROM HERE
           * 1. IF THERE IS AN EMPTY CACHE BLOCK, SIMPLY BRING THE MEMORY BLOCK INTO CACHE
           * 2. IF THE REQUIRED MEMORY BLOCK IS ALREADY IN CACHE, DO NOTHING
           * 3. IF THE CACHE IS FULL, FIND THE LRU BLOCK AND REPLACE IT WITH THE REQUIRED MEMORY BLOCK
           */

          // IF THE MEMORY BLOCK WAS NOT IN CACHE AND AN EMPTY CACHE BLOCK IS AVAILABLE
          // BRING THE MEMORY BLOCK AND TAG INTO CACHE AND HIGHLIGHT CACHE BLOCK
          if ((memInCache == -1) && !(emptyCacheBlock == -1)) {

            // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
            if (tempState == moveStatus) {
              tProgress.setText(
                  "As we saw earlier, the required memory block was not in cache."
                      + "\nSince there was empty space in cache, we brought the memory block into it."
                      + "\nWe also stored the tag, "
                      + tag
                      + ", of the memory block with the cache block."
                      + "\n\nRemember that the memory block could be brought into any empty cache block."
                      + "\nIn our example, we are using the first available empty block.");
              tProgress.setCaretPosition(0);
            }

            // UPDATE THE COUNTER FOR THE LRU CACHE BLOCK
            statusLRU++;
            statusCacheLRU[emptyCacheBlock] = statusLRU;
            statusCacheEmpty[emptyCacheBlock] = false;

            // UPDATE THE CACHE ARRAYS KEEPING TRACK OF MEMORY BLOCKS AND TAGS
            cachePanel.stringBlocks[emptyCacheBlock] = "" + intBlockDecMem;
            cachePanel.tag[emptyCacheBlock] = tag;

            // HIGHLIGHT THE CACHE BLOCK IN YELLOW
            cachePanel.boolBlocks[emptyCacheBlock] = true;
            cachePanel.boolWords[intWordDec] = true;
            cachePanel.boolTags[emptyCacheBlock] = true;

            // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
            intBlockDec = emptyCacheBlock;

          } // END IF

          // IF MEMORY BLOCK IS ALREADY IN CACHE THEN JUST HIGHLIGHT THE CACHE BLOCK
          else if ((memInCache >= 0) && (memInCache < 16)) {

            // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
            if (tempState == moveStatus) {
              tProgress.setText(
                  "As we saw earlier, the required memory block is already in cache.");
              tProgress.setCaretPosition(0);
            }

            // UPDATE THE COUNTER FOR THE LRU CACHE BLOCK
            statusLRU++;
            statusCacheLRU[memInCache] = statusLRU;

            // HIGHLIGHT THE CACHE BLOCK IN YELLOW
            cachePanel.boolBlocks[memInCache] = true;
            cachePanel.boolWords[intWordDec] = true;
            cachePanel.boolTags[memInCache] = true;

            // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
            intBlockDec = memInCache;

          } // END ELSE IF

          // IF THE MEMORY BLOCK IS NOT IN CACHE AND THE CACHE IS FULL
          // FIND THE LRU CACHE BLOCK AND REPLACE IT WITH THE MEMORY BLOCK, THEN HIGHLIGHT THE CACHE
          // BLOCK
          else {

            // FIND THE LRU CACHE BLOCK
            lruCacheBlock = getLRUCacheBlock();

            // IF THIS IS THE CURRENT STATE, UPDATE THE PROGRESS FIELD
            if (tempState == moveStatus) {
              tProgress.setText(
                  "As we saw earlier, the cache is full."
                      + "\nSo we picked the least recently used cache block, "
                      + lruCacheBlock
                      + ", and replaced it with the required memory block.");
              tProgress.setCaretPosition(0);
            }

            // UPDATE THE COUNTER FOR THE LRU CACHE BLOCK
            statusLRU++;
            statusCacheLRU[lruCacheBlock] = statusLRU;
            statusCacheEmpty[lruCacheBlock] = false; // redundant stmt

            // UPDATE THE CACHE ARRAYS KEEPING TRACK OF MEMORY BLOCKS AND TAGS
            cachePanel.stringBlocks[lruCacheBlock] = "" + intBlockDecMem;
            cachePanel.tag[lruCacheBlock] = tag;

            // HIGHLIGHT THE CACHE BLOCK IN YELLOW
            cachePanel.boolBlocks[lruCacheBlock] = true;
            cachePanel.boolWords[intWordDec] = true;
            cachePanel.boolTags[lruCacheBlock] = true;

            // STORE THE CHANGED CACHE BLOCK INDEX IN COMMON VARIABLE
            intBlockDec = lruCacheBlock;
          } // END ELSE

          break;

        case 0: // LAST STEP IN CYCLE - CLEANUP STEP!

          // UNDO HIGHLIGHTS OF PREVIOUS STEP
          cachePanel.boolBlocks[intBlockDec] = false;
          cachePanel.boolWords[intWordDec] = false;
          cachePanel.boolTags[intBlockDec] = false;

          tTag.setText("");
          tWord.setText("");

          tTag.setBackground(new Color(205, 205, 205));
          tWord.setBackground(new Color(205, 205, 205));

          // CLEAR THE SELECTED ADDRESS REFERENCE STRING
          addRefStrList.clearSelection();

          // INCREMENT THE INDEX SO AS TO POINT TO THE NEXT ADDRESS REFERENCE STRING
          evaluateIndex++;

          // IF THE LAST ADDRESS REFERENCE STRING HAS BEEN REACHED, DO THE APPROPRIATE
          if (evaluateIndex == listData.size()) {

            if (tempState == moveStatus) {
              tProgress.setText(
                  "This completes the runthrough."
                      + "\nPlease click on \"Restart\", generate the Address Reference String "
                      + "OR click \"Quit\" to finish.");
              tProgress.setCaretPosition(0);
            }
            next.setEnabled(false);

            // ENABLE ADDRESS GENERATION BUTTONS
            autoGen.setEnabled(true);
            selfGen.setEnabled(true);

            reStarted = false;
          }

          // ELSE AN ACCESS CYCLE HAS BEEN COMPLETED SO SHOW THE APPROPRIATE MESSAGE IN THE PROGRESS
          // FIELD
          else {
            if (tempState == moveStatus) {
              tProgress.setText("This completes an access cycle.");
              tProgress.setCaretPosition(0);
            }

            // CLEAR THE SELECTION IN THE ADDRESS REFERENCE STRING
            addRefStrList.clearSelection();
          }

          break;

        default:
          JOptionPane.showMessageDialog(null, "Uh Oh, there's a problem in switch-case!");
      } // END switch

      tempState++;
    } // END while

    // CALL THE REPAINT METHOD
    repaint();
  } // END FUNCTION step
Exemple #28
0
 private void subZListBoxEintrag() {
   if (zielJList.getSelectedIndex() < 0) return;
   else zielListModel.remove(zielJList.getSelectedIndex());
   if (zielListModel.getSize() > 0) zielJList.setSelectedIndex(zielListModel.getSize() - 1);
 }
  public SQLiteDataBrowser() {
    SQLiteDbManager dbManager = new SQLiteDbManager();

    setLayout(new BorderLayout());

    showTablesList = new JList();
    showTablesList.setLayoutOrientation(JList.VERTICAL_WRAP);
    showTablesList.setSelectedIndex(ListSelectionModel.SINGLE_SELECTION);
    showTablesList.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    showTablesList.setFont(new Font("Times New Roman", Font.PLAIN, 13));
    showTablesList.setDragEnabled(false);
    showTablesList.setFixedCellWidth(150);
    showTablesList.setVisibleRowCount(-1);
    showTablesList.setEnabled(false);

    showTablesListScroller = new JScrollPane(showTablesList);
    showTablesListScroller.setBorder(
        BorderFactory.createTitledBorder(new LineBorder(Color.BLACK), "List of Tables"));
    showTablesListScroller.setPreferredSize(new Dimension(160, this.getHeight()));

    add(showTablesListScroller, BorderLayout.EAST);

    loadDbPanel = new JPanel(new FlowLayout());
    loadDbPanel.setBackground(new Color(0xe8e8e8));
    loadDbPanel.setPreferredSize(new Dimension(getWidth(), 40));

    loadDbLabel = new JLabel("Load SQLite Database: ");
    loadDbLabel.setToolTipText("Possible extensions being .sqlite|.sqlite3|.db|.db3");

    loadedDbPath = new JTextField("Click browse to choose the database file.", 60);
    loadedDbPath.setForeground(Color.GRAY);
    loadedDbPath.setFont(new Font("Times New Roman", Font.ITALIC, 13));
    loadedDbPath.setEditable(false);

    lastFolderLocation = new File(Utils.getUserHome());
    fc = new JFileChooser(lastFolderLocation);

    browseDb = new JButton("Browse");
    browseDb.addActionListener(
        actionEvent -> {
          int retVal = fc.showOpenDialog(SQLiteDataBrowser.this);
          if (retVal == JFileChooser.APPROVE_OPTION) {
            File dbPath = fc.getSelectedFile();
            if (Utils.checkIfSQLiteDb(dbPath)) {
              loadedDbPath.setText(dbPath.toString());
              lastFolderLocation = fc.getCurrentDirectory();
              new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                  try {
                    dbManager.setDbPath(dbPath.toString());
                    dbManager.initialize();
                    showTablesList.setListData(dbManager.getTables().toArray());
                    showTablesList.setEnabled(true);
                  } catch (SQLException e) {
                    e.printStackTrace();
                  }
                  return null;
                }
              }.execute();
            } else {
              JOptionPane.showMessageDialog(
                  SQLiteDataBrowser.this,
                  "The Selected file is not in SQLite Format",
                  "File Format Error",
                  JOptionPane.ERROR_MESSAGE);
              loadedDbPath.setText("Click browse to choose the database file.");
            }
          }
        });

    loadDbPanel.add(loadDbLabel);
    loadDbPanel.add(loadedDbPath);
    loadDbPanel.add(browseDb);

    loadDbRecords = new JLabel("Records Fetched (Rows x Cols): ");
    loadDbRecords.setFont(new Font("Times New Roman", Font.ITALIC, 12));
    loadDbPanel.add(loadDbRecords);

    loadDbRecordsCount = new JLabel();
    loadDbRecordsCount.setFont(new Font("Times New Roman", Font.ITALIC, 12));
    loadDbPanel.add(loadDbRecordsCount);

    final class DataBrowserTableModal extends DefaultTableModel {

      public DataBrowserTableModal() {}

      public DataBrowserTableModal(Object[][] tableData, Object[] colNames) {
        super(tableData, colNames);
      }

      @Override
      public void setDataVector(Object[][] tableData, Object[] colNames) {
        super.setDataVector(tableData, colNames);
      }

      @Override
      public boolean isCellEditable(int row, int column) {
        return false;
      }
    }

    DataBrowserTableModal tableModal = new DataBrowserTableModal();
    defaultTableModel = tableModal;

    table = new JTable();
    table.setModel(defaultTableModel);

    showTablesList.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent evt) {
            JList list = (JList) evt.getSource();
            if (evt.getClickCount() == 2) {
              String tableName = list.getSelectedValue().toString();

              new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                  try {
                    ResultSet rs = dbManager.executeQuery("SELECT * from " + tableName);
                    Vector<String> columnNames = dbManager.getColumnNames(rs);
                    Vector<Vector<Object>> tableData = new Vector<>();
                    while (rs.next()) {
                      Vector<Object> vector = new Vector<>();

                      for (int i = 1; i <= columnNames.size(); i++) {
                        vector.add(rs.getObject(i));
                      }
                      tableData.add(vector);
                    }
                    defaultTableModel.setDataVector(tableData, columnNames);
                  } catch (SQLException e) {
                    e.printStackTrace();
                  }

                  loadDbRecordsCount.setText(
                      defaultTableModel.getRowCount() + " x " + defaultTableModel.getColumnCount());

                  if (defaultTableModel.getColumnCount() < 5) {
                    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                  } else {
                    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                  }

                  return null;
                }
              }.execute();
            }
          }
        });

    tableScrollPane = new JScrollPane(table);
    tableScrollPane.setHorizontalScrollBarPolicy(
        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    tableScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    tableScrollPane.setPreferredSize(new Dimension(getWidth(), getHeight()));
    add(tableScrollPane, BorderLayout.CENTER);

    add(loadDbPanel, BorderLayout.NORTH);
  }
  public BorrowerSearchPanel(BorrowerView borrowerView, Controller mySession) {
    super(new BorderLayout());
    parent = borrowerView;
    this.mySession = mySession;

    listModel = new DefaultListModel();

    // Create the list and put it in a scroll pane.
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(this);
    list.setVisibleRowCount(5);
    JScrollPane listScrollPane = new JScrollPane(list);
    /*
    employeeName = new JTextField(10);
    employeeName.addActionListener(hireListener);
    employeeName.getDocument().addDocumentListener(hireListener);
    String name = listModel.getElementAt(
                          list.getSelectedIndex()).toString();*/

    // Create a panel that uses BoxLayout.
    JPanel buttonPane = new JPanel();
    buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    add(listScrollPane, BorderLayout.CENTER);

    JPanel panel = new JPanel();
    listScrollPane.setColumnHeaderView(panel);

    JLabel lblSearchForBooks = new JLabel("Search For Books");
    panel.add(lblSearchForBooks);
    add(buttonPane, BorderLayout.PAGE_END);
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));

    JSplitPane splitPane = new JSplitPane();
    splitPane.setContinuousLayout(true);
    splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
    buttonPane.add(splitPane);

    JPanel panel_1 = new JPanel();
    splitPane.setLeftComponent(panel_1);

    cmboKeyWords = new JComboBox();
    cmboKeyWords.setModel(new DefaultComboBoxModel(new String[] {"Title", "Author", "Subject"}));
    cmboKeyWords.setSize(100, 75);
    panel_1.add(cmboKeyWords);

    searchArgument = new JTextField();
    panel_1.add(searchArgument);
    searchArgument.setColumns(10);

    JPanel panel_2 = new JPanel();
    splitPane.setRightComponent(panel_2);

    btnSearch = new JButton("Search");
    btnSearch.addActionListener(new SearchListener());
    panel_2.add(btnSearch);

    btbPlaceOnHold = new JButton("Place Hold Request");
    btbPlaceOnHold.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            System.out.println("yep");
            PlaceHoldRequestDialog test =
                new PlaceHoldRequestDialog(
                    getInstance(), getLoggedInUserBID(), getInstance().mySession);
            test.setVisible(true);
          }
        });
    panel_2.add(btbPlaceOnHold);
  }