List of usage examples for javax.swing JButton setToolTipText
@BeanProperty(bound = false, preferred = true, description = "The text to display in a tool tip.") public void setToolTipText(String text)
From source file:UndoExample5.java
public UndoExample5() { super("Undo/Redo Example 5"); pane = new JTextPane(); pane.setEditable(true); // Editable getContentPane().add(new JScrollPane(pane), BorderLayout.CENTER); // Add a menu bar menuBar = new JMenuBar(); setJMenuBar(menuBar);/*from www . j a v a2 s .c om*/ // Populate the menu bar createMenuBar(); // Create the undo manager and actions MonitorableUndoManager manager = new MonitorableUndoManager(); pane.getDocument().addUndoableEditListener(manager); Action undoAction = new UndoAction(manager); Action redoAction = new RedoAction(manager); // Add the actions to buttons JPanel panel = new JPanel(); final JButton undoButton = new JButton("Undo"); final JButton redoButton = new JButton("Redo"); undoButton.addActionListener(undoAction); redoButton.addActionListener(redoAction); undoButton.setEnabled(false); redoButton.setEnabled(false); panel.add(undoButton); panel.add(redoButton); getContentPane().add(panel, BorderLayout.SOUTH); // Assign the actions to keys pane.registerKeyboardAction(undoAction, KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK), JComponent.WHEN_FOCUSED); pane.registerKeyboardAction(redoAction, KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK), JComponent.WHEN_FOCUSED); // Handle events from the MonitorableUndoManager manager.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { MonitorableUndoManager m = (MonitorableUndoManager) evt.getSource(); boolean canUndo = m.canUndo(); boolean canRedo = m.canRedo(); undoButton.setEnabled(canUndo); redoButton.setEnabled(canRedo); undoButton.setToolTipText(canUndo ? m.getUndoPresentationName() : null); redoButton.setToolTipText(canRedo ? m.getRedoPresentationName() : null); } }); }
From source file:com.xilinx.kintex7.MainScreen.java
private JPanel pciInfo() { JPanel pciSystemPanel = new JPanel(); pciSystemPanel.setLayout(new BoxLayout(pciSystemPanel, BoxLayout.Y_AXIS)); JPanel topPanel = new JPanel(new GridLayout(1, 2)); topPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("PCIe Settings"), BorderFactory.createRaisedBevelBorder())); JPanel sPanel = new JPanel(new FlowLayout()); sPanel.add(new JLabel("Link Speed: ")); Object[] speeds = { "2.5 Gbps", "5.0 Gbps" }; final PartialDisableComboBox lspeed = new PartialDisableComboBox(); lspeed.addItems(speeds);//from w ww .ja v a 2 s .co m lspeed.setSelectedIndex(di.getPCIInfo().LinkSpeed - 1); lspeed.setItemEnabled(di.getPCIInfo().LinkSpeed - 1, false); sPanel.add(lspeed); JButton setSpeed = new JButton("Go"); setSpeed.setToolTipText("This enables directed PCIe link speed change"); setSpeed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (lspeed.isItemEnabled(lspeed.getSelectedIndex())) { int ret = di.setLinkSpeed(lspeed.getSelectedIndex() + 1); if (ret == 0) { //update pcie information di.get_PCIstate(); lspeed.setItemEnabled(0, true); lspeed.setItemEnabled(1, true); lspeed.setSelectedIndex(di.getPCIInfo().LinkSpeed - 1); lspeed.setItemEnabled(di.getPCIInfo().LinkSpeed - 1, false); ptable.setData(di.getPCIInfo().getPCIData(), pcieColumnNames); ptable.fireTableDataChanged(); } else { updateLog("Unable to set Link Speed " + lspeed.getSelectedItem(), keyWord); } } } }); sPanel.add(setSpeed); topPanel.add(sPanel); JPanel sPanel1 = new JPanel(new FlowLayout()); sPanel1.add(new JLabel("Link Width: ")); Object[] widths = { "x1", "x2", "x4", "x8" }; final PartialDisableComboBox lwidths = new PartialDisableComboBox(); lwidths.addItems(widths); lwidths.setSelectedItem("x" + di.getPCIInfo().LinkWidth); lwidths.setItemEnabled(lwidths.getSelectedIndex(), false); sPanel1.add(lwidths); JButton setWidth = new JButton("Go"); setWidth.setToolTipText("This enables directed PCIe link width change"); setWidth.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (lwidths.isItemEnabled(lwidths.getSelectedIndex())) { int ret = di.setLinkWidth(lwidths.getSelectedIndex() + 1); if (ret == 0) { //update pcie information // some times width change affect link speed so // enable the same in lspeedd also di.get_PCIstate(); lwidths.setItemEnabled(0, true); lwidths.setItemEnabled(1, true); lwidths.setItemEnabled(2, true); lwidths.setItemEnabled(3, true); lwidths.setSelectedItem("x" + di.getPCIInfo().LinkWidth); lwidths.setItemEnabled(lwidths.getSelectedIndex(), false); // some times width change affect link speed so // enable the same in lspeed also lspeed.setItemEnabled(0, true); lspeed.setItemEnabled(1, true); lspeed.setSelectedIndex(di.getPCIInfo().LinkSpeed - 1); lspeed.setItemEnabled(di.getPCIInfo().LinkSpeed - 1, false); ptable.setData(di.getPCIInfo().getPCIData(), pcieColumnNames); ptable.fireTableDataChanged(); } else { di.get_PCIstate(); int upCap = di.getPCIInfo().LinkUpCap; if (upCap == 0) updateLog("Unable to set Link Width " + lwidths.getSelectedItem() + ". PCIe link not upconfigurable", keyWord); else updateLog("Unable to set Link Width " + lwidths.getSelectedItem(), keyWord); } } } }); sPanel1.add(setWidth); topPanel.add(sPanel1); pciSystemPanel.add(topPanel); JPanel panel = new JPanel(new GridLayout(1, 2)); JPanel pciPanel = new JPanel(new BorderLayout()); pciPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("PCIe Endpoint Status"), BorderFactory.createRaisedBevelBorder())); ptable = new MyTableModel(di.getPCIInfo().getPCIData(), pcieColumnNames); pcieTable = new JTable(ptable); try { pcieTable.setDefaultRenderer(Object.class, new CustomTableCellRenderer()); } catch (Exception e) { } JTableHeader pcieHeader = pcieTable.getTableHeader(); pcieHeader.setForeground(new Color(92, 25, 25)); pciPanel.add(pcieHeader, BorderLayout.PAGE_START); pciPanel.add(pcieTable, BorderLayout.CENTER); panel.add(pciPanel); JPanel hostPanel = new JPanel(new BorderLayout()); hostPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Host System's Initial Credits"), BorderFactory.createRaisedBevelBorder())); htable = new MyTableModel(di.getPCIInfo().getHostedData(), pcieColumnNames); hostTable = new JTable(htable); try { hostTable.setDefaultRenderer(Object.class, new CustomTableCellRenderer()); } catch (Exception e) { } JTableHeader hostHeader = hostTable.getTableHeader(); hostHeader.setForeground(new Color(92, 25, 25)); hostPanel.add(hostHeader, BorderLayout.PAGE_START); hostPanel.add(hostTable, BorderLayout.CENTER); panel.add(hostPanel); pciSystemPanel.add(panel); pciSystemPanel.add(dialChart(pciSystemPanel.getWidth())); return pciSystemPanel; }
From source file:com.xilinx.kintex7.MainScreen.java
private Container createContentPane() { JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); contentPane.setOpaque(true);/*from w w w.j av a 2 s. c o m*/ mainPanel = new JPanel(new BorderLayout()); mainPanel.setBounds(0, 0, minWidth, minHeight); testPanel = new JPanel(new BorderLayout()); testPanel.add(testAndStats(), BorderLayout.CENTER); mainPanel.add(testPanel, BorderLayout.LINE_START); //Make the center component big, since that's the //typical usage of BorderLayout. tabs = new JTabbedPane(); mainPanel.add(tabs, BorderLayout.CENTER); tabs.add("System Monitor", pciInfo()); tabs.add("Performance Plots", plotPanel()); mainPanel.setOpaque(true); try { imagePanel = new ImageBackgroundPanel(blockDiagram, false); } catch (Exception e) { } /*imagePanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createTitledBorder("Design Block Diagram"), BorderFactory.createEmptyBorder(5,5,5,5)));*/ imagePanel.setBackground(Color.WHITE); imagePanel.setSize(minWidth, minHeight); imagePanel.setLocation(0, 0); imagePanel.setOpaque(true); final JLayeredPane layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(new Dimension(minWidth, minHeight)); layeredPane.add(mainPanel, JLayeredPane.DEFAULT_LAYER, 0); layeredPane.add(imagePanel, JLayeredPane.DEFAULT_LAYER, 0); layeredPane.addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent ce) { mainPanel.setBounds(0, 0, Math.max(minWidth, layeredPane.getWidth()), Math.max(minHeight, layeredPane.getHeight())); if (layeredPane.getWidth() > 1024) { tplotPanel.setPreferredSize(new Dimension(300, 100)); } else { tplotPanel.setPreferredSize(new Dimension(200, 100)); } imagePanel.setSize(mainPanel.getWidth(), mainPanel.getHeight()); imagePanel.setLocation(0, 0); mainPanel.repaint(); } @Override public void componentMoved(ComponentEvent ce) { //throw new UnsupportedOperationException("Not supported yet."); } @Override public void componentShown(ComponentEvent ce) { //throw new UnsupportedOperationException("Not supported yet."); } @Override public void componentHidden(ComponentEvent ce) { //throw new UnsupportedOperationException("Not supported yet."); } }); // on top, but invisible initially imagePanel.setVisible(false); JPanel bpanel = new JPanel(new BorderLayout()); final JButton button = new JButton( "<html><b>B<br>L<br>O<br>C<br>K<br> <br>D<br>I<br>A<br>G<br>R<br>A<br>M<br></b></html>"); button.setToolTipText("Click here to see the block diagram"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { adjustSelectionPanel(); } }); bpanel.add(button, BorderLayout.CENTER); contentPane.add(layeredPane, BorderLayout.CENTER); contentPane.add(button, BorderLayout.EAST); JLabel mLabel = new JLabel(modeText, JLabel.CENTER); mLabel.setFont(new Font(modeText, Font.BOLD, 15)); contentPane.add(mLabel, BorderLayout.PAGE_START); return contentPane; }
From source file:at.becast.youploader.gui.FrmMain.java
public void initMainTab() { cmbCategory = new JComboBox<Categories>(); cmbCategory.setModel(new DefaultComboBoxModel<Categories>(Categories.values())); SideBar sideBar = new SideBar(SideBar.SideBarMode.TOP_LEVEL, true, 300, true); ss1 = new SidebarSection(sideBar, LANG.getString("frmMain.Sidebar.Settings"), new EditPanel(this), new ImageIcon(getClass().getResource("/pencil.png"))); ss2 = new SidebarSection(sideBar, LANG.getString("frmMain.Sidebar.Playlists"), new PlaylistPanel(this), new ImageIcon(getClass().getResource("/layers.png"))); ss3 = new SidebarSection(sideBar, LANG.getString("frmMain.Sidebar.Monetisation"), new MonetPanel(), new ImageIcon(getClass().getResource("/money.png"))); sideBar.addSection(ss1, false);//from w w w .j a v a2 s . co m sideBar.addSection(ss2); sideBar.addSection(ss3); JPanel mainTab = new JPanel(); JPanel panel = new JPanel(); GroupLayout mainTabLayout = new GroupLayout(mainTab); mainTabLayout.setHorizontalGroup(mainTabLayout.createParallelGroup(Alignment.TRAILING) .addGroup(mainTabLayout.createSequentialGroup() .addComponent(panel, GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(sideBar, GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE))); mainTabLayout.setVerticalGroup(mainTabLayout.createParallelGroup(Alignment.LEADING) .addComponent(panel, GroupLayout.DEFAULT_SIZE, 492, Short.MAX_VALUE) .addGroup(mainTabLayout.createSequentialGroup() .addComponent(sideBar, GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE).addContainerGap())); panel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("2px"), FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("20px:grow"), FormSpecs.LABEL_COMPONENT_GAP_COLSPEC, ColumnSpec.decode("23px"), ColumnSpec.decode("33px"), FormSpecs.UNRELATED_GAP_COLSPEC, ColumnSpec.decode("61px"), FormSpecs.DEFAULT_COLSPEC, FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("24px"), ColumnSpec.decode("28px"), ColumnSpec.decode("40px"), ColumnSpec.decode("36px"), FormSpecs.LABEL_COMPONENT_GAP_COLSPEC, ColumnSpec.decode("28px"), FormSpecs.LABEL_COMPONENT_GAP_COLSPEC, ColumnSpec.decode("58px"), }, new RowSpec[] { RowSpec.decode("2px"), FormSpecs.RELATED_GAP_ROWSPEC, RowSpec.decode("14px"), RowSpec.decode("25px"), FormSpecs.RELATED_GAP_ROWSPEC, RowSpec.decode("14px"), RowSpec.decode("25px"), FormSpecs.LINE_GAP_ROWSPEC, RowSpec.decode("14px"), RowSpec.decode("25px"), FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, RowSpec.decode("64dlu:grow"), FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, RowSpec.decode("max(64dlu;default)"), FormSpecs.RELATED_GAP_ROWSPEC, FormSpecs.DEFAULT_ROWSPEC, RowSpec.decode("25px"), FormSpecs.PARAGRAPH_GAP_ROWSPEC, RowSpec.decode("24px"), RowSpec.decode("23px"), })); lbltitlelenght = new JLabel("(0/100)"); panel.add(lbltitlelenght, "14, 6, 3, 1, right, top"); txtTitle = new JTextField(); contextMenu.add(txtTitle); panel.add(txtTitle, "3, 7, 14, 1, fill, fill"); txtTitle.setColumns(10); txtTitle.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { calcNotifies(); } }); JLabel lblCategory = new JLabel(LANG.getString("frmMain.Category")); panel.add(lblCategory, "3, 9, 4, 1, left, bottom"); panel.add(cmbCategory, "3, 10, 14, 1, fill, fill"); JLabel lblDescription = new JLabel(LANG.getString("frmMain.Description")); panel.add(lblDescription, "3, 12, 4, 1, left, bottom"); lblDesclenght = new JLabel("(0/5000)"); panel.add(lblDesclenght, "14, 12, 3, 1, right, bottom"); JScrollPane DescriptionScrollPane = new JScrollPane(); panel.add(DescriptionScrollPane, "3, 13, 14, 1, fill, fill"); txtDescription = new JTextArea(); contextMenu.add(txtDescription); txtDescription.setFont(new Font("SansSerif", Font.PLAIN, 13)); DescriptionScrollPane.setViewportView(txtDescription); txtDescription.setWrapStyleWord(true); txtDescription.setLineWrap(true); txtDescription.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { calcNotifies(); } }); JLabel lblTags = new JLabel(LANG.getString("frmMain.Tags")); panel.add(lblTags, "3, 15, 4, 1, left, bottom"); lblTagslenght = new JLabel("(0/500)"); panel.add(lblTagslenght, "14, 15, 3, 1, right, top"); JScrollPane TagScrollPane = new JScrollPane(); panel.add(TagScrollPane, "3, 16, 14, 1, fill, fill"); txtTags = new JTextArea(); contextMenu.add(txtTags); txtTags.setFont(new Font("SansSerif", Font.PLAIN, 13)); TagScrollPane.setViewportView(txtTags); txtTags.setWrapStyleWord(true); txtTags.setLineWrap(true); txtTags.setBorder(BorderFactory.createEtchedBorder()); txtTags.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { calcNotifies(); } }); JLabel lblAccount = new JLabel(LANG.getString("frmMain.Account")); panel.add(lblAccount, "3, 18, 4, 1, left, bottom"); cmbAccount = new JComboBox<AccountType>(); panel.add(getCmbAccount(), "3, 19, 14, 1, fill, fill"); cmbAccount.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeUser(); } }); btnAddToQueue = new JButton(LANG.getString("frmMain.addtoQueue")); btnAddToQueue.setEnabled(false); panel.add(btnAddToQueue, "3, 21, 6, 1, fill, fill"); btnAddToQueue.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { queueButton(); } }); JLabel lblSelectVideo = new JLabel(); panel.add(lblSelectVideo, "3, 3, 4, 1, left, bottom"); lblSelectVideo.setText(LANG.getString("frmMain.selectVideoFile")); cmbFile = new JComboBox<String>(); cmbFile.setDropTarget(new DropTarget() { private static final long serialVersionUID = 8809983794742040683L; public synchronized void drop(DropTargetDropEvent evt) { try { evt.acceptDrop(DnDConstants.ACTION_COPY); @SuppressWarnings("unchecked") List<File> droppedFiles = (List<File>) evt.getTransferable() .getTransferData(DataFlavor.javaFileListFlavor); for (File file : droppedFiles) { cmbFile.removeAllItems(); cmbFile.addItem(file.getAbsolutePath()); } } catch (Exception ex) { LOG.error("Error dropping video file", ex); } } }); panel.add(cmbFile, "3, 4, 14, 1, fill, fill"); JButton btnSelectMovie = new JButton(); btnSelectMovie.setToolTipText("Select Video File"); panel.add(btnSelectMovie, "18, 4, center, top"); btnSelectMovie.setIcon(new ImageIcon(getClass().getResource("/film_add.png"))); JLabel lblTitle = new JLabel(LANG.getString("frmMain.Title")); panel.add(lblTitle, "3, 6, 4, 1, left, bottom"); JButton btnReset = new JButton(LANG.getString("frmMain.Reset")); btnReset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { resetEdit(); } }); panel.add(btnReset, "11, 21, 6, 1, fill, fill"); btnSelectMovie.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { EditPanel edit = (EditPanel) ss1.contentPane; NativeJFileChooser chooser; if (edit.getTxtStartDir() != null && !edit.getTxtStartDir().equals("")) { chooser = new NativeJFileChooser(edit.getTxtStartDir().getText().trim()); } else { chooser = new NativeJFileChooser(); } int returnVal = chooser.showOpenDialog((Component) self); if (returnVal == JFileChooser.APPROVE_OPTION) { cmbFile.removeAllItems(); cmbFile.addItem(chooser.getSelectedFile().getAbsolutePath().toString()); } } }); mainTab.setLayout(mainTabLayout); mainTab.revalidate(); mainTab.repaint(); TabbedPane.addTab(LANG.getString("frmMain.Tabs.VideoSettings"), mainTab); }
From source file:com.emental.mindraider.ui.frames.MindRaiderMainWindow.java
/** * Maximize left side bar./*www.ja va 2 s.c om*/ * * @param maximizeButton * the maximize JButton */ public void maximizeLeftSidebar(JButton maximizeButton) { if (latelyMaximized) { restoreLeftSidebar(); if (maximizeButton != null) { maximizeButton.setIcon(IconsRegistry.getImageIcon("explorerMaximizeRight.png")); maximizeButton.setToolTipText(Messages.getString("MindRaiderJFrame.maximizeExplorerSidebar")); } latelyMaximized = false; } else { leftSidebarSplitPane.setDividerLocation(2000); if (maximizeButton != null) { maximizeButton.setIcon(IconsRegistry.getImageIcon("explorerRestoreLeft.png")); maximizeButton.setToolTipText(Messages.getString("MindRaiderJFrame.restoreExplorerSidebar")); } latelyMaximized = true; } }
From source file:com._17od.upm.gui.AccountDialog.java
public AccountDialog(AccountInformation account, JFrame parentWindow, boolean readOnly, ArrayList existingAccounts) { super(parentWindow, true); boolean addingAccount = false; //Request focus on Account JDialog when mouse clicked this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) { requestFocus();/*from w ww . j a v a2 s . c om*/ } } }); // Set the title based on weather we've been opened in readonly mode and // weather the // Account passed in is empty or not String title = null; if (readOnly) { title = Translator.translate("viewAccount"); } else if (!readOnly && account.getAccountName().trim().equals("")) { title = Translator.translate("addAccount"); addingAccount = true; } else { title = Translator.translate("editAccount"); } setTitle(title); this.pAccount = account; this.existingAccounts = existingAccounts; this.parentWindow = parentWindow; getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); Container container = getContentPane(); // The AccountName Row JLabel accountLabel = new JLabel(Translator.translate("account")); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; container.add(accountLabel, c); // This panel will hold the Account field and the copy and paste // buttons. JPanel accountPanel = new JPanel(new GridBagLayout()); accountName = new JTextField(new String(pAccount.getAccountName()), 20); if (readOnly) { accountName.setEditable(false); } c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; accountPanel.add(accountName, c); accountName.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { accountName.selectAll(); } }); JButton acctCopyButton = new JButton(); acctCopyButton.setIcon(Util.loadImage("copy-icon.png")); acctCopyButton.setToolTipText("Copy"); acctCopyButton.setEnabled(true); acctCopyButton.setMargin(new Insets(0, 0, 0, 0)); acctCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { copyTextField(accountName); } }); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; accountPanel.add(acctCopyButton, c); JButton acctPasteButton = new JButton(); acctPasteButton.setIcon(Util.loadImage("paste-icon.png")); acctPasteButton.setToolTipText("Paste"); acctPasteButton.setEnabled(!readOnly); acctPasteButton.setMargin(new Insets(0, 0, 0, 0)); acctPasteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { pasteToTextField(accountName); } }); c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; accountPanel.add(acctPasteButton, c); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; container.add(accountPanel, c); // Userid Row JLabel useridLabel = new JLabel(Translator.translate("userid")); c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; container.add(useridLabel, c); // This panel will hold the User ID field and the copy and paste // buttons. JPanel idPanel = new JPanel(new GridBagLayout()); userId = new JTextField(new String(pAccount.getUserId()), 20); if (readOnly) { userId.setEditable(false); } c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; idPanel.add(userId, c); userId.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { userId.selectAll(); } }); JButton idCopyButton = new JButton(); idCopyButton.setIcon(Util.loadImage("copy-icon.png")); idCopyButton.setToolTipText("Copy"); idCopyButton.setEnabled(true); idCopyButton.setMargin(new Insets(0, 0, 0, 0)); idCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { copyTextField(userId); } }); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; idPanel.add(idCopyButton, c); JButton idPasteButton = new JButton(); idPasteButton.setIcon(Util.loadImage("paste-icon.png")); idPasteButton.setToolTipText("Paste"); idPasteButton.setEnabled(!readOnly); idPasteButton.setMargin(new Insets(0, 0, 0, 0)); idPasteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { pasteToTextField(userId); } }); c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; idPanel.add(idPasteButton, c); c.gridx = 1; c.gridy = 1; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; container.add(idPanel, c); // Password Row JLabel passwordLabel = new JLabel(Translator.translate("password")); c.gridx = 0; c.gridy = 2; c.anchor = GridBagConstraints.FIRST_LINE_START; c.insets = new Insets(15, 10, 10, 10); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; container.add(passwordLabel, c); // This panel will hold the password, generate password button, copy and // paste buttons, and hide password checkbox JPanel passwordPanel = new JPanel(new GridBagLayout()); password = new JPasswordField(new String(pAccount.getPassword()), 20); // allow CTRL-C on the password field password.putClientProperty("JPasswordField.cutCopyAllowed", Boolean.TRUE); password.setEditable(!readOnly); password.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { password.selectAll(); } }); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 1; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; passwordPanel.add(password, c); JButton generateRandomPasswordButton = new JButton(Translator.translate("generate")); if (readOnly) { generateRandomPasswordButton.setEnabled(false); } generateRandomPasswordButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionevent) { // Get the user's preference about including or not Escape // Characters to generated passwords Boolean includeEscapeChars = new Boolean( Preferences.get(Preferences.ApplicationOptions.INCLUDE_ESCAPE_CHARACTERS, "true")); int pwLength = Preferences.getInt(Preferences.ApplicationOptions.ACCOUNT_PASSWORD_LENGTH, 8); String Password; if ((includeEscapeChars.booleanValue()) && (pwLength > 3)) { // Verify that the generated password satisfies the criteria // for strong passwords(including Escape Characters) do { Password = GeneratePassword(pwLength, includeEscapeChars.booleanValue()); } while (!(CheckPassStrong(Password, includeEscapeChars.booleanValue()))); } else if (!(includeEscapeChars.booleanValue()) && (pwLength > 2)) { // Verify that the generated password satisfies the criteria // for strong passwords(excluding Escape Characters) do { Password = GeneratePassword(pwLength, includeEscapeChars.booleanValue()); } while (!(CheckPassStrong(Password, includeEscapeChars.booleanValue()))); } else { // Else a weak password of 3 or less chars will be produced Password = GeneratePassword(pwLength, includeEscapeChars.booleanValue()); } password.setText(Password); } }); if (addingAccount) { generateRandomPasswordButton.doClick(); } c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; passwordPanel.add(generateRandomPasswordButton, c); JButton pwCopyButton = new JButton(); pwCopyButton.setIcon(Util.loadImage("copy-icon.png")); pwCopyButton.setToolTipText("Copy"); pwCopyButton.setEnabled(true); pwCopyButton.setMargin(new Insets(0, 0, 0, 0)); pwCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { copyTextField(password); } }); c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; passwordPanel.add(pwCopyButton, c); JButton pwPasteButton = new JButton(); pwPasteButton.setIcon(Util.loadImage("paste-icon.png")); pwPasteButton.setToolTipText("Paste"); pwPasteButton.setEnabled(!readOnly); pwPasteButton.setMargin(new Insets(0, 0, 0, 0)); pwPasteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { pasteToTextField(password); } }); c.gridx = 3; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; passwordPanel.add(pwPasteButton, c); JCheckBox hidePasswordCheckbox = new JCheckBox(Translator.translate("hide"), true); defaultEchoChar = password.getEchoChar(); hidePasswordCheckbox.setMargin(new Insets(5, 0, 5, 0)); hidePasswordCheckbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { password.setEchoChar(defaultEchoChar); } else { password.setEchoChar((char) 0); } } }); Boolean hideAccountPassword = new Boolean( Preferences.get(Preferences.ApplicationOptions.ACCOUNT_HIDE_PASSWORD, "true")); hidePasswordCheckbox.setSelected(hideAccountPassword.booleanValue()); c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 0); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; passwordPanel.add(hidePasswordCheckbox, c); c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 1; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; container.add(passwordPanel, c); // URL Row JLabel urlLabel = new JLabel(Translator.translate("url")); c.gridx = 0; c.gridy = 3; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; container.add(urlLabel, c); // This panel will hold the URL field and the copy and paste buttons. JPanel urlPanel = new JPanel(new GridBagLayout()); url = new JTextField(new String(pAccount.getUrl()), 20); if (readOnly) { url.setEditable(false); } c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; urlPanel.add(url, c); url.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { url.selectAll(); } }); final JButton urlLaunchButton = new JButton(); urlLaunchButton.setIcon(Util.loadImage("launch-url-sm.png")); urlLaunchButton.setToolTipText("Launch URL"); urlLaunchButton.setEnabled(true); urlLaunchButton.setMargin(new Insets(0, 0, 0, 0)); urlLaunchButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String urlText = url.getText(); // Check if the selected url is null or emty and inform the user // via JoptioPane message if ((urlText == null) || (urlText.length() == 0)) { JOptionPane.showMessageDialog(urlLaunchButton.getParent(), Translator.translate("EmptyUrlJoptionpaneMsg"), Translator.translate("UrlErrorJoptionpaneTitle"), JOptionPane.WARNING_MESSAGE); // Check if the selected url is a valid formated url(via // urlIsValid() method) and inform the user via JoptioPane // message } else if (!(urlIsValid(urlText))) { JOptionPane.showMessageDialog(urlLaunchButton.getParent(), Translator.translate("InvalidUrlJoptionpaneMsg"), Translator.translate("UrlErrorJoptionpaneTitle"), JOptionPane.WARNING_MESSAGE); // Call the method LaunchSelectedURL() using the selected // url as input } else { LaunchSelectedURL(urlText); } } }); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; urlPanel.add(urlLaunchButton, c); JButton urlCopyButton = new JButton(); urlCopyButton.setIcon(Util.loadImage("copy-icon.png")); urlCopyButton.setToolTipText("Copy"); urlCopyButton.setEnabled(true); urlCopyButton.setMargin(new Insets(0, 0, 0, 0)); urlCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { copyTextField(url); } }); c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; urlPanel.add(urlCopyButton, c); JButton urlPasteButton = new JButton(); urlPasteButton.setIcon(Util.loadImage("paste-icon.png")); urlPasteButton.setToolTipText("Paste"); urlPasteButton.setEnabled(!readOnly); urlPasteButton.setMargin(new Insets(0, 0, 0, 0)); urlPasteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { pasteToTextField(url); } }); c.gridx = 3; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; urlPanel.add(urlPasteButton, c); c.gridx = 1; c.gridy = 3; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; container.add(urlPanel, c); // Notes Row JLabel notesLabel = new JLabel(Translator.translate("notes")); c.gridx = 0; c.gridy = 4; c.anchor = GridBagConstraints.FIRST_LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; container.add(notesLabel, c); // This panel will hold the Notes text area and the copy and paste // buttons. JPanel notesPanel = new JPanel(new GridBagLayout()); notes = new JTextArea(new String(pAccount.getNotes()), 10, 20); if (readOnly) { notes.setEditable(false); } notes.setLineWrap(true); // Enable line wrapping. notes.setWrapStyleWord(true); // Line wrap at whitespace. JScrollPane notesScrollPane = new JScrollPane(notes); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.BOTH; notesPanel.add(notesScrollPane, c); JButton notesCopyButton = new JButton(); notesCopyButton.setIcon(Util.loadImage("copy-icon.png")); notesCopyButton.setToolTipText("Copy"); notesCopyButton.setEnabled(true); notesCopyButton.setMargin(new Insets(0, 0, 0, 0)); notesCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { copyTextArea(notes); } }); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.FIRST_LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; notesPanel.add(notesCopyButton, c); JButton notesPasteButton = new JButton(); notesPasteButton.setIcon(Util.loadImage("paste-icon.png")); notesPasteButton.setToolTipText("Paste"); notesPasteButton.setEnabled(!readOnly); notesPasteButton.setMargin(new Insets(0, 0, 0, 0)); notesPasteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { pasteToTextArea(notes); } }); c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.FIRST_LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; notesPanel.add(notesPasteButton, c); c.gridx = 1; c.gridy = 4; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; container.add(notesPanel, c); // Seperator Row JSeparator sep = new JSeparator(); c.gridx = 0; c.gridy = 5; c.anchor = GridBagConstraints.PAGE_END; c.insets = new Insets(0, 0, 0, 0); c.weightx = 0; c.weighty = 0; c.gridwidth = 3; c.fill = GridBagConstraints.HORIZONTAL; container.add(sep, c); // Button Row JPanel buttonPanel = new JPanel(); JButton okButton = new JButton(Translator.translate("ok")); // Link Enter key to okButton getRootPane().setDefaultButton(okButton); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { okButtonAction(); } }); buttonPanel.add(okButton); if (!readOnly) { JButton cancelButton = new JButton(Translator.translate("cancel")); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeButtonAction(); } }); buttonPanel.add(cancelButton); } c.gridx = 0; c.gridy = 6; c.anchor = GridBagConstraints.PAGE_END; c.insets = new Insets(5, 0, 5, 0); c.weightx = 0; c.weighty = 0; c.gridwidth = 3; c.fill = GridBagConstraints.NONE; container.add(buttonPanel, c); }
From source file:Installer.java
public Installer(File targetDir) { ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE); this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); JPanel logoSplash = new JPanel(); logoSplash.setLayout(new BoxLayout(logoSplash, BoxLayout.Y_AXIS)); try {//from w ww . ja va2 s. c om // Read png BufferedImage image; image = ImageIO.read(Installer.class.getResourceAsStream("logo.png")); ImageIcon icon = new ImageIcon(image); JLabel logoLabel = new JLabel(icon); logoLabel.setAlignmentX(CENTER_ALIGNMENT); logoLabel.setAlignmentY(CENTER_ALIGNMENT); logoLabel.setSize(image.getWidth(), image.getHeight()); if (!QUIET_DEV) // VIVE - hide oculus logo logoSplash.add(logoLabel); } catch (IOException e) { } catch (IllegalArgumentException e) { } userHomeDir = System.getProperty("user.home", "."); osType = System.getProperty("os.name").toLowerCase(); if (osType.contains("win")) { isWindows = true; appDataDir = System.getenv("APPDATA"); } version = "UNKNOWN"; try { InputStream ver = Installer.class.getResourceAsStream("version"); if (ver != null) { String[] tok = new BufferedReader(new InputStreamReader(ver)).readLine().split(":"); if (tok.length > 0) { jar_id = tok[0]; version = tok[1]; } } } catch (IOException e) { } // Read release notes, save to file String tmpFileName = System.getProperty("java.io.tmpdir") + releaseNotePathAddition + "Vivecraft" + version.toLowerCase() + "_release_notes.txt"; releaseNotes = new File(tmpFileName); InputStream is = Installer.class.getResourceAsStream("release_notes.txt"); if (!copyInputStreamToFile(is, releaseNotes)) { releaseNotes = null; } JLabel tag = new JLabel("Welcome! This will install Vivecraft " + version); tag.setAlignmentX(CENTER_ALIGNMENT); tag.setAlignmentY(CENTER_ALIGNMENT); logoSplash.add(tag); logoSplash.add(Box.createRigidArea(new Dimension(5, 20))); tag = new JLabel("Select path to minecraft. (The default here is almost always what you want.)"); tag.setAlignmentX(CENTER_ALIGNMENT); tag.setAlignmentY(CENTER_ALIGNMENT); logoSplash.add(tag); logoSplash.setAlignmentX(CENTER_ALIGNMENT); logoSplash.setAlignmentY(TOP_ALIGNMENT); this.add(logoSplash); JPanel entryPanel = new JPanel(); entryPanel.setLayout(new BoxLayout(entryPanel, BoxLayout.X_AXIS)); Installer.targetDir = targetDir; selectedDirText = new JTextField(); selectedDirText.setEditable(false); selectedDirText.setToolTipText("Path to minecraft"); selectedDirText.setColumns(30); entryPanel.add(selectedDirText); JButton dirSelect = new JButton(); dirSelect.setAction(new FileSelectAction()); dirSelect.setText("..."); dirSelect.setToolTipText("Select an alternative minecraft directory"); entryPanel.add(dirSelect); entryPanel.setAlignmentX(LEFT_ALIGNMENT); entryPanel.setAlignmentY(TOP_ALIGNMENT); infoLabel = new JLabel(); infoLabel.setHorizontalTextPosition(JLabel.LEFT); infoLabel.setVerticalTextPosition(JLabel.TOP); infoLabel.setAlignmentX(LEFT_ALIGNMENT); infoLabel.setAlignmentY(TOP_ALIGNMENT); infoLabel.setVisible(false); fileEntryPanel = new JPanel(); fileEntryPanel.setLayout(new BoxLayout(fileEntryPanel, BoxLayout.Y_AXIS)); fileEntryPanel.add(infoLabel); fileEntryPanel.add(entryPanel); fileEntryPanel.setAlignmentX(CENTER_ALIGNMENT); fileEntryPanel.setAlignmentY(TOP_ALIGNMENT); this.add(fileEntryPanel); this.add(Box.createVerticalStrut(5)); JPanel optPanel = new JPanel(); optPanel.setLayout(new BoxLayout(optPanel, BoxLayout.Y_AXIS)); optPanel.setAlignmentX(LEFT_ALIGNMENT); optPanel.setAlignmentY(TOP_ALIGNMENT); //Add forge options JPanel forgePanel = new JPanel(); forgePanel.setLayout(new BoxLayout(forgePanel, BoxLayout.X_AXIS)); //Create forge: no/yes buttons useForge = new JCheckBox(); AbstractAction actf = new updateActionF(); actf.putValue(AbstractAction.NAME, "Install Vivecraft with Forge " + FORGE_VERSION); useForge.setAction(actf); forgeVersion = new JComboBox(); if (!ALLOW_FORGE_INSTALL) useForge.setEnabled(false); useForge.setToolTipText( "<html>" + "If checked, installs Vivecraft with Forge support. The correct version of Forge<br>" + "(as displayed) must already be installed.<br>" + "</html>"); //Add "yes" and "which version" to the forgePanel useForge.setAlignmentX(LEFT_ALIGNMENT); forgeVersion.setAlignmentX(LEFT_ALIGNMENT); forgePanel.add(useForge); //forgePanel.add(forgeVersion); // Profile creation / update support createProfile = new JCheckBox("", true); AbstractAction actp = new updateActionP(); actp.putValue(AbstractAction.NAME, "Create Vivecraft launcher profile"); createProfile.setAction(actp); createProfile.setAlignmentX(LEFT_ALIGNMENT); createProfile.setSelected(true); createProfile.setToolTipText("<html>" + "If checked, if a Vivecraft profile doesn't already exist within the Minecraft launcher<br>" + "one is added. Then the profile is selected, and this Vivecraft version is set as the<br>" + "current version.<br>" + "</html>"); useShadersMod = new JCheckBox(); useShadersMod.setAlignmentX(LEFT_ALIGNMENT); if (!ALLOW_SHADERSMOD_INSTALL) useShadersMod.setEnabled(false); AbstractAction acts = new updateActionSM(); acts.putValue(AbstractAction.NAME, "Install Vivecraft with ShadersMod 2.3.29"); useShadersMod.setAction(acts); useShadersMod.setToolTipText("<html>" + "If checked, sets the vivecraft profile to use ShadersMod <br>" + "support." + "</html>"); useHydra = new JCheckBox("Razer Hydra support", false); useHydra.setAlignmentX(LEFT_ALIGNMENT); if (!ALLOW_HYDRA_INSTALL) useHydra.setEnabled(false); useHydra.setToolTipText("<html>" + "If checked, installs the additional Razor Hydra native library required for Razor Hydra<br>" + "support." + "</html>"); useHrtf = new JCheckBox("Enable binaural audio (Only needed once per PC)", false); useHrtf.setToolTipText("<html>" + "If checked, the installer will create the configuration file needed for OpenAL HRTF<br>" + "ear-aware sound in Minecraft (and other games).<br>" + " If the file has previously been created, you do not need to check this again.<br>" + " NOTE: Your sound card's output MUST be set to 44.1Khz.<br>" + " WARNING, will overwrite " + (isWindows ? (appDataDir + "\\alsoft.ini") : (userHomeDir + "/.alsoftrc")) + "!<br>" + " Delete the " + (isWindows ? "alsoft.ini" : "alsoftrc") + " file to disable HRTF again." + "</html>"); useHrtf.setAlignmentX(LEFT_ALIGNMENT); //Add option panels option panel forgePanel.setAlignmentX(LEFT_ALIGNMENT); //optPanel.add(forgePanel); //optPanel.add(useShadersMod); optPanel.add(createProfile); optPanel.add(useHrtf); this.add(optPanel); this.add(Box.createRigidArea(new Dimension(5, 20))); instructions = new JLabel("", SwingConstants.CENTER); instructions.setAlignmentX(CENTER_ALIGNMENT); instructions.setAlignmentY(TOP_ALIGNMENT); instructions.setForeground(Color.RED); instructions.setPreferredSize(new Dimension(20, 40)); this.add(instructions); this.add(Box.createVerticalGlue()); JLabel github = linkify("Vivecraft is open source. find it on Github", "https://github.com/jrbudda/Vivecraft_111", "Vivecraft 1.11 Github"); JLabel wiki = linkify("Vivecraft home page", "http://www.vivecraft.org", "Vivecraft Home"); JLabel donate = linkify("If you think Vivecraft is awesome, please consider donating.", "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=JVBJLN5HJJS52&lc=US&item_name=jrbudda¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted)", "jrbudda's Paypal"); JLabel optifine = linkify("Vivecraft includes OptiFine for performance. Consider donating to them as well.", "http://optifine.net/donate.php", "http://optifine.net/donate.php"); github.setAlignmentX(CENTER_ALIGNMENT); github.setHorizontalAlignment(SwingConstants.CENTER); wiki.setAlignmentX(CENTER_ALIGNMENT); wiki.setHorizontalAlignment(SwingConstants.CENTER); donate.setAlignmentX(CENTER_ALIGNMENT); donate.setHorizontalAlignment(SwingConstants.CENTER); optifine.setAlignmentX(CENTER_ALIGNMENT); optifine.setHorizontalAlignment(SwingConstants.CENTER); this.add(Box.createRigidArea(new Dimension(5, 20))); this.add(github); this.add(wiki); this.add(donate); this.add(optifine); this.setAlignmentX(LEFT_ALIGNMENT); updateFilePath(); updateInstructions(); }
From source file:edu.snu.leader.discrete.simulator.SimulatorLauncherGUI.java
/** * Create the frame.//w w w. j av a 2s . co m */ public SimulatorLauncherGUI() { NumberFormat countFormat = NumberFormat.getNumberInstance(); countFormat.setParseIntegerOnly(true); NumberFormat doubleFormat = NumberFormat.getNumberInstance(); doubleFormat.setMinimumIntegerDigits(1); doubleFormat.setMaximumFractionDigits(10); setTitle("Simulator"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 515, 340); setResizable(false); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); tabbedPane = new JTabbedPane(JTabbedPane.TOP); contentPane.add(tabbedPane, BorderLayout.CENTER); JPanel panelTab1 = new JPanel(); tabbedPane.addTab("Simulator", null, panelTab1, null); JPanel panelAgentCount = new JPanel(); panelTab1.add(panelAgentCount); JLabel lblNewLabel = new JLabel("Agent Count"); panelAgentCount.add(lblNewLabel); sliderAgent = new JSlider(); panelAgentCount.add(sliderAgent); sliderAgent.setValue(10); sliderAgent.setSnapToTicks(true); sliderAgent.setPaintTicks(true); sliderAgent.setPaintLabels(true); sliderAgent.setMinorTickSpacing(10); sliderAgent.setMajorTickSpacing(10); sliderAgent.setMinimum(10); sliderAgent.setMaximum(70); sliderAgent.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent arg0) { Integer spinnerValue = (Integer) spinnerMaxEaten.getValue(); if (spinnerValue > sliderAgent.getValue()) { spinnerValue = sliderAgent.getValue(); } spinnerMaxEaten.setModel(new SpinnerNumberModel(spinnerValue, new Integer(0), new Integer(sliderAgent.getValue()), new Integer(1))); JFormattedTextField tfMaxEaten = ((JSpinner.DefaultEditor) spinnerMaxEaten.getEditor()) .getTextField(); tfMaxEaten.setEditable(false); } }); JPanel panelCommType = new JPanel(); panelTab1.add(panelCommType); JLabel lblNewLabel_1 = new JLabel("Communication Type"); panelCommType.add(lblNewLabel_1); comboBoxCommType = new JComboBox<String>(); panelCommType.add(comboBoxCommType); comboBoxCommType .setModel(new DefaultComboBoxModel<String>(new String[] { "Global", "Topological", "Metric" })); comboBoxCommType.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String item = (String) comboBoxCommType.getSelectedItem(); if (item.equals("Topological")) { panelNearestNeighborCount.setVisible(true); panelMaxLocationRadius.setVisible(false); } else if (item.equals("Metric")) { panelNearestNeighborCount.setVisible(false); panelMaxLocationRadius.setVisible(true); } else if (item.equals("Global")) { panelNearestNeighborCount.setVisible(false); panelMaxLocationRadius.setVisible(false); } } }); JPanel panelDestinationRadius = new JPanel(); panelTab1.add(panelDestinationRadius); JLabel lblDestinationRadius = new JLabel("Destination Radius"); panelDestinationRadius.add(lblDestinationRadius); frmtdtxtfldDestinationRadius = new JFormattedTextField(doubleFormat); frmtdtxtfldDestinationRadius.setColumns(4); frmtdtxtfldDestinationRadius.setValue((Number) 10); panelDestinationRadius.add(frmtdtxtfldDestinationRadius); JPanel panelResultsOutput = new JPanel(); panelTab1.add(panelResultsOutput); JLabel lblResultsOutput = new JLabel("Results Output"); panelResultsOutput.add(lblResultsOutput); final JCheckBox chckbxEskridge = new JCheckBox("Eskridge"); panelResultsOutput.add(chckbxEskridge); final JCheckBox chckbxConflict = new JCheckBox("Conflict"); panelResultsOutput.add(chckbxConflict); final JCheckBox chckbxPosition = new JCheckBox("Position"); panelResultsOutput.add(chckbxPosition); final JCheckBox chckbxPredationResults = new JCheckBox("Predation"); panelResultsOutput.add(chckbxPredationResults); JPanel panelMisc = new JPanel(); panelTab1.add(panelMisc); JLabel lblNewLabel_3 = new JLabel("Misc"); panelMisc.add(lblNewLabel_3); chckbxGraphical = new JCheckBox("Graphical?"); chckbxGraphical.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (chckbxGraphical.isSelected()) { frmtdtxtfldRunCount.setValue((Number) 1); frmtdtxtfldRunCount.setEnabled(false); chckbxEskridge.setSelected(false); chckbxEskridge.setEnabled(false); String agentBuilder = (String) comboBoxAgentBuilder.getSelectedItem(); if (agentBuilder.equals("Default")) { comboBoxAgentBuilder.setSelectedIndex(1); } } else { chckbxEskridge.setEnabled(true); frmtdtxtfldRunCount.setEnabled(true); } } }); panelMisc.add(chckbxGraphical); chckbxRandomSeed = new JCheckBox("Random Seed?"); panelMisc.add(chckbxRandomSeed); chckbxPredationEnable = new JCheckBox("Predation?"); chckbxPredationEnable.setSelected(true); chckbxPredationEnable.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (chckbxPredationEnable.isSelected()) { panelPredationStuff.setVisible(true); panelPredationBoxes.setVisible(true); panelPredationConstant.setVisible(true); panelNonMoversSurvive.setVisible(true); } else { panelPredationStuff.setVisible(false); panelPredationBoxes.setVisible(false); panelPredationConstant.setVisible(false); panelNonMoversSurvive.setVisible(false); } } }); panelMisc.add(chckbxPredationEnable); JPanel panelCounts = new JPanel(); panelTab1.add(panelCounts); JLabel lblNewLabel_4 = new JLabel("Run Count"); panelCounts.add(lblNewLabel_4); frmtdtxtfldRunCount = new JFormattedTextField(countFormat); frmtdtxtfldRunCount.setToolTipText("The number of runs. Each run has a different random seed."); panelCounts.add(frmtdtxtfldRunCount); frmtdtxtfldRunCount.setColumns(4); frmtdtxtfldRunCount.setValue((Number) 1); JLabel lblNewLabel_5 = new JLabel("Sim Count"); panelCounts.add(lblNewLabel_5); frmtdtxtfldSimCount = new JFormattedTextField(countFormat); frmtdtxtfldSimCount .setToolTipText("The number of simulations per run. Each simulation uses the same random seed."); frmtdtxtfldSimCount.setColumns(4); frmtdtxtfldSimCount.setValue((Number) 1); panelCounts.add(frmtdtxtfldSimCount); JLabel lblNewLabel_6 = new JLabel("Max Time Steps"); panelCounts.add(lblNewLabel_6); frmtdtxtfldMaxTimeSteps = new JFormattedTextField(countFormat); frmtdtxtfldMaxTimeSteps.setToolTipText("The max number of time steps per simulation."); frmtdtxtfldMaxTimeSteps.setColumns(6); frmtdtxtfldMaxTimeSteps.setValue((Number) 20000); panelCounts.add(frmtdtxtfldMaxTimeSteps); ////////Panel tab 2 JPanel panelTab2 = new JPanel(); tabbedPane.addTab("Parameters", null, panelTab2, null); JPanel panelDecisionCalculator = new JPanel(); panelTab2.add(panelDecisionCalculator); JLabel lblDecisionCalculator = new JLabel("Decision Calculator"); panelDecisionCalculator.add(lblDecisionCalculator); final JComboBox<String> comboBoxDecisionCalculator = new JComboBox<String>(); panelDecisionCalculator.add(comboBoxDecisionCalculator); comboBoxDecisionCalculator.setModel( new DefaultComboBoxModel<String>(new String[] { "Default", "Conflict", "Conflict Uninformed" })); JPanel panelAgentBuilder = new JPanel(); panelTab2.add(panelAgentBuilder); JLabel lblAgentBuilder = new JLabel("Agent Builder"); panelAgentBuilder.add(lblAgentBuilder); comboBoxAgentBuilder = new JComboBox<String>(); panelAgentBuilder.add(comboBoxAgentBuilder); comboBoxAgentBuilder.setModel(new DefaultComboBoxModel<String>(new String[] { "Default", "Simple Angular", "Personality Simple Angular", "Simple Angular Uninformed" })); comboBoxAgentBuilder.setSelectedIndex(1); comboBoxAgentBuilder.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (chckbxGraphical.isSelected()) { String agentBuilder = (String) comboBoxAgentBuilder.getSelectedItem(); if (agentBuilder.equals("Default")) { comboBoxAgentBuilder.setSelectedIndex(1); } } } }); JPanel panelModel = new JPanel(); panelTab2.add(panelModel); JLabel lblModel = new JLabel("Model"); panelModel.add(lblModel); comboBoxModel = new JComboBox<String>(); panelModel.add(comboBoxModel); comboBoxModel.setModel(new DefaultComboBoxModel<String>(new String[] { "Sueur", "Gautrais" })); comboBoxModel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String item = (String) comboBoxModel.getSelectedItem(); if (item.equals("Sueur")) { panelSueurValues.setVisible(true); panelGautraisValues.setVisible(false); } else if (item.equals("Gautrais")) { panelSueurValues.setVisible(false); panelGautraisValues.setVisible(true); } } }); JPanel panelEnvironment = new JPanel(); panelTab2.add(panelEnvironment); JLabel lblEnvironment = new JLabel("Environment"); panelEnvironment.add(lblEnvironment); comboBoxEnvironment = new JComboBox<String>(); comboBoxEnvironment.setModel( new DefaultComboBoxModel<String>(new String[] { "Minimum", "Medium", "Maximum", "Uninformed" })); comboBoxEnvironment.setSelectedIndex(1); comboBoxEnvironment.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String item = (String) comboBoxEnvironment.getSelectedItem(); if (!item.equals("Uninformed")) { comboBoxDecisionCalculator.setEnabled(true); comboBoxAgentBuilder.setEnabled(true); } if (item.equals("Medium")) { panelAngle.setVisible(true); panelDistance.setVisible(true); panelPercentage.setVisible(true); panelNumberOfDestinations.setVisible(false); panelInformedCount.setVisible(false); } else if (item.equals("Minimum")) { panelAngle.setVisible(false); panelDistance.setVisible(false); panelPercentage.setVisible(true); panelNumberOfDestinations.setVisible(false); panelInformedCount.setVisible(false); } else if (item.equals("Maximum")) { panelAngle.setVisible(false); panelDistance.setVisible(false); panelPercentage.setVisible(true); panelNumberOfDestinations.setVisible(false); panelInformedCount.setVisible(false); } else if (item.equals("Uninformed")) { panelAngle.setVisible(true); panelDistance.setVisible(true); panelPercentage.setVisible(true); panelNumberOfDestinations.setVisible(false); panelInformedCount.setVisible(true); comboBoxDecisionCalculator.setSelectedIndex(2); comboBoxDecisionCalculator.setEnabled(false); comboBoxAgentBuilder.setSelectedIndex(3); comboBoxAgentBuilder.setEnabled(false); } } }); panelEnvironment.add(comboBoxEnvironment); JPanel panelDefaultConflict = new JPanel(); panelTab2.add(panelDefaultConflict); JLabel lblDefaultConflict = new JLabel("Default Conflict"); panelDefaultConflict.add(lblDefaultConflict); final JSpinner spinnerDefaultConflict = new JSpinner(); panelDefaultConflict.add(spinnerDefaultConflict); spinnerDefaultConflict.setModel( new SpinnerNumberModel(new Float(0.9f), new Float(0.1f), new Float(0.91f), new Float(0.05))); JFormattedTextField tfSpinnerConflict = ((JSpinner.DefaultEditor) spinnerDefaultConflict.getEditor()) .getTextField(); tfSpinnerConflict.setEditable(false); JPanel panelCancelationThreshold = new JPanel(); panelTab2.add(panelCancelationThreshold); JLabel lblCancelationThreshold = new JLabel("Cancelation Threshold"); panelCancelationThreshold.add(lblCancelationThreshold); final JSpinner spinnerCancelationThreshold = new JSpinner(); panelCancelationThreshold.add(spinnerCancelationThreshold); spinnerCancelationThreshold.setModel( new SpinnerNumberModel(new Float(1.0f), new Float(0.0f), new Float(1.01f), new Float(0.05))); JFormattedTextField tfCancelationThreshold = ((JSpinner.DefaultEditor) spinnerCancelationThreshold .getEditor()).getTextField(); tfCancelationThreshold.setEditable(false); JPanel panelStopAnywhere = new JPanel(); panelTab2.add(panelStopAnywhere); final JCheckBox chckbxStopAnywhere = new JCheckBox("Stop Anywhere?"); panelStopAnywhere.add(chckbxStopAnywhere); panelNearestNeighborCount = new JPanel(); panelNearestNeighborCount.setVisible(false); panelTab2.add(panelNearestNeighborCount); JLabel lblNearestNeighborCount = new JLabel("Nearest Neighbor Count"); panelNearestNeighborCount.add(lblNearestNeighborCount); frmtdtxtfldNearestNeighborCount = new JFormattedTextField(countFormat); panelNearestNeighborCount.add(frmtdtxtfldNearestNeighborCount); frmtdtxtfldNearestNeighborCount.setColumns(3); frmtdtxtfldNearestNeighborCount.setValue((Number) 10); panelMaxLocationRadius = new JPanel(); panelMaxLocationRadius.setVisible(false); panelTab2.add(panelMaxLocationRadius); JLabel lblMaxLocationRadius = new JLabel("Max Location Radius"); panelMaxLocationRadius.add(lblMaxLocationRadius); frmtdtxtfldMaxLocationRadius = new JFormattedTextField(doubleFormat); panelMaxLocationRadius.add(frmtdtxtfldMaxLocationRadius); frmtdtxtfldMaxLocationRadius.setColumns(5); frmtdtxtfldMaxLocationRadius.setValue((Number) 10.0); panelPredationBoxes = new JPanel(); panelTab2.add(panelPredationBoxes); final JCheckBox chckbxUsePredationThreshold = new JCheckBox("Use Predation Threshold"); panelPredationBoxes.add(chckbxUsePredationThreshold); final JCheckBox chckbxPopulationIndependent = new JCheckBox("Population Independent"); chckbxPopulationIndependent.setSelected(true); panelPredationBoxes.add(chckbxPopulationIndependent); chckbxPopulationIndependent.setToolTipText( "Select this to allow predation to be independent of population size. Max predation for 10 agents will be the same as for 50 agents. "); panelPredationStuff = new JPanel(); panelTab2.add(panelPredationStuff); JLabel lblPredationMinimum = new JLabel("Predation Minimum"); panelPredationStuff.add(lblPredationMinimum); frmtdtxtfldPredationMinimum = new JFormattedTextField(doubleFormat); frmtdtxtfldPredationMinimum.setColumns(4); frmtdtxtfldPredationMinimum.setValue((Number) 0.0); panelPredationStuff.add(frmtdtxtfldPredationMinimum); JLabel lblPredationThreshold = new JLabel("Predation Threshold"); panelPredationStuff.add(lblPredationThreshold); final JSpinner spinnerPredationThreshold = new JSpinner(); panelPredationStuff.add(spinnerPredationThreshold); spinnerPredationThreshold.setModel( new SpinnerNumberModel(new Float(1.0f), new Float(0.0f), new Float(1.01f), new Float(0.05))); JFormattedTextField tfPredationThreshold = ((JSpinner.DefaultEditor) spinnerPredationThreshold.getEditor()) .getTextField(); tfPredationThreshold.setEditable(false); JLabel lblMaxEaten = new JLabel("Max Eaten"); panelPredationStuff.add(lblMaxEaten); spinnerMaxEaten = new JSpinner(); spinnerMaxEaten.setToolTipText("The max number eaten per time step."); panelPredationStuff.add(spinnerMaxEaten); spinnerMaxEaten.setModel(new SpinnerNumberModel(new Integer(10), new Integer(0), new Integer(sliderAgent.getValue()), new Integer(1))); JFormattedTextField tfMaxEaten = ((JSpinner.DefaultEditor) spinnerMaxEaten.getEditor()).getTextField(); tfMaxEaten.setEditable(false); panelPredationConstant = new JPanel(); panelTab2.add(panelPredationConstant); JLabel lblPredationConstant = new JLabel("Predation Constant"); panelPredationConstant.add(lblPredationConstant); frmtdtxtfldPredationConstant = new JFormattedTextField(doubleFormat); panelPredationConstant.add(frmtdtxtfldPredationConstant); frmtdtxtfldPredationConstant.setToolTipText("Value should be positive. Recommended values are near 0.001"); frmtdtxtfldPredationConstant.setColumns(4); frmtdtxtfldPredationConstant.setValue((Number) 0.001); panelNonMoversSurvive = new JPanel(); panelTab2.add(panelNonMoversSurvive); final JCheckBox chckbxNonMoversSurvive = new JCheckBox("Non-movers Survive?"); chckbxNonMoversSurvive.setSelected(false); panelNonMoversSurvive.add(chckbxNonMoversSurvive); ////////Tab 3 JPanel panelTab3 = new JPanel(); tabbedPane.addTab("Environment", null, panelTab3, null); panelTab3.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); panelSueurValues = new JPanel(); panelTab3.add(panelSueurValues); panelSueurValues.setLayout(new BoxLayout(panelSueurValues, BoxLayout.Y_AXIS)); JLabel lblSueurValues = new JLabel("Sueur Values"); lblSueurValues.setHorizontalAlignment(SwingConstants.TRAILING); lblSueurValues.setAlignmentX(Component.CENTER_ALIGNMENT); panelSueurValues.add(lblSueurValues); JPanel panelAlpha = new JPanel(); FlowLayout flowLayout = (FlowLayout) panelAlpha.getLayout(); flowLayout.setAlignment(FlowLayout.RIGHT); panelSueurValues.add(panelAlpha); JLabel lblAlpha = new JLabel("alpha"); lblAlpha.setHorizontalAlignment(SwingConstants.CENTER); panelAlpha.add(lblAlpha); final JFormattedTextField frmtdtxtfldAlpha = new JFormattedTextField(doubleFormat); frmtdtxtfldAlpha.setHorizontalAlignment(SwingConstants.TRAILING); lblAlpha.setLabelFor(frmtdtxtfldAlpha); panelAlpha.add(frmtdtxtfldAlpha); frmtdtxtfldAlpha.setColumns(6); frmtdtxtfldAlpha.setValue((Number) 0.006161429); JPanel panelAlphaC = new JPanel(); FlowLayout flowLayout_2 = (FlowLayout) panelAlphaC.getLayout(); flowLayout_2.setAlignment(FlowLayout.RIGHT); panelSueurValues.add(panelAlphaC); JLabel lblAlphaC = new JLabel("alpha c"); panelAlphaC.add(lblAlphaC); final JFormattedTextField frmtdtxtfldAlphaC = new JFormattedTextField(doubleFormat); frmtdtxtfldAlphaC.setHorizontalAlignment(SwingConstants.TRAILING); lblAlphaC.setLabelFor(frmtdtxtfldAlphaC); panelAlphaC.add(frmtdtxtfldAlphaC); frmtdtxtfldAlphaC.setColumns(6); frmtdtxtfldAlphaC.setValue((Number) 0.009); JPanel panelBeta = new JPanel(); FlowLayout flowLayout_1 = (FlowLayout) panelBeta.getLayout(); flowLayout_1.setAlignment(FlowLayout.RIGHT); panelSueurValues.add(panelBeta); JLabel lblBeta = new JLabel("beta"); panelBeta.add(lblBeta); final JFormattedTextField frmtdtxtfldBeta = new JFormattedTextField(doubleFormat); frmtdtxtfldBeta.setHorizontalAlignment(SwingConstants.TRAILING); panelBeta.add(frmtdtxtfldBeta); frmtdtxtfldBeta.setColumns(6); frmtdtxtfldBeta.setValue((Number) 0.013422819); JPanel panelBetaC = new JPanel(); FlowLayout flowLayout_14 = (FlowLayout) panelBetaC.getLayout(); flowLayout_14.setAlignment(FlowLayout.RIGHT); panelSueurValues.add(panelBetaC); JLabel lblBetaC = new JLabel("beta c"); panelBetaC.add(lblBetaC); final JFormattedTextField frmtdtxtfldBetaC = new JFormattedTextField(doubleFormat); frmtdtxtfldBetaC.setHorizontalAlignment(SwingConstants.TRAILING); panelBetaC.add(frmtdtxtfldBetaC); frmtdtxtfldBetaC.setColumns(6); frmtdtxtfldBetaC.setValue((Number) (-0.009)); JPanel panelS = new JPanel(); FlowLayout flowLayout_3 = (FlowLayout) panelS.getLayout(); flowLayout_3.setAlignment(FlowLayout.RIGHT); panelSueurValues.add(panelS); JLabel lblS = new JLabel("S"); panelS.add(lblS); final JFormattedTextField frmtdtxtfldS = new JFormattedTextField(countFormat); frmtdtxtfldS.setHorizontalAlignment(SwingConstants.TRAILING); panelS.add(frmtdtxtfldS); frmtdtxtfldS.setColumns(6); frmtdtxtfldS.setValue((Number) 2); JPanel panelQ = new JPanel(); FlowLayout flowLayout_4 = (FlowLayout) panelQ.getLayout(); flowLayout_4.setAlignment(FlowLayout.RIGHT); panelSueurValues.add(panelQ); JLabel lblQ = new JLabel("q"); panelQ.add(lblQ); final JFormattedTextField frmtdtxtfldQ = new JFormattedTextField(doubleFormat); frmtdtxtfldQ.setHorizontalAlignment(SwingConstants.TRAILING); panelQ.add(frmtdtxtfldQ); frmtdtxtfldQ.setColumns(6); frmtdtxtfldQ.setValue((Number) 2.3); panelGautraisValues = new JPanel(); panelGautraisValues.setVisible(false); panelTab3.add(panelGautraisValues); panelGautraisValues.setLayout(new BoxLayout(panelGautraisValues, BoxLayout.Y_AXIS)); JLabel label = new JLabel("Gautrais Values"); label.setAlignmentX(Component.CENTER_ALIGNMENT); panelGautraisValues.add(label); JPanel panelTauO = new JPanel(); FlowLayout flowLayout_5 = (FlowLayout) panelTauO.getLayout(); flowLayout_5.setAlignment(FlowLayout.RIGHT); panelGautraisValues.add(panelTauO); JLabel lblTauO = new JLabel("tau o"); panelTauO.add(lblTauO); final JFormattedTextField frmtdtxtfldTaoO = new JFormattedTextField(doubleFormat); frmtdtxtfldTaoO.setHorizontalAlignment(SwingConstants.TRAILING); panelTauO.add(frmtdtxtfldTaoO); frmtdtxtfldTaoO.setColumns(4); frmtdtxtfldTaoO.setValue((Number) 1290); JPanel panelGammaC = new JPanel(); FlowLayout flowLayout_6 = (FlowLayout) panelGammaC.getLayout(); flowLayout_6.setAlignment(FlowLayout.RIGHT); panelGautraisValues.add(panelGammaC); JLabel lblGammaC = new JLabel("gamma c"); panelGammaC.add(lblGammaC); final JFormattedTextField frmtdtxtfldGammaC = new JFormattedTextField(doubleFormat); frmtdtxtfldGammaC.setHorizontalAlignment(SwingConstants.TRAILING); panelGammaC.add(frmtdtxtfldGammaC); frmtdtxtfldGammaC.setColumns(4); frmtdtxtfldGammaC.setValue((Number) 2.0); JPanel panelEpsilonC = new JPanel(); FlowLayout flowLayout_7 = (FlowLayout) panelEpsilonC.getLayout(); flowLayout_7.setAlignment(FlowLayout.RIGHT); panelGautraisValues.add(panelEpsilonC); JLabel lblEpsilonC = new JLabel("epsilon c"); panelEpsilonC.add(lblEpsilonC); final JFormattedTextField frmtdtxtfldEpsilonC = new JFormattedTextField(doubleFormat); frmtdtxtfldEpsilonC.setHorizontalAlignment(SwingConstants.TRAILING); panelEpsilonC.add(frmtdtxtfldEpsilonC); frmtdtxtfldEpsilonC.setColumns(4); frmtdtxtfldEpsilonC.setValue((Number) 2.3); JPanel panelAlphaF = new JPanel(); FlowLayout flowLayout_8 = (FlowLayout) panelAlphaF.getLayout(); flowLayout_8.setAlignment(FlowLayout.RIGHT); panelGautraisValues.add(panelAlphaF); JLabel lblAlphaF = new JLabel("alpha f"); panelAlphaF.add(lblAlphaF); final JFormattedTextField frmtdtxtfldAlphaF = new JFormattedTextField(doubleFormat); frmtdtxtfldAlphaF.setHorizontalAlignment(SwingConstants.TRAILING); panelAlphaF.add(frmtdtxtfldAlphaF); frmtdtxtfldAlphaF.setColumns(4); frmtdtxtfldAlphaF.setValue((Number) 162.3); JPanel panelBetaF = new JPanel(); FlowLayout flowLayout_9 = (FlowLayout) panelBetaF.getLayout(); flowLayout_9.setAlignment(FlowLayout.RIGHT); panelGautraisValues.add(panelBetaF); JLabel lblBetaF = new JLabel("beta f"); panelBetaF.add(lblBetaF); final JFormattedTextField frmtdtxtfldBetaF = new JFormattedTextField(doubleFormat); frmtdtxtfldBetaF.setHorizontalAlignment(SwingConstants.TRAILING); panelBetaF.add(frmtdtxtfldBetaF); frmtdtxtfldBetaF.setColumns(4); frmtdtxtfldBetaF.setValue((Number) 75.4); JPanel panelEnvironmentVariables = new JPanel(); panelTab3.add(panelEnvironmentVariables); panelEnvironmentVariables.setLayout(new BoxLayout(panelEnvironmentVariables, BoxLayout.Y_AXIS)); JLabel lblEnvironmentVariables = new JLabel("Environment Variables"); lblEnvironmentVariables.setAlignmentX(Component.CENTER_ALIGNMENT); panelEnvironmentVariables.add(lblEnvironmentVariables); panelAngle = new JPanel(); FlowLayout flowLayout_10 = (FlowLayout) panelAngle.getLayout(); flowLayout_10.setAlignment(FlowLayout.RIGHT); panelEnvironmentVariables.add(panelAngle); JLabel lblAngle = new JLabel("Angle"); panelAngle.add(lblAngle); final JFormattedTextField frmtdtxtfldAngle = new JFormattedTextField(doubleFormat); frmtdtxtfldAngle.setHorizontalAlignment(SwingConstants.TRAILING); frmtdtxtfldAngle.setToolTipText("Angle between destinations"); panelAngle.add(frmtdtxtfldAngle); frmtdtxtfldAngle.setColumns(3); frmtdtxtfldAngle.setValue((Number) 72.00); panelNumberOfDestinations = new JPanel(); FlowLayout flowLayout_13 = (FlowLayout) panelNumberOfDestinations.getLayout(); flowLayout_13.setAlignment(FlowLayout.RIGHT); panelNumberOfDestinations.setVisible(false); panelEnvironmentVariables.add(panelNumberOfDestinations); JLabel lblNumberOfDestinations = new JLabel("Number of Destinations"); panelNumberOfDestinations.add(lblNumberOfDestinations); JFormattedTextField frmtdtxtfldNumberOfDestinations = new JFormattedTextField(countFormat); frmtdtxtfldNumberOfDestinations.setHorizontalAlignment(SwingConstants.TRAILING); panelNumberOfDestinations.add(frmtdtxtfldNumberOfDestinations); frmtdtxtfldNumberOfDestinations.setColumns(3); frmtdtxtfldNumberOfDestinations.setValue((Number) 2); panelDistance = new JPanel(); FlowLayout flowLayout_11 = (FlowLayout) panelDistance.getLayout(); flowLayout_11.setAlignment(FlowLayout.RIGHT); panelEnvironmentVariables.add(panelDistance); JLabel lblDistance = new JLabel("Distance"); panelDistance.add(lblDistance); frmtdtxtfldDistance = new JFormattedTextField(doubleFormat); frmtdtxtfldDistance.setHorizontalAlignment(SwingConstants.TRAILING); frmtdtxtfldDistance.setToolTipText("Distance the destination is from origin (0,0)"); panelDistance.add(frmtdtxtfldDistance); frmtdtxtfldDistance.setColumns(3); frmtdtxtfldDistance.setValue((Number) 150.0); panelPercentage = new JPanel(); FlowLayout flowLayout_12 = (FlowLayout) panelPercentage.getLayout(); flowLayout_12.setAlignment(FlowLayout.RIGHT); panelEnvironmentVariables.add(panelPercentage); JLabel lblPercentage = new JLabel("Percentage"); panelPercentage.add(lblPercentage); frmtdtxtfldPercentage = new JFormattedTextField(doubleFormat); frmtdtxtfldPercentage.setHorizontalAlignment(SwingConstants.TRAILING); frmtdtxtfldPercentage.setToolTipText( "The percentage moving to one of the two destinations ( The other gets 1 - percentage)."); panelPercentage.add(frmtdtxtfldPercentage); frmtdtxtfldPercentage.setColumns(3); frmtdtxtfldPercentage.setValue((Number) 0.500); panelInformedCount = new JPanel(); panelEnvironmentVariables.add(panelInformedCount); JLabel lblInformedCount = new JLabel("Informed Count"); panelInformedCount.add(lblInformedCount); final JFormattedTextField frmtdtxtfldInformedCount = new JFormattedTextField(countFormat); frmtdtxtfldInformedCount.setHorizontalAlignment(SwingConstants.TRAILING); frmtdtxtfldInformedCount.setColumns(3); frmtdtxtfldInformedCount.setToolTipText( "The number of agents moving toward a preferred destination. This number is duplicated on the southern pole as well."); frmtdtxtfldInformedCount.setValue((Number) 4); panelInformedCount.setVisible(false); panelInformedCount.add(frmtdtxtfldInformedCount); JPanel panelStartButtons = new JPanel(); JButton btnStartSimulation = new JButton("Create Simulator Instance"); btnStartSimulation.setToolTipText("Creates a new simulator instance from the settings provided."); btnStartSimulation.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean isReady = true; ErrorPacketContainer errorPacketContainer = new ErrorPacketContainer(); if (jframeErrorMessages != null && jframeErrorMessages.isVisible()) { jframeErrorMessages.dispose(); } frmtdtxtfldRunCount.setBackground(Color.WHITE); frmtdtxtfldSimCount.setBackground(Color.WHITE); frmtdtxtfldMaxTimeSteps.setBackground(Color.WHITE); frmtdtxtfldPredationMinimum.setBackground(Color.WHITE); frmtdtxtfldPredationConstant.setBackground(Color.WHITE); frmtdtxtfldNearestNeighborCount.setBackground(Color.WHITE); frmtdtxtfldMaxLocationRadius.setBackground(Color.WHITE); frmtdtxtfldPercentage.setBackground(Color.WHITE); frmtdtxtfldDistance.setBackground(Color.WHITE); frmtdtxtfldDestinationRadius.setBackground(Color.WHITE); frmtdtxtfldAngle.setBackground(Color.WHITE); frmtdtxtfldInformedCount.setBackground(Color.WHITE); StringBuilder errorMessages = new StringBuilder(); if (((Number) frmtdtxtfldRunCount.getValue()).intValue() <= 0) { errorMessages.append("Run Count must be positive\n"); frmtdtxtfldRunCount.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Run Count must be positive", frmtdtxtfldRunCount, 0); isReady = false; } if (((Number) frmtdtxtfldSimCount.getValue()).intValue() <= 0) { errorMessages.append("Sim Count must be positive\n"); frmtdtxtfldSimCount.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Sim Count must be positive", frmtdtxtfldSimCount, 0); isReady = false; } if (((Number) frmtdtxtfldMaxTimeSteps.getValue()).intValue() <= 0) { errorMessages.append("Max Time Steps must be positive\n"); frmtdtxtfldMaxTimeSteps.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Max Time Steps must be positive", frmtdtxtfldMaxTimeSteps, 0); isReady = false; } if (((Number) frmtdtxtfldPredationMinimum.getValue()).doubleValue() < 0 && chckbxPredationEnable.isSelected()) { errorMessages.append("Predation Minimum must be positive\n"); frmtdtxtfldPredationMinimum.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Predation Minimum must be positive", frmtdtxtfldPredationMinimum, 1); isReady = false; } if (((Number) frmtdtxtfldPredationConstant.getValue()).doubleValue() <= 0 && chckbxPredationEnable.isSelected()) { errorMessages.append("Predation Constant must be positive\n"); frmtdtxtfldPredationConstant.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Predation Constant must be positive", frmtdtxtfldPredationConstant, 1); isReady = false; } if (((Number) frmtdtxtfldNearestNeighborCount.getValue()).intValue() < 0 && panelNearestNeighborCount.isVisible()) { errorMessages.append("Nearest Neighbor Count must be positive\n"); frmtdtxtfldNearestNeighborCount.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Nearest Neighbor Count must be positive", frmtdtxtfldNearestNeighborCount, 1); isReady = false; } if (((Number) frmtdtxtfldMaxLocationRadius.getValue()).doubleValue() < 0 && panelMaxLocationRadius.isVisible()) { errorMessages.append("Max Location Radius must be positive\n"); frmtdtxtfldMaxLocationRadius.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Max Location Radius must be positive", frmtdtxtfldMaxLocationRadius, 1); isReady = false; } if ((((Number) frmtdtxtfldPercentage.getValue()).doubleValue() < 0.0 || ((Number) frmtdtxtfldPercentage.getValue()).doubleValue() > 1.0) && panelPercentage.isVisible()) { errorMessages.append( "Percentage needs to be greater than or equal to 0 and less than or equal to 1\n"); frmtdtxtfldPercentage.setBackground(Color.YELLOW); errorPacketContainer.addPacket( "Percentage needs to be greater than or equal to 0 and less than or equal to 1", frmtdtxtfldPercentage, 2); isReady = false; } if (((Number) frmtdtxtfldDistance.getValue()).doubleValue() <= 0 && frmtdtxtfldDistance.isVisible()) { errorMessages.append("Distance must be positive\n"); frmtdtxtfldDistance.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Distance must be positive", frmtdtxtfldDistance, 2); isReady = false; } if (((Number) frmtdtxtfldDestinationRadius.getValue()).doubleValue() <= 0) { errorMessages.append("Destination Radius must be positive\n"); frmtdtxtfldDestinationRadius.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Destination Radius must be positive", frmtdtxtfldDestinationRadius, 0); isReady = false; } if (((Number) frmtdtxtfldAngle.getValue()).doubleValue() < 0) { errorMessages.append("Angle must be positive or zero\n"); frmtdtxtfldAngle.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Angle must be positive", frmtdtxtfldAngle, 2); isReady = false; } if (((Number) frmtdtxtfldInformedCount.getValue()).intValue() <= 0) { errorMessages.append("Informed Count must be positive\n"); frmtdtxtfldInformedCount.setBackground(Color.YELLOW); errorPacketContainer.addPacket("Informed Count must be positive", frmtdtxtfldInformedCount, 2); isReady = false; } else if (((Number) frmtdtxtfldInformedCount.getValue()).intValue() * 2 > sliderAgent.getValue()) { errorMessages.append("Informed Count should at most be half the count of total agents\n"); frmtdtxtfldInformedCount.setBackground(Color.YELLOW); errorPacketContainer.addPacket( "Informed Count should at most be half the count of total agents", frmtdtxtfldInformedCount, 2); isReady = false; } if (!isReady) { jframeErrorMessages = createJFrameErrorMessages(errorPacketContainer, tabbedPane); jframeErrorMessages.setVisible(true); } else { _simulatorProperties = new Properties(); _simulatorProperties.put("run-count", String.valueOf(frmtdtxtfldRunCount.getValue())); _simulatorProperties.put("simulation-count", String.valueOf(frmtdtxtfldSimCount.getValue())); _simulatorProperties.put("max-simulation-time-steps", String.valueOf(frmtdtxtfldMaxTimeSteps.getValue())); _simulatorProperties.put("random-seed", String.valueOf(1)); // Doesn't change _simulatorProperties.put("individual-count", String.valueOf(sliderAgent.getValue())); _simulatorProperties.put("run-graphical", String.valueOf(chckbxGraphical.isSelected())); _simulatorProperties.put("pre-calculate-probabilities", String.valueOf(false)); // Doesn't change _simulatorProperties.put("use-random-random-seed", String.valueOf(chckbxRandomSeed.isSelected())); _simulatorProperties.put("can-multiple-initiate", String.valueOf(true)); // Doesn't change _simulatorProperties.put("eskridge-results", String.valueOf(chckbxEskridge.isSelected())); _simulatorProperties.put("conflict-results", String.valueOf(chckbxConflict.isSelected())); _simulatorProperties.put("position-results", String.valueOf(chckbxPosition.isSelected())); _simulatorProperties.put("predation-results", String.valueOf(chckbxPredationResults.isSelected())); _simulatorProperties.put("communication-type", String.valueOf(comboBoxCommType.getSelectedItem()).toLowerCase()); _simulatorProperties.put("nearest-neighbor-count", String.valueOf(frmtdtxtfldNearestNeighborCount.getValue())); _simulatorProperties.put("max-location-radius", String.valueOf(frmtdtxtfldMaxLocationRadius.getValue())); _simulatorProperties.put("destination-size-radius", String.valueOf(frmtdtxtfldDestinationRadius.getValue())); _simulatorProperties.put("max-agents-eaten-per-step", String.valueOf(spinnerMaxEaten.getValue())); _simulatorProperties.put("enable-predator", String.valueOf(chckbxPredationEnable.isSelected())); _simulatorProperties.put("predation-probability-minimum", String.valueOf(frmtdtxtfldPredationMinimum.getValue())); _simulatorProperties.put("predation-multiplier", String.valueOf(frmtdtxtfldPredationConstant.getValue())); _simulatorProperties.put("use-predation-threshold", String.valueOf(chckbxUsePredationThreshold.isSelected())); _simulatorProperties.put("predation-threshold", String.valueOf(spinnerPredationThreshold.getValue())); _simulatorProperties.put("predation-by-population", String.valueOf(chckbxPopulationIndependent.isSelected())); _simulatorProperties.put("count-non-movers-as-survivors", String.valueOf(chckbxNonMoversSurvive.isSelected())); _simulatorProperties.put("stop-at-any-destination", String.valueOf(chckbxStopAnywhere.isSelected())); _simulatorProperties.put("adhesion-time-limit", String.valueOf(frmtdtxtfldMaxTimeSteps.getValue())); _simulatorProperties.put("alpha", String.valueOf(frmtdtxtfldAlpha.getValue())); _simulatorProperties.put("alpha-c", String.valueOf(frmtdtxtfldAlphaC.getValue())); _simulatorProperties.put("beta", String.valueOf(frmtdtxtfldBeta.getValue())); _simulatorProperties.put("beta-c", String.valueOf(frmtdtxtfldBetaC.getValue())); _simulatorProperties.put("S", String.valueOf(frmtdtxtfldS.getValue())); _simulatorProperties.put("q", String.valueOf(frmtdtxtfldQ.getValue())); _simulatorProperties.put("lambda", String.valueOf(0.2)); _simulatorProperties.put("tau-o", String.valueOf(frmtdtxtfldTaoO.getValue())); _simulatorProperties.put("gamma-c", String.valueOf(frmtdtxtfldGammaC.getValue())); _simulatorProperties.put("epsilon-c", String.valueOf(frmtdtxtfldEpsilonC.getValue())); _simulatorProperties.put("alpha-f", String.valueOf(frmtdtxtfldAlphaF.getValue())); _simulatorProperties.put("beta-f", String.valueOf(frmtdtxtfldBetaF.getValue())); _simulatorProperties.put("default-conflict-value", String.valueOf(spinnerDefaultConflict.getValue())); _simulatorProperties.put("cancellation-threshold", String.valueOf(spinnerCancelationThreshold.getValue())); StringBuilder sbAgentBuilder = new StringBuilder(); sbAgentBuilder.append("edu.snu.leader.discrete.simulator.Sueur"); sbAgentBuilder.append(comboBoxAgentBuilder.getSelectedItem().toString().replace(" ", "")); sbAgentBuilder.append("AgentBuilder"); _simulatorProperties.put("agent-builder", String.valueOf(sbAgentBuilder.toString())); StringBuilder sbDecisionCalculator = new StringBuilder(); sbDecisionCalculator.append("edu.snu.leader.discrete.simulator."); sbDecisionCalculator.append(comboBoxModel.getSelectedItem()); // sbDecisionCalculator.append(comboBoxDecisionCalculator.getSelectedItem()); sbDecisionCalculator .append(comboBoxDecisionCalculator.getSelectedItem().toString().replace(" ", "")); sbDecisionCalculator.append("DecisionCalculator"); _simulatorProperties.put("decision-calculator", String.valueOf(sbDecisionCalculator.toString())); StringBuilder sbLocationsFile = new StringBuilder(); sbLocationsFile.append("cfg/sim/locations/metric/valid-metric-loc-"); sbLocationsFile.append(String.format("%03d", sliderAgent.getValue())); sbLocationsFile.append("-seed-00001.dat"); _simulatorProperties.put("locations-file", String.valueOf(sbLocationsFile.toString())); //create destination file DestinationBuilder db = new DestinationBuilder(sliderAgent.getValue(), 1L); StringBuilder sbDestinationsFile = new StringBuilder(); sbDestinationsFile.append("cfg/sim/destinations/destinations-"); switch (comboBoxEnvironment.getSelectedItem().toString()) { case ("Minimum"): sbDestinationsFile.append("diffdis-" + sliderAgent.getValue()); sbDestinationsFile.append("-per-" + frmtdtxtfldPercentage.getValue()); sbDestinationsFile.append("-seed-1.dat"); db.generateDifferentDistance(((Number) frmtdtxtfldPercentage.getValue()).doubleValue(), 200, 100, 75); break; case ("Medium"): sbDestinationsFile.append("split-" + sliderAgent.getValue()); sbDestinationsFile.append("-dis-" + frmtdtxtfldDistance.getValue()); sbDestinationsFile.append("-ang-" + String.format("%.2f", ((Number) frmtdtxtfldAngle.getValue()).doubleValue())); sbDestinationsFile.append("-per-" + String.format("%.3f", ((Number) frmtdtxtfldPercentage.getValue()).doubleValue())); sbDestinationsFile.append("-seed-1.dat"); db.generateSplitNorth(((Number) frmtdtxtfldDistance.getValue()).doubleValue(), ((Number) frmtdtxtfldAngle.getValue()).doubleValue(), ((Number) frmtdtxtfldPercentage.getValue()).doubleValue()); break; case ("Maximum"): sbDestinationsFile.append("poles-" + sliderAgent.getValue()); sbDestinationsFile.append("-per-" + frmtdtxtfldPercentage.getValue()); sbDestinationsFile.append("-seed-1.dat"); db.generatePoles(50, 100, ((Number) frmtdtxtfldPercentage.getValue()).doubleValue()); break; case ("Uninformed"): sbDestinationsFile.append("split-poles-" + frmtdtxtfldInformedCount.getValue()); sbDestinationsFile.append("-dis-" + String.format("%.1f", ((Number) frmtdtxtfldDistance.getValue()).doubleValue())); sbDestinationsFile.append("-ang-" + String.format("%.2f", ((Number) frmtdtxtfldAngle.getValue()).doubleValue())); sbDestinationsFile.append("-per-" + String.format("%.3f", ((Number) frmtdtxtfldPercentage.getValue()).doubleValue())); sbDestinationsFile.append("-seed-1.dat"); db.generateSplitPoles(((Number) frmtdtxtfldDistance.getValue()).doubleValue(), ((Number) frmtdtxtfldAngle.getValue()).doubleValue(), ((Number) frmtdtxtfldPercentage.getValue()).doubleValue(), ((Number) frmtdtxtfldInformedCount.getValue()).intValue()); break; default: //Should never happen break; } _simulatorProperties.put("destinations-file", String.valueOf(sbDestinationsFile.toString())); _simulatorProperties.put("live-delay", String.valueOf(15)); //Doesn't change _simulatorProperties.put("results-dir", "results"); //Doesn't change new Thread(new Runnable() { public void run() { try { runSimulation(); } catch (Exception e) { e.printStackTrace(); } } }).start(); } } }); panelStartButtons.add(btnStartSimulation); JButton btnStartSimulationFrom = new JButton("Run Simulation from Properties File"); btnStartSimulationFrom .setToolTipText("Runs the simulator with the values provided in the properties file."); btnStartSimulationFrom.setEnabled(false); panelStartButtons.add(btnStartSimulationFrom); panelTab3.add(panelStartButtons); }
From source file:net.sf.jabref.importer.ImportCustomizationDialog.java
/** * * @param frame//from w w w .ja v a 2s. co m */ public ImportCustomizationDialog(final JabRefFrame frame) { super(frame, Localization.lang("Manage custom imports"), false); ImportTableModel tableModel = new ImportTableModel(); customImporterTable = new JTable(tableModel); TableColumnModel cm = customImporterTable.getColumnModel(); cm.getColumn(0).setPreferredWidth(COL_0_WIDTH); cm.getColumn(1).setPreferredWidth(COL_1_WIDTH); cm.getColumn(2).setPreferredWidth(COL_2_WIDTH); cm.getColumn(3).setPreferredWidth(COL_3_WIDTH); JScrollPane sp = new JScrollPane(customImporterTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); customImporterTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); customImporterTable.setPreferredScrollableViewportSize(getSize()); if (customImporterTable.getRowCount() > 0) { customImporterTable.setRowSelectionInterval(0, 0); } JButton addFromFolderButton = new JButton(Localization.lang("Add from folder")); addFromFolderButton.addActionListener(e -> { CustomImporter importer = new CustomImporter(); importer.setBasePath(FileDialogs.getNewDir(frame, new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), Collections.emptyList(), Localization.lang("Select Classpath of New Importer"), JFileChooser.CUSTOM_DIALOG, false)); String chosenFileStr = null; if (importer.getBasePath() != null) { chosenFileStr = FileDialogs.getNewFile(frame, importer.getFileFromBasePath(), Collections.singletonList(".class"), Localization.lang("Select new ImportFormat subclass"), JFileChooser.CUSTOM_DIALOG, false); } if (chosenFileStr != null) { try { importer.setClassName(pathToClass(importer.getFileFromBasePath(), new File(chosenFileStr))); importer.setName(importer.getInstance().getFormatName()); importer.setCliId(importer.getInstance().getId()); addOrReplaceImporter(importer); customImporterTable.revalidate(); customImporterTable.repaint(); } catch (Exception exc) { JOptionPane.showMessageDialog(frame, Localization.lang("Could not instantiate %0", chosenFileStr)); } catch (NoClassDefFoundError exc) { JOptionPane.showMessageDialog(frame, Localization.lang( "Could not instantiate %0. Have you chosen the correct package path?", chosenFileStr)); } } }); addFromFolderButton .setToolTipText(Localization.lang("Add a (compiled) custom ImportFormat class from a class path.") + "\n" + Localization.lang("The path need not be on the classpath of JabRef.")); JButton addFromJarButton = new JButton(Localization.lang("Add from jar")); addFromJarButton.addActionListener(e -> { String basePath = FileDialogs.getNewFile(frame, new File(Globals.prefs.get(JabRefPreferences.WORKING_DIRECTORY)), Arrays.asList(".zip", ".jar"), Localization.lang("Select a Zip-archive"), JFileChooser.CUSTOM_DIALOG, false); if (basePath != null) { try (ZipFile zipFile = new ZipFile(new File(basePath), ZipFile.OPEN_READ)) { ZipFileChooser zipFileChooser = new ZipFileChooser(this, zipFile); zipFileChooser.setVisible(true); customImporterTable.revalidate(); customImporterTable.repaint(10); } catch (IOException exc) { LOGGER.info("Could not open Zip-archive.", exc); JOptionPane.showMessageDialog(frame, Localization.lang("Could not open %0", basePath) + "\n" + Localization.lang("Have you chosen the correct package path?")); } catch (NoClassDefFoundError exc) { LOGGER.info("Could not instantiate Zip-archive reader.", exc); JOptionPane.showMessageDialog(frame, Localization.lang("Could not instantiate %0", basePath) + "\n" + Localization.lang("Have you chosen the correct package path?")); } } }); addFromJarButton .setToolTipText(Localization.lang("Add a (compiled) custom ImportFormat class from a Zip-archive.") + "\n" + Localization.lang("The Zip-archive need not be on the classpath of JabRef.")); JButton showDescButton = new JButton(Localization.lang("Show description")); showDescButton.addActionListener(e -> { int row = customImporterTable.getSelectedRow(); if (row == -1) { JOptionPane.showMessageDialog(frame, Localization.lang("Please select an importer.")); } else { CustomImporter importer = ((ImportTableModel) customImporterTable.getModel()).getImporter(row); try { ImportFormat importFormat = importer.getInstance(); JOptionPane.showMessageDialog(frame, importFormat.getDescription()); } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException exc) { LOGGER.warn("Could not instantiate importer " + importer.getName(), exc); JOptionPane.showMessageDialog(frame, Localization.lang("Could not instantiate %0 %1", importer.getName() + ":\n", exc.getMessage())); } } }); JButton removeButton = new JButton(Localization.lang("Remove")); removeButton.addActionListener(e -> { int row = customImporterTable.getSelectedRow(); if (row == -1) { JOptionPane.showMessageDialog(frame, Localization.lang("Please select an importer.")); } else { customImporterTable.removeRowSelectionInterval(row, row); Globals.prefs.customImports .remove(((ImportTableModel) customImporterTable.getModel()).getImporter(row)); Globals.IMPORT_FORMAT_READER.resetImportFormats(); customImporterTable.revalidate(); customImporterTable.repaint(); } }); Action closeAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { dispose(); } }; JButton closeButton = new JButton(Localization.lang("Close")); closeButton.addActionListener(closeAction); JButton helpButton = new HelpAction(HelpFile.CUSTOM_IMPORTS).getHelpButton(); // Key bindings: JPanel mainPanel = new JPanel(); ActionMap am = mainPanel.getActionMap(); InputMap im = mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DIALOG), "close"); am.put("close", closeAction); mainPanel.setLayout(new BorderLayout()); mainPanel.add(sp, BorderLayout.CENTER); JPanel buttons = new JPanel(); ButtonBarBuilder bb = new ButtonBarBuilder(buttons); buttons.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); bb.addGlue(); bb.addButton(addFromFolderButton); bb.addButton(addFromJarButton); bb.addButton(showDescButton); bb.addButton(removeButton); bb.addButton(closeButton); bb.addUnrelatedGap(); bb.addButton(helpButton); bb.addGlue(); getContentPane().add(mainPanel, BorderLayout.CENTER); getContentPane().add(buttons, BorderLayout.SOUTH); this.setSize(getSize()); pack(); this.setLocationRelativeTo(frame); new FocusRequester(customImporterTable); }
From source file:be.vds.jtbdive.client.view.core.dive.profile.DiveProfileGraphicDetailPanel.java
private Component createImportButton() { JButton b = new JButton(new AbstractAction(null, UIAgent.getInstance().getIcon(UIAgent.ICON_IMPORT_24)) { private static final long serialVersionUID = 985413615438877711L; @Override/* w w w .ja v a 2 s . c o m*/ public void actionPerformed(ActionEvent e) { JFileChooser ch = new JFileChooser(); ch.setFileFilter(new ExtensionFilter("xls", "Excel File")); int i = ch.showOpenDialog(null); if (i == JFileChooser.APPROVE_OPTION) { DiveProfileExcelParser p = new DiveProfileExcelParser(); try { File f = ch.getSelectedFile(); DiveProfile dp = p.read(f); I18nResourceManager i18n = I18nResourceManager.sharedInstance(); int yes = JOptionPane.showConfirmDialog(DiveProfileGraphicDetailPanel.this, i18n.getString("overwritte.diveprofile.confirm"), i18n.getString("confirmation"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (yes == JOptionPane.YES_OPTION) { currentDive.setDiveProfile(dp); setDiveProfile(dp, currentDive); logBookManagerFacade.setDiveChanged(currentDive); } } catch (IOException e1) { ExceptionDialog.showDialog(e1, DiveProfileGraphicDetailPanel.this); LOGGER.error(e1.getMessage()); } } } }); b.setToolTipText("Import"); return b; }