⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 returnattributesdisplay.java

📁 JAVA开源LDAP浏览器jxplorer的源码!
💻 JAVA
📖 第 1 页 / 共 2 页
字号:

            // Get rid of the scroll pane that holds the table...
			topPanel.remove(scrollPane);

			model = new DefaultTableModel(tableData, tableHeader);

            // For sorting via clicking on table headers...
            sorter = new CBTableSorter(model);

            // Requires a click/shift + click...
            table = new JTable(sorter);
			addMouseListenerToTable();
			sorter.addMouseListenerToHeaderInTable(table);
			scrollPane = new JScrollPane(table);	
			
			topPanel.add(scrollPane);	

			repaint();
		}

	   /**
	    *	Adds a mouse listener to the table.  It is only listening for right
		*	mouse click events.  Kicks off the setUp for the popup menu with the 
		*	co-ordinates of the mouse at the time of the click.
		*/
		public void addMouseListenerToTable()
		{
			table.addMouseListener(new MouseAdapter()
			{
                public void mousePressed(MouseEvent e) { if (!doPopupStuff(e)) super.mousePressed(e); }

                public void mouseReleased(MouseEvent e) { if (!doPopupStuff(e)) super.mouseReleased(e); }

				public boolean doPopupStuff(MouseEvent e)
				{
					if(!e.isPopupTrigger())
                        return false;

                    setUpPopup(e.getX(), e.getY());

                    return true;
				}
			});		
		}

	   /**
	    *	Sets up a popup menu with one menu item 'Go to enty...'.  Because
		*	this is triggered by a right click - this method grabs the row at the
		*	location of the mouse event and ensures that that row is selected (the 
		*	table doesn't do this automatically).  Adds a listener to the menu item
		*	that kicks off the 'goToEntry' work if selected.
		*	@param x the vertical co-ordinate of the mouse click.
		*	@param y the horizontal co-ordinate of the mouse click.
		*/
		public void setUpPopup(int x, int y)
		{
			JPopupMenu pop = new JPopupMenu("Go to");
			final JMenuItem menuItem = new JMenuItem(CBIntText.get("Go to entry..."),
                    new ImageIcon(JXplorer.getProperty("dir.images")+"goto.gif"));
			pop.add(menuItem);

            // If a right click has been performed we can't be sure that row is selected.
			final int selectedRow = table.rowAtPoint(new Point(x, y));

			table.changeSelection(selectedRow, table.getSelectedColumn(), false, false);
						
	        menuItem.addActionListener(new ActionListener()
	        {
	            public void actionPerformed(ActionEvent e)
	            {
	                JMenuItem src = ((JMenuItem)e.getSource());
						
	                if (src == menuItem)
	                    goToEntry(selectedRow);	
	            }
	        });		
			
			pop.show(table, x, y);
		}
		
	   /**
	   	*	Gets the Explore tree, gets the DN from the HashMap (by looking up the true row number via
		*	the table sorter).  Asks the tree to read and expand the DN and flips to the Explore tab.
		*	@param selectedRow the row number that is selected.  This is the look up key for the HashMap.
		*		Prior to looking up the DN in the HashMap - a check is done that the row number is the true
		*		row number and not the row number after a sort.
		*/
		public void goToEntry(int selectedRow)
		{
            // Get the Explore tab tree...
			SmartTree tree = jx.getTree();

            // Get the DN from the HashMap store (get the true row number from the sorter)...
			Object temp = map.get(String.valueOf(sorter.getTrueIndex(selectedRow)));
			tree.collapse();
			tree.readAndExpandDN(new DN(temp.toString()));

            // Flip to the Explore tab...
			jx.getTreeTabPane().setSelectedComponent(jx.getExplorePanel());
		}

	   /**
		* 	The method @print@ must be implemented for @Printable@ interface.
		* 	Parameters are supplied by system.
		*/
		public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException
		{
			Graphics2D g2 = (Graphics2D)g;

            //set default foreground color to black...
			g2.setColor(Color.black);

			//for faster printing, turn off double buffering
			//RepaintManager.currentManager(this).setDoubleBufferingEnabled(false);

			Dimension d = printComponent.getSize();    			//get size of document
			double panelWidth  = d.width;    					//width in pixels
			double panelHeight = d.height;   					//height in pixels
			double pageHeight = pf.getImageableHeight();   		//height of printer page
			double pageWidth  = pf.getImageableWidth();    		//width of printer page
			double scale = pageWidth/panelWidth;
			int totalNumPages = (int)Math.ceil(scale * panelHeight / pageHeight);

			//make sure we don't print empty pages
			if(pageIndex >= totalNumPages)
			{
				return Printable.NO_SUCH_PAGE;
			}

			//shift Graphic to line up with beginning of print-imageable region
			g2.translate(pf.getImageableX(), pf.getImageableY());

			//shift Graphic to line up with beginning of next page to print
			g2.translate(0f, -pageIndex*pageHeight);

			//scale the page so the width fits...
			g2.scale(scale, scale);

			// PRINT IT!
			printComponent.paint(g2);

			return Printable.PAGE_EXISTS;
		}

	   /**
		*  	Starts the print operation.  This is quite expensive, and is kicked off
		*  	in a separate thread.
		*/
		public void print()
		{
			final PrinterJob job = PrinterJob.getPrinterJob();
			job.setPrintable(this);

			// make a local copy of the object to be printed, for use by the print thread
			// below...

			final Component printMe = table;

			Thread worker = new Thread()
			{
				public void run()
				{
					if (job.printDialog())
					{
						try 
						{ 
							// need to make sure that no other thread tries to 
							// run a print job and set printCompnent at the same
							// time...
							synchronized(this)
							{ 
								printComponent = printMe;
								job.print(); 
								printComponent = null;
							}    
						}
						catch (Exception ex) 
						{ 
							log.warning("error printing: " + ex);
						}
					}
				}
			};
			worker.start();	
		}	

	   /**
	    *	Disposes of the dialog.
		*/
		public void close()
		{
			this.setVisible(false);
			this.dispose();
		}

	   /**
	    *	Opens a file selector and saves the contents of the JTable in commar-separated-form
		*	(.csv) to the location the user has selected.
		*/
		public void save()
		{
	        chooser = new JFileChooser(JXplorer.getProperty("csv.homeDir"));
	        
	        chooser.addChoosableFileFilter(new CBFileFilter(new String[] {"csv"},"CSV Files (*.csv)"));
	        
	        int option = chooser.showSaveDialog(this);

            // only do something if user chose 'ok'...
	        if (option == JFileChooser.APPROVE_OPTION)
	        {
	            File readFile = chooser.getSelectedFile();
	            
				if (readFile == null)
				{
	                CBUtility.error(CBIntText.get("Please select a file"));
				}
	            else
	            {
                    // Make sure the files extension is '.csv'...
					readFile = adjustFileName(readFile);
					
					int response = -1;

                    // Ask the user if they want to overwrite an existing file...
					if (readFile.exists())
					{
						response = JOptionPane.showConfirmDialog(this,
                                CBIntText.get("The File ''{0}'' already exists.  Do you want to replace it?", new String[] {readFile.toString()}),
                                CBIntText.get("Overwrite Confirmation"), JOptionPane.YES_NO_OPTION );

						if (response != JOptionPane.YES_OPTION)
							save();
					}

                    // Save the user specified path to dxconfig.txt...
	                JXplorer.setProperty("csv.homeDir", readFile.getParent());
	                doFileWrite(readFile);
	            }                    
	        }						
		}

	   /** 
		*   A quick spot of mucking around to add '.csv' to naked files.
		*	@param file the file to add the extension to.
		*/
	    protected File adjustFileName(File file)
	    {
            // sanity check.
	        if (file == null)
                return null;

            // don't do anything if file already exists...
	        if (file.exists())
                return file;
	        
	        String name = file.getName();

            // ... or if it already has an extension.
	        if (name.indexOf('.') != -1)
                return file;
	        
	        name = name + ".csv";
	        
	        return new File(file.getParentFile(), name);
	    }		

	   /** 
		*   Gets the text from the table, escapes any commars (by placing quotes around text),  then
		*	writes the CSV file to the user specified location.  Closes the file when complete.
		*	@param file the file to save the data to.
		*/
	    protected void doFileWrite(File file)
	    {                           
	        if (file == null)
	            CBUtility.error(CBIntText.get("Unable to write to empty file"), null);

			FileWriter fileWriter = null;
			
            try
            {
                fileWriter = new FileWriter(file);

                // Temp storage for data that is to be written to file...
				StringBuffer buffy = new StringBuffer(0);

                // How many columns in the table...
				int cols = model.getColumnCount();

                // How many rows in the table...
				int rows = model.getRowCount();
				String temp = "";
				
				for (int i = 0; i < rows; i++)
				{
                    // Grabs the text from the table model...
					for (int j = 0; j < cols; j++)
					{
						temp = (model.getValueAt(i, j)).toString();

                        // Escape the value for CSV, then add it to the list...
						buffy.append(escapeForCSV(temp));

                        // Don't add a commar at the end of the row, instead put in a carrage return....
						if(!((j == cols - 1) == true))
							buffy.append(",");
						else
							buffy.append("\n");
						
						temp = "";
					}
				}						

				fileWriter.write(buffy.toString());

				fileWriter.close();		            
				log.warning("Closed CSV file");
				
				chooser.setVisible(false); 
            }
            catch (Exception e)
            {
                log.warning("Error writing CSV file from Return Attributes dialog "+e);
            }
	    }  			
	}

    /**
     * Escapes a value for CSV:
     * 1) any " is replaced with ""
     * 2) trims white space from start and end.
     * 3) the string is surrounded in double quotes.
     * For example (note white space at end),<br>
     * John, "Da Man" Doe <br>
     * becomes<br>
     * "John, ""Da Man"" Doe"
     * @param str the string value to escape.
     * @return the string value escaped.
     */
    private String escapeForCSV(String str)
    {
        if(str == null)
            return str;

        str = str.trim();

        str = str.replaceAll("\"", "\"\"");
        return "\"" + str + "\"";
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -