List of usage examples for java.awt FontMetrics stringWidth
public int stringWidth(String str)
From source file:org.yccheok.jstock.gui.charting.ChartLayerUI.java
private void drawInformationBox(Graphics2D g2, JXLayer<? extends V> layer) { if (JStock.instance().getJStockOptions() .getYellowInformationBoxOption() == JStockOptions.YellowInformationBoxOption.Hide) { return;/*from www . j a va 2 s .c o m*/ } final Font oldFont = g2.getFont(); final Font paramFont = oldFont; final FontMetrics paramFontMetrics = g2.getFontMetrics(paramFont); final Font valueFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() + 1); final FontMetrics valueFontMetrics = g2.getFontMetrics(valueFont); final Font dateFont = oldFont.deriveFont((float) oldFont.getSize() - 1); final FontMetrics dateFontMetrics = g2.getFontMetrics(dateFont); final List<ChartData> chartDatas = this.chartJDialog.getChartDatas(); List<String> values = new ArrayList<String>(); final ChartData chartData = chartDatas.get(this.mainTraceInfo.getDataIndex()); // Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. // If multiple threads access a format concurrently, it must be synchronized externally. // http://stackoverflow.com/questions/2213410/usage-of-decimalformat-for-the-following-case final DecimalFormat integerFormat = new DecimalFormat("###,###"); // It is common to use OHLC for chat, instead of using PrevPrice. values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.openPrice)); values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.highPrice)); values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.lowPrice)); values.add(org.yccheok.jstock.gui.Utils.stockPriceDecimalFormat(chartData.lastPrice)); values.add(integerFormat.format(chartData.volume)); final List<String> indicatorParams = new ArrayList<String>(); final List<String> indicatorValues = new ArrayList<String>(); final DecimalFormat decimalFormat = new DecimalFormat("0.00"); for (TraceInfo indicatorTraceInfo : this.indicatorTraceInfos) { final int plotIndex = indicatorTraceInfo.getPlotIndex(); final int seriesIndex = indicatorTraceInfo.getSeriesIndex(); final int dataIndex = indicatorTraceInfo.getDataIndex(); final String name = this.getLegendName(plotIndex, seriesIndex); final Number value = this.getValue(plotIndex, seriesIndex, dataIndex); if (name == null || value == null) { continue; } indicatorParams.add(name); indicatorValues.add(decimalFormat.format(value)); } assert (values.size() == params.size()); int index = 0; final int paramValueWidthMargin = 10; final int paramValueHeightMargin = 0; // Slightly larger than dateInfoHeightMargin, as font for indicator is // larger than date's. final int infoIndicatorHeightMargin = 8; int maxInfoWidth = -1; // paramFontMetrics will always "smaller" than valueFontMetrics. int totalInfoHeight = Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()) * values.size() + paramValueHeightMargin * (values.size() - 1); for (String param : params) { final String value = values.get(index++); final int paramStringWidth = paramFontMetrics.stringWidth(param + ":") + paramValueWidthMargin + valueFontMetrics.stringWidth(value); if (maxInfoWidth < paramStringWidth) { maxInfoWidth = paramStringWidth; } } if (indicatorValues.size() > 0) { totalInfoHeight += infoIndicatorHeightMargin; totalInfoHeight += Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()) * indicatorValues.size() + paramValueHeightMargin * (indicatorValues.size() - 1); index = 0; for (String indicatorParam : indicatorParams) { final String indicatorValue = indicatorValues.get(index++); final int paramStringWidth = paramFontMetrics.stringWidth(indicatorParam + ":") + paramValueWidthMargin + valueFontMetrics.stringWidth(indicatorValue); if (maxInfoWidth < paramStringWidth) { maxInfoWidth = paramStringWidth; } } } final Date date = new Date(chartData.timestamp); // Date formats are not synchronized. It is recommended to create separate format instances for each thread. // If multiple threads access a format concurrently, it must be synchronized externally. final SimpleDateFormat simpleDateFormat = this.simpleDataFormatThreadLocal.get(); final String dateString = simpleDateFormat.format(date); final int dateStringWidth = dateFontMetrics.stringWidth(dateString); final int dateStringHeight = dateFontMetrics.getHeight(); // We want to avoid information box from keep changing its width while // user moves along the mouse. This will prevent user from feeling, // information box is flickering, which is uncomfortable to user's eye. final int maxStringWidth = Math.max(dateFontMetrics.stringWidth(longDateString), Math.max(this.maxWidth, Math.max(dateStringWidth, maxInfoWidth))); if (maxStringWidth > this.maxWidth) { this.maxWidth = maxStringWidth; } final int dateInfoHeightMargin = 5; final int maxStringHeight = dateStringHeight + dateInfoHeightMargin + totalInfoHeight; final int padding = 5; final int boxPointMargin = 8; final int width = maxStringWidth + (padding << 1); final int height = maxStringHeight + (padding << 1); /* Get Border Rect Information. */ /* fillRect(1, 1, 1, 1); // O is rect pixel xxx xOx xxx drawRect(0, 0, 2, 2); // O is rect pixel OOO OxO OOO */ final int borderWidth = width + 2; final int borderHeight = height + 2; // On left side of the ball. final double suggestedBorderX = this.mainTraceInfo.getPoint().getX() - borderWidth - boxPointMargin; final double suggestedBorderY = this.mainTraceInfo.getPoint().getY() - (borderHeight >> 1); double bestBorderX = 0; double bestBorderY = 0; if (JStock.instance().getJStockOptions() .getYellowInformationBoxOption() == JStockOptions.YellowInformationBoxOption.Stay) { if (this.mainTraceInfo.getPoint() .getX() > ((int) (this.mainDrawArea.getX() + this.mainDrawArea.getWidth() + 0.5) >> 1)) { bestBorderX = this.mainDrawArea.getX(); bestBorderY = this.mainDrawArea.getY(); } else { bestBorderX = this.mainDrawArea.getX() + this.mainDrawArea.getWidth() - borderWidth; bestBorderY = this.mainDrawArea.getY(); } } else { assert (JStock.instance().getJStockOptions() .getYellowInformationBoxOption() == JStockOptions.YellowInformationBoxOption.Follow); bestBorderX = suggestedBorderX > this.mainDrawArea.getX() ? (suggestedBorderX + borderWidth) < (this.mainDrawArea.getX() + this.mainDrawArea.getWidth()) ? suggestedBorderX : this.mainDrawArea.getX() + this.mainDrawArea.getWidth() - borderWidth - boxPointMargin : this.mainTraceInfo.getPoint().getX() + boxPointMargin; bestBorderY = suggestedBorderY > this.mainDrawArea.getY() ? (suggestedBorderY + borderHeight) < (this.mainDrawArea.getY() + this.mainDrawArea.getHeight()) ? suggestedBorderY : this.mainDrawArea.getY() + this.mainDrawArea.getHeight() - borderHeight - boxPointMargin : this.mainDrawArea.getY() + boxPointMargin; } final double x = bestBorderX + 1; final double y = bestBorderY + 1; final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING); final Composite oldComposite = g2.getComposite(); final Color oldColor = g2.getColor(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(COLOR_BORDER); g2.drawRoundRect((int) (bestBorderX + 0.5), (int) (bestBorderY + 0.5), borderWidth - 1, borderHeight - 1, 15, 15); g2.setColor(COLOR_BACKGROUND); g2.setComposite(Utils.makeComposite(0.75f)); g2.fillRoundRect((int) (x + 0.5), (int) (y + 0.5), width, height, 15, 15); g2.setComposite(oldComposite); g2.setColor(oldColor); int yy = (int) (y + padding + dateFontMetrics.getAscent() + 0.5); g2.setFont(dateFont); g2.setColor(COLOR_BLUE); g2.drawString(dateString, (int) (((width - dateFontMetrics.stringWidth(dateString)) >> 1) + x + 0.5), yy); index = 0; yy += dateFontMetrics.getDescent() + dateInfoHeightMargin + valueFontMetrics.getAscent(); final String CLOSE_STR = GUIBundle.getString("StockHistory_Close"); for (String param : params) { final String value = values.get(index++); g2.setColor(Color.BLACK); if (param.equals(CLOSE_STR)) { // It is common to use OHLC for chat, instead of using PrevPrice. final double changePrice = chartData.lastPrice - chartData.openPrice; if (changePrice > 0.0) { g2.setColor(JStockOptions.DEFAULT_HIGHER_NUMERICAL_VALUE_FOREGROUND_COLOR); } else if (changePrice < 0.0) { g2.setColor(JStockOptions.DEFAULT_LOWER_NUMERICAL_VALUE_FOREGROUND_COLOR); } } g2.setFont(paramFont); g2.drawString(param + ":", (int) (padding + x + 0.5), yy); g2.setFont(valueFont); g2.drawString(value, (int) (width - padding - valueFontMetrics.stringWidth(value) + x + 0.5), yy); // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent() yy += paramValueHeightMargin + valueFontMetrics.getHeight(); } g2.setColor(Color.BLACK); yy -= paramValueHeightMargin; yy += infoIndicatorHeightMargin; index = 0; for (String indicatorParam : indicatorParams) { final String indicatorValue = indicatorValues.get(index++); g2.setFont(paramFont); g2.drawString(indicatorParam + ":", (int) (padding + x + 0.5), yy); g2.setFont(valueFont); g2.drawString(indicatorValue, (int) (width - padding - valueFontMetrics.stringWidth(indicatorValue) + x + 0.5), yy); // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent() yy += paramValueHeightMargin + valueFontMetrics.getHeight(); } g2.setColor(oldColor); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias); g2.setFont(oldFont); }
From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java
private void updateROIInformationBox(Graphics2D g2) { final Font oldFont = g2.getFont(); final Font paramFont = oldFont; final FontMetrics paramFontMetrics = g2.getFontMetrics(paramFont); final Font valueFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() + 1); final FontMetrics valueFontMetrics = g2.getFontMetrics(valueFont); final Font dateFont = oldFont.deriveFont((float) oldFont.getSize() - 1); final FontMetrics dateFontMetrics = g2.getFontMetrics(dateFont); final Activities activities = this.investmentFlowChartJDialog.getROIActivities(this.ROIPointIndex); this.ROIValues.clear(); this.ROIParams.clear(); this.totalROIValue = 0.0; final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace(); for (int i = 0, size = activities.size(); i < size; i++) { final Activity activity = activities.get(i); // Buy, Sell or Dividend only. if (activity.getType() == Activity.Type.Buy) { final double quantity = (Double) activity.get(Activity.Param.Quantity); final StockInfo stockInfo = (StockInfo) activity.get(Activity.Param.StockInfo); this.ROIParams.add(GUIBundle.getString("InvestmentFlowLayerUI_Own") + " " + org.yccheok.jstock.portfolio.Utils.toQuantity(quantity) + " " + stockInfo.symbol); final double amount = convertToPoundIfNecessary(stockInfo.code, quantity * this.investmentFlowChartJDialog.getStockPrice(stockInfo.code)); this.totalROIValue += amount; this.ROIValues.add(org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, amount)); } else if (activity.getType() == Activity.Type.Sell) { final double quantity = (Double) activity.get(Activity.Param.Quantity); final StockInfo stockInfo = (StockInfo) activity.get(Activity.Param.StockInfo); this.ROIParams.add(activity.getType() + " " + org.yccheok.jstock.portfolio.Utils.toQuantity(quantity) + " " + stockInfo.symbol); final double amount = convertToPoundIfNecessary(stockInfo.code, activity.getAmount()); this.totalROIValue += amount; this.ROIValues.add(org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, amount)); } else if (activity.getType() == Activity.Type.Dividend) { final StockInfo stockInfo = (StockInfo) activity.get(Activity.Param.StockInfo); this.ROIParams.add(activity.getType() + " " + stockInfo.symbol); final double amount = activity.getAmount(); this.totalROIValue += amount; this.ROIValues.add(org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, amount)); } else {//from w w w . j a va 2s .co m assert (false); } } final boolean isTotalNeeded = this.ROIParams.size() > 1; final String totalParam = GUIBundle.getString("InvestmentFlowLayerUI_Total_Return"); final String totalValue = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, this.totalROIValue); /* This is the height for "total" information. */ int totalHeight = 0; assert (this.ROIParams.size() == this.ROIValues.size()); int index = 0; final int paramValueWidthMargin = 10; final int paramValueHeightMargin = 0; int maxInfoWidth = -1; // paramFontMetrics will always "smaller" than valueFontMetrics. int totalInfoHeight = Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()) * this.ROIValues.size() + paramValueHeightMargin * (this.ROIValues.size() - 1); for (String param : this.ROIParams) { final String value = this.ROIValues.get(index++); final int paramStringWidth = paramFontMetrics.stringWidth(param + ":") + paramValueWidthMargin + valueFontMetrics.stringWidth(value); if (maxInfoWidth < paramStringWidth) { maxInfoWidth = paramStringWidth; } } if (isTotalNeeded) { final int tmp = paramFontMetrics.stringWidth(totalParam + ":") + paramValueWidthMargin + valueFontMetrics.stringWidth(totalValue); if (maxInfoWidth < tmp) { maxInfoWidth = tmp; } totalHeight = Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight()); } final Date date = activities.getDate().getTime(); final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy"); final String dateString = simpleDateFormat.format(date); final int dateStringWidth = dateFontMetrics.stringWidth(dateString); final int dateStringHeight = dateFontMetrics.getHeight(); final int maxStringWidth = Math.max(dateStringWidth, maxInfoWidth); final int dateInfoHeightMargin = 5; final int infoTotalHeightMargin = 5; final int maxStringHeight = isTotalNeeded ? (dateStringHeight + dateInfoHeightMargin + totalInfoHeight + infoTotalHeightMargin + totalHeight) : (dateStringHeight + dateInfoHeightMargin + totalInfoHeight); // Now, We have a pretty good information on maxStringWidth and maxStringHeight. final int padding = 5; final int boxPointMargin = 8; final int width = maxStringWidth + (padding << 1); final int height = maxStringHeight + (padding << 1); final int borderWidth = width + 2; final int borderHeight = height + 2; // On left side of the ball. final double suggestedBorderX = this.ROIPoint.getX() - borderWidth - boxPointMargin; final double suggestedBorderY = this.ROIPoint.getY() - (borderHeight >> 1); final double bestBorderX = suggestedBorderX > this.drawArea.getX() ? (suggestedBorderX + borderWidth) < (this.drawArea.getX() + this.drawArea.getWidth()) ? suggestedBorderX : this.drawArea.getX() + this.drawArea.getWidth() - borderWidth - boxPointMargin : this.ROIPoint.getX() + boxPointMargin; final double bestBorderY = suggestedBorderY > this.drawArea.getY() ? (suggestedBorderY + borderHeight) < (this.drawArea.getY() + this.drawArea.getHeight()) ? suggestedBorderY : this.drawArea.getY() + this.drawArea.getHeight() - borderHeight - boxPointMargin : this.drawArea.getY() + boxPointMargin; final double x = bestBorderX + 1; final double y = bestBorderY + 1; this.ROIRect.setRect(x, y, width, height); }
From source file:com.projity.contrib.calendar.JXXMonthView.java
/** * Paints a month. It is assumed the calendar, _cal, is already set to the * first day of the month to be painted. * * @param col//from w ww . ja va2 s . c o m * X (column) the calendar is displayed in. * @param row * Y (row) the calendar is displayed in. * @param g * Graphics object. */ private void paintMonth(Graphics g, int col, int row) { String numericDay; int days = _cal.getActualMaximum(Calendar.DAY_OF_MONTH); FontMetrics fm = g.getFontMetrics(); Rectangle clip = g.getClipBounds(); long nextFlaggedDate = -1; int flaggedDateIndex = 0; if (_flaggedDates != null && _flaggedDates.length > 0) { nextFlaggedDate = _flaggedDates[flaggedDateIndex]; } long nextColoredDate = -1; int coloredDateIndex = 0; if (_coloredDates != null && _coloredDates.length > 0) { nextColoredDate = _coloredDates[coloredDateIndex]; } for (int i = 0; i < days; i++) { calculateBoundsForDay(_bounds, _cal, false); if (_bounds.intersects(clip)) { numericDay = _dayOfMonthFormatter.format(_cal.getTime()); // PROJITY_MODIFICATION // // Paint Sunday // if (_cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY // || _cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) { // // paintSundayAndSaturday(g, _bounds.x, _bounds.y, // _bounds.width, _bounds.height); // // g.setColor(getForeground()); // // } // Paint bounding box around today. boolean today = _cal.getTimeInMillis() == _today; // if (_cal.getTimeInMillis() == _today) { // paintTodayBackground(g, _bounds.x, _bounds.y, // _bounds.width, _bounds.height); // // g.setColor(getForeground()); // } // If the appointment date is less than the current // calendar date increment to the next appointment. while (nextFlaggedDate != -1 && nextFlaggedDate < _cal.getTimeInMillis()) { flaggedDateIndex++; if (flaggedDateIndex < _flaggedDates.length) { nextFlaggedDate = _flaggedDates[flaggedDateIndex]; } else { nextFlaggedDate = -1; } } while (nextColoredDate != -1 && nextColoredDate < _cal.getTimeInMillis()) { coloredDateIndex++; if (coloredDateIndex < _coloredDates.length) { nextColoredDate = _coloredDates[coloredDateIndex]; } else { nextColoredDate = -1; } } boolean flagged = nextFlaggedDate != -1 && _cal.getTimeInMillis() == nextFlaggedDate; boolean colored = nextColoredDate != -1 && _cal.getTimeInMillis() == nextColoredDate; drawDay(colored, flagged, today, g, numericDay, _ltr ? _bounds.x + _boxPaddingX + _boxWidth - fm.stringWidth(numericDay) : _bounds.x + _boxPaddingX + _boxWidth - fm.stringWidth(numericDay) - 1, _bounds.y + _boxPaddingY + fm.getAscent()); // Paint bounding box around any date that falls within the // selection. if (isSelectedDate(_cal.getTimeInMillis())) { // Keep track of the rectangle for the currently // selected date so we don't have to recalculate it // later when it becomes unselected. This is only // useful for SINGLE_SELECTION mode. if (_selectionMode == SINGLE_SELECTION) { _dirtyRect.x = _bounds.x; _dirtyRect.y = _bounds.y; _dirtyRect.width = _bounds.width; _dirtyRect.height = _bounds.height; } paintSelectedDayBackground(g, _bounds.x, _bounds.y, _bounds.width, _bounds.height); g.setColor(getForeground()); } // PROJITY_MODIFICATION // g.setColor(defaultColor); // } else { // g.drawString(numericDay, _ltr ? _bounds.x + _boxPaddingX // + _boxWidth - fm.stringWidth(numericDay) // : _bounds.x + _boxPaddingX + _boxWidth // - fm.stringWidth(numericDay) - 1, _bounds.y // + _boxPaddingY + fm.getAscent()); // } // // // Paint numeric day of the month. // if (nextColoredDate != -1 // && _cal.getTimeInMillis() == nextColoredDate) { // Font oldFont = getFont(); // //g.setFont(_derivedFont); // // // //hk // g.setColor(Color.LIGHT_GRAY); // g.fillRect(_bounds.x, _bounds.y, // _bounds.width, _bounds.height); // g.setColor(defaultColor); // // g.drawString(numericDay, _ltr ? _bounds.x + _boxPaddingX // + _boxWidth - fm.stringWidth(numericDay) // : _bounds.x + _boxPaddingX + _boxWidth // - fm.stringWidth(numericDay) - 1, _bounds.y // + _boxPaddingY + fm.getAscent()); // g.setFont(oldFont); // } else { // g.drawString(numericDay, _ltr ? _bounds.x + _boxPaddingX // + _boxWidth - fm.stringWidth(numericDay) // : _bounds.x + _boxPaddingX + _boxWidth // - fm.stringWidth(numericDay) - 1, _bounds.y // + _boxPaddingY + fm.getAscent()); // } // } _cal.add(Calendar.DAY_OF_MONTH, 1); } }
From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java
/** * Adjust all the column width for the data in the column, this may be handles with JDK 1.6 (6.) * @param tableArg the table that should have it's columns adjusted */// w ww. j a v a 2s .c om private void initColumnSizes(final JTable tableArg, final JButton theSaveBtn) throws Exception { TableModel tblModel = tableArg.getModel(); TableColumn column = null; Component comp = null; int headerWidth = 0; int cellWidth = 0; Element uploadDefs = null; if (WorkbenchTask.isCustomizedSchema()) { uploadDefs = XMLHelper.readFileToDOM4J( new File(UIRegistry.getAppDataDir() + File.separator + "specify_workbench_upload_def.xml")); } else { uploadDefs = XMLHelper.readDOMFromConfigDir("specify_workbench_upload_def.xml"); } //UIRegistry.getInstance().hookUpUndoableEditListener(cellEditor); Vector<WorkbenchTemplateMappingItem> wbtmis = new Vector<WorkbenchTemplateMappingItem>(); wbtmis.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems()); Collections.sort(wbtmis); DBTableIdMgr databaseSchema = WorkbenchTask.getDatabaseSchema(); columnMaxWidths = new Integer[tableArg.getColumnCount()]; for (int i = 0; i < wbtmis.size() /*tableArg.getColumnCount()*/; i++) { TableCellRenderer headerRenderer = tableArg.getColumnModel().getColumn(i).getHeaderRenderer(); WorkbenchTemplateMappingItem wbtmi = wbtmis.elementAt(i); // Now go retrieve the data length int fieldWidth = WorkbenchDataItem.getMaxWBCellLength(); DBTableInfo ti = databaseSchema.getInfoById(wbtmi.getSrcTableId()); if (ti != null) { DBFieldInfo fi = ti.getFieldByName(wbtmi.getFieldName()); if (fi != null) { wbtmi.setFieldInfo(fi); //System.out.println(fi.getName()+" "+fi.getLength()+" "+fi.getType()); if (RecordTypeCodeBuilder.getTypeCode(fi) == null && fi.getLength() > 0) { fieldWidth = Math.min(fi.getLength(), WorkbenchDataItem.getMaxWBCellLength()); } } else { log.error("Can't find field with name [" + wbtmi.getFieldName() + "]"); } } else { log.error("Can't find table [" + wbtmi.getSrcTableId() + "]"); } columnMaxWidths[i] = new Integer(fieldWidth); GridCellEditor cellEditor = getCellEditor(wbtmi, fieldWidth, theSaveBtn, uploadDefs); column = tableArg.getColumnModel().getColumn(i); comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0); headerWidth = comp.getPreferredSize().width; comp = tableArg.getDefaultRenderer(tblModel.getColumnClass(i)).getTableCellRendererComponent(tableArg, tblModel.getValueAt(0, i), false, false, 0, i); cellWidth = comp.getPreferredSize().width; //comp.setBackground(Color.WHITE); int maxWidth = headerWidth + 10; TableModel m = tableArg.getModel(); FontMetrics fm = comp.getFontMetrics(comp.getFont()); for (int row = 0; row < tableArg.getModel().getRowCount(); row++) { String text = m.getValueAt(row, i).toString(); maxWidth = Math.max(maxWidth, fm.stringWidth(text) + 10); //log.debug(i+" "+maxWidth); } //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead. //log.debug(Math.max(maxWidth, cellWidth)); //log.debug(Math.min(Math.max(maxWidth, cellWidth), 400)); column.setPreferredWidth(Math.min(Math.max(maxWidth, cellWidth), 400)); column.setCellEditor(cellEditor); } //tableArg.setCellEditor(cellEditor); }
From source file:de.laures.cewolf.jfree.ThermometerPlot.java
/** * Draws the plot on a Java 2D graphics device (such as the screen or a printer). * * @param g2 the graphics device./*from www . j a va 2 s . c om*/ * @param area the area within which the plot should be drawn. * @param anchor the anchor point (<code>null</code> permitted). * @param parentState the state from the parent plot, if there is one. * @param info collects info about the drawing. */ public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { RoundRectangle2D outerStem = new RoundRectangle2D.Double(); RoundRectangle2D innerStem = new RoundRectangle2D.Double(); RoundRectangle2D mercuryStem = new RoundRectangle2D.Double(); Ellipse2D outerBulb = new Ellipse2D.Double(); Ellipse2D innerBulb = new Ellipse2D.Double(); String temp = null; FontMetrics metrics = null; if (info != null) { info.setPlotArea(area); } // adjust for insets... RectangleInsets insets = getInsets(); insets.trim(area); drawBackground(g2, area); // adjust for padding... Rectangle2D interior = (Rectangle2D) area.clone(); this.padding.trim(interior); int midX = (int) (interior.getX() + (interior.getWidth() / 2)); int midY = (int) (interior.getY() + (interior.getHeight() / 2)); int stemTop = (int) (interior.getMinY() + getBulbRadius()); int stemBottom = (int) (interior.getMaxY() - getBulbDiameter()); Rectangle2D dataArea = new Rectangle2D.Double(midX - getColumnRadius(), stemTop, getColumnRadius(), stemBottom - stemTop); outerBulb.setFrame(midX - getBulbRadius(), stemBottom, getBulbDiameter(), getBulbDiameter()); outerStem.setRoundRect(midX - getColumnRadius(), interior.getMinY(), getColumnDiameter(), stemBottom + getBulbDiameter() - stemTop, getColumnDiameter(), getColumnDiameter()); Area outerThermometer = new Area(outerBulb); Area tempArea = new Area(outerStem); outerThermometer.add(tempArea); innerBulb.setFrame(midX - getBulbRadius() + getGap(), stemBottom + getGap(), getBulbDiameter() - getGap() * 2, getBulbDiameter() - getGap() * 2); innerStem.setRoundRect(midX - getColumnRadius() + getGap(), interior.getMinY() + getGap(), getColumnDiameter() - getGap() * 2, stemBottom + getBulbDiameter() - getGap() * 2 - stemTop, getColumnDiameter() - getGap() * 2, getColumnDiameter() - getGap() * 2); Area innerThermometer = new Area(innerBulb); tempArea = new Area(innerStem); innerThermometer.add(tempArea); if ((this.dataset != null) && (this.dataset.getValue() != null)) { double current = this.dataset.getValue().doubleValue(); double ds = this.rangeAxis.valueToJava2D(current, dataArea, RectangleEdge.LEFT); int i = getColumnDiameter() - getGap() * 2; // already calculated int j = getColumnRadius() - getGap(); // already calculated int l = (i / 2); int k = (int) Math.round(ds); if (k < (getGap() + interior.getMinY())) { k = (int) (getGap() + interior.getMinY()); l = getBulbRadius(); } Area mercury = new Area(innerBulb); if (k < (stemBottom + getBulbRadius())) { mercuryStem.setRoundRect(midX - j, k, i, (stemBottom + getBulbRadius()) - k, l, l); tempArea = new Area(mercuryStem); mercury.add(tempArea); } g2.setPaint(getCurrentPaint()); g2.fill(mercury); // draw range indicators... if (this.subrangeIndicatorsVisible) { g2.setStroke(this.subrangeIndicatorStroke); Range range = this.rangeAxis.getRange(); // draw start of normal range double value = this.subrangeInfo[NORMAL][RANGE_LOW]; if (range.contains(value)) { double x = midX + getColumnRadius() + 2; double y = this.rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(x, y, x + 10, y); g2.setPaint(this.subrangePaint[NORMAL]); g2.draw(line); } // draw start of warning range value = this.subrangeInfo[WARNING][RANGE_LOW]; if (range.contains(value)) { double x = midX + getColumnRadius() + 2; double y = this.rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(x, y, x + 10, y); g2.setPaint(this.subrangePaint[WARNING]); g2.draw(line); } // draw start of critical range value = this.subrangeInfo[CRITICAL][RANGE_LOW]; if (range.contains(value)) { double x = midX + getColumnRadius() + 2; double y = this.rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(x, y, x + 10, y); g2.setPaint(this.subrangePaint[CRITICAL]); g2.draw(line); } } // draw the axis... if ((this.rangeAxis != null) && (this.axisLocation != NONE)) { int drawWidth = AXIS_GAP; Rectangle2D drawArea; double cursor = 0; switch (this.axisLocation) { case RIGHT: cursor = midX + getColumnRadius(); drawArea = new Rectangle2D.Double(cursor, stemTop, drawWidth, (stemBottom - stemTop + 1)); this.rangeAxis.draw(g2, cursor, area, drawArea, RectangleEdge.RIGHT, null); break; case LEFT: default: //cursor = midX - COLUMN_RADIUS - AXIS_GAP; cursor = midX - getColumnRadius(); drawArea = new Rectangle2D.Double(cursor, stemTop, drawWidth, (stemBottom - stemTop + 1)); this.rangeAxis.draw(g2, cursor, area, drawArea, RectangleEdge.LEFT, null); break; } } // draw text value on screen g2.setFont(this.valueFont); g2.setPaint(this.valuePaint); metrics = g2.getFontMetrics(); switch (this.valueLocation) { case RIGHT: g2.drawString(this.valueFormat.format(current), midX + getColumnRadius() + getGap(), midY); break; case LEFT: String valueString = this.valueFormat.format(current); int stringWidth = metrics.stringWidth(valueString); g2.drawString(valueString, midX - getColumnRadius() - getGap() - stringWidth, midY); break; case BULB: temp = this.valueFormat.format(current); i = metrics.stringWidth(temp) / 2; g2.drawString(temp, midX - i, stemBottom + getBulbRadius() + getGap()); break; default: } /***/ } g2.setPaint(this.thermometerPaint); g2.setFont(this.valueFont); // draw units indicator metrics = g2.getFontMetrics(); int tickX1 = midX - getColumnRadius() - getGap() * 2 - metrics.stringWidth(UNITS[this.units]); if (tickX1 > area.getMinX()) { g2.drawString(UNITS[this.units], tickX1, (int) (area.getMinY() + 20)); } // draw thermometer outline g2.setStroke(this.thermometerStroke); g2.draw(outerThermometer); g2.draw(innerThermometer); drawOutline(g2, area); }