how to bold and change font size of the tableview item or row in javafx? - javafx-2

In my project I'm using javafx and there is a TableView in which there are four columns i.e source, target, score, date and I want either a single word in the column or the whole row to be bold or italic and to change the font size.
public void readtextfile(String data) //data contains the location of the file
{
data1 = FXCollections.observableArrayList();
tab = new Tab("new" + (tabPaneTableview.getTabs().size() + 1));//create a new tab every time loaddatabase() is called
tabPaneTableview.getTabs().add(tab);//tab is added in tabpane
tabPaneTableview.getSelectionModel().select(tab);//the particular tab is selected
tv_new = new TableView<>();
tc_id = new TableColumn<File, Integer>("Id");
tc_source = new TableColumn<File, String>("Source");
tc_target = new TableColumn<File, String>("Target");
tc_score = new TableColumn<File, String>("Score");
// tcUsername=new TableColumn<File,String>("Creation User");
//tcCurrentdate=new TableColumn<File,String>("Date/Time");
tcNote = new TableColumn<File, String>("Note");
tcStatus = new TableColumn<File, String>("Status");
//tcConfirm=new TableColumn<File,String>("Confirm");
//tcLock=new TableColumn<File,String>("Lock");
//tcStatus.getColumns().addAll(tcConfirm,tcLock);
//tcPostag=new TableColumn<ExcelFile,String>("Pos Tag");
tv_new.getColumns().addAll(tc_id, tc_source, tc_target, tc_score, tcNote, tcStatus);
tab.setContent(tv_new);
tv_new.setPrefHeight(250);
tv_new.setRowFactory(new Callback<TableView<File>, TableRow<File>>() {
#Override
public TableRow<File> call(TableView<File> param) {
final TableRow<File> row = new TableRow<File>() {
#Override
protected void updateItem(File row, boolean empty) {
super.updateItem(row, empty);
if (!empty)
styleProperty().bind(Bindings.when(row.selectedProperty())
.then("-fx-font-weight: bold; -fx-font-size: 16;")
.otherwise(""));
}
};
return row;
}
});
public boolean getSelected() {return selected.get();}
public BooleanProperty selectedProperty(){return selected;}
I'm using this code but it doesn't yield the desired result.

Maybe this is not the solution that you are looking for but this might help you.
.table-row-cell:hover {
-fx-border-color: red; /* Vertical Lines*/
-fx-control-inner-background: #c1c1c1;
-fx-border-width: 1;
}
This is a fragment of code that I have provided because I think that changing the text font, just selecting a row is a bit complicated because you have to keep in mind that the text is linked by the column or cell that is focused.
This piece of code has to be included in the css file and from sceneBuilder or from the code you have to include the stylesheet. Good luck.

Related

how change color in datagrid view base on string

[enter image description here][1][enter image description here][2]
how to change specific genre text color with color in datagridview base on text
how to change specific genre text color with color in datagridview base on textcom/K8l1o.png
http://i.stack.imgur.com/DgmkW.png
You can create a color from a name like this :
Color red = Color.FromName("Red");
If Color.FromName cannot find a match, it returns new Color(0,0,0);
Than you can use it in a paint event.
I noticed from your image you are using devexpress gridview, so you can try this code (untested !)
private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
{
GridView gridView = sender as GridView;
if (e.RowHandle >= 0)
{
if (gridView.GetRowCellValue(e.RowHandle, gridView.Columns["color"]) != null)
{
Color color = Color.FromName(gridView.GetRowCellValue(e.RowHandle, gridView.Columns["color"]).ToString());
e.Appearance.BackColor = color;
}
}
}
but i do it like this
private void gridView1_RowCellStyle_1(object sender, RowCellStyleEventArgs e)
{
GridView View = sender as GridView;
if (e.Column.FieldName == "genre")
{
string category = View.GetRowCellDisplayText(e.RowHandle, View.Columns["genre"]);
if (category == "Gymnastics")
{
e.Appearance.ForeColor = Color.Magenta;
}

How do you center align a checkbox cell in a GXT grid column

my code:
List<ColumnConfig<Reminder, ?>> ccs = new LinkedList<ColumnConfig<Reminder, ?>>();
CheckBoxCell cbc = new CheckBoxCell();
ColumnConfig<Reminder,Boolean> applicableColumn = new ColumnConfig<Reminder,Boolean>(properties.applicable(),100,"Applicable");
applicableColumn.setCell(cbc);
applicableColumn.setAlignment(HasHorizontalAlignment.ALIGN_CENTER);
This does not work.
I realize that this answer is probably too late for your purposes, but it may help someone looking for the same question. Here's the code that I use:
private void centerCheckBox(final ColumnConfig<Pet, ?> columnConfig) {
final int leftPadding = (columnConfig.getWidth() - 12) / 2;
final String styles = "padding: 3px 0px 0px " + leftPadding + "px;";
final SafeStyles textStyles = SafeStylesUtils.fromTrustedString(styles);
columnConfig.setColumnTextStyle(textStyles);
}
In addition to calling this method for each checkbox after the ColumnConfig is created I also call it for each checkbox column in the ColumnWidthChange event handler (the event handler is added to the ColumnModel). Here's my code for the column width change handler (note: I add each checkbox column config to a set when I create the ColumnConfig instances):
columnModel.addColumnWidthChangeHandler(new ColumnWidthChangeHandler() {
#Override
public void onColumnWidthChange(final ColumnWidthChangeEvent event) {
final ColumnConfig<Pet, ?> petColumnConfig = columnConfigList.get(event.getIndex());
if (_checkBoxSet.contains(petColumnConfig)) {
centerCheckBox(petColumnConfig);
_grid.getView().refresh(true);
}
}
});

javafx column in tableview auto fit size

afaik The TableView in javafx have 2 column resize policies: CONSTRAINED_RESIZE_POLICY and UNCONSTRAINED_RESIZE_POLICY, but I want columns is resized to fit the content of theirs cells
I think it's a simple problem in other platform (like datagridview in C#) but can not resolve
After 3 years I come back to this problem again, some suggestions are calculating the size of text of data in each cell (it's complicated depending on font size, font family, padding...)
But I realize that when I click on the divider on table header, it's resized fit to content as I want. So I dig into JavaFX source code I finally found resizeColumnToFitContent method in TableViewSkin, but it is protected method, we can resolve by reflection:
import com.sun.javafx.scene.control.skin.TableViewSkin;
import javafx.scene.control.Skin;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class GUIUtils {
private static Method columnToFitMethod;
static {
try {
columnToFitMethod = TableViewSkin.class.getDeclaredMethod("resizeColumnToFitContent", TableColumn.class, int.class);
columnToFitMethod.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public static void autoFitTable(TableView tableView) {
tableView.getItems().addListener(new ListChangeListener<Object>() {
#Override
public void onChanged(Change<?> c) {
for (Object column : tableView.getColumns()) {
try {
columnToFitMethod.invoke(tableView.getSkin(), column, -1);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
});
}
}
Note that we call "tableView.getItems()" so we have to call this function after setItems()
After testing the previous solutions I finally found one that worked for me.
So here is mine (call the method after inserting the data into table):
public static void autoResizeColumns( TableView<?> table )
{
//Set the right policy
table.setColumnResizePolicy( TableView.UNCONSTRAINED_RESIZE_POLICY);
table.getColumns().stream().forEach( (column) ->
{
//Minimal width = columnheader
Text t = new Text( column.getText() );
double max = t.getLayoutBounds().getWidth();
for ( int i = 0; i < table.getItems().size(); i++ )
{
//cell must not be empty
if ( column.getCellData( i ) != null )
{
t = new Text( column.getCellData( i ).toString() );
double calcwidth = t.getLayoutBounds().getWidth();
//remember new max-width
if ( calcwidth > max )
{
max = calcwidth;
}
}
}
//set the new max-widht with some extra space
column.setPrefWidth( max + 10.0d );
} );
}
I think just by overriding a call back function that returns true will solve your problem it will disable the re-sizing of columns and all columns will be re-sized to fit the content of their cells.
Example:
TableView<String[]> table = new TableView<>();
table.setColumnResizePolicy(new Callback<TableView.ResizeFeatures, Boolean>() {
#Override
public Boolean call(ResizeFeatures p) {
return true;
}
});
If you want that only one column fills the remaining width of a table, I have found a pretty straight forward solution, which is short and does not require the hacky reflection solution described above:
DoubleBinding usedWidth = columnA.widthProperty().add(columnB.widthProperty()).add(columnC.widthProperty());
fillingColumn.prefWidthProperty().bind(tableView.widthProperty().subtract(usedWidth));
Or to make it short:
// automatically adjust width of columns depending on their content
configAttributeTreeTable.setColumnResizePolicy((param) -> true );
I have used the other solutions on this question, and it works pretty good. However, the downside of this is when the width of the TableView is greater than the required width of the TableColumns together. I have created a hack to solve this problem, and it works OK:
orderOverview.setColumnResizePolicy((param) -> true );
Platform.runLater(() -> FXUtils.customResize(orderOverview));
where FXUtils.customResize() is created as follows:
public static void customResize(TableView<?> view) {
AtomicDouble width = new AtomicDouble();
view.getColumns().forEach(col -> {
width.addAndGet(col.getWidth());
});
double tableWidth = view.getWidth();
if (tableWidth > width.get()) {
TableColumn<?, ?> col = view.getColumns().get(view.getColumns().size()-1);
col.setPrefWidth(col.getWidth()+(tableWidth-width.get()));
}
}
I hope this could be helpful for other people as well!
This is the way I found :
tableview.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY );
idCol.setMaxWidth( 1f * Integer.MAX_VALUE * 50 ); // 50% width
nameCol.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width
ageCol.setMaxWidth( 1f * Integer.MAX_VALUE * 20 ); // 20% width
This code autoresizes all column widths in relational proportions to the table width,
while it can fix the first column width to a given value when table width is lower than x
// To generalize the columns width proportions in relation to the table width,
// you do not need to put pixel related values, you can use small float numbers if you wish,
// because it's the relative proportion of each columns width what matters here:
final float[] widths = { 1.2f, 2f, 0.8f };// define the relational width of each column
// whether the first column should be fixed
final boolean fixFirstColumm = true;
// fix the first column width when table width is lower than:
final float fixOnTableWidth = 360; //pixels
// calulates sum of widths
float sum = 0;
for (double i : widths) {
sum += i;
}
// calculates the fraction of the first column proportion in relation to the sum of all column proportions
float firstColumnProportion = widths[0] / sum;
// calculate the fitting fix width for the first column, you can change it by your needs, but it jumps to this width
final float firstColumnFixSize = fixOnTableWidth * firstColumnProportion;
// set the width to the columns
for (int i = 0; i < widths.length; i++) {
table.getColumns().get(i).prefWidthProperty().bind(table.widthProperty().multiply((widths[i] / sum)));
// ---------The exact width-------------^-------------^
if (fixFirstColumm)
if (i == 0) {
table.widthProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> arg0, Number oldTableWidth, Number newTableWidth) {
if (newTableWidth.intValue() <= fixOnTableWidth) {
// before you can set new value to column width property, need to unbind the autoresize binding
table.getColumns().get(0).prefWidthProperty().unbind();
table.getColumns().get(0).prefWidthProperty().setValue(firstColumnFixSize);
} else if (!table.getColumns().get(0).prefWidthProperty().isBound()) {
// than readd the autoresize binding if condition table.width > x
table.getColumns().get(0).prefWidthProperty()
.bind(table.widthProperty().multiply(firstColumnProportion));
}
}
});
}
}
advice to put the code in an separated TableAutoresizeModel class, there you can handle further calculations, for example on hiding columns add listener...
#HarleyDavidson 's answer in kotlin
val String.fxWidth: Double
get() = Text(this).layoutBounds.width
// call the method after inserting the data into table
fun <T> TableView<T>.autoResizeColumns() {
columnResizePolicy = TableView.UNCONSTRAINED_RESIZE_POLICY
columns.forEach { column ->
column.setPrefWidth(
(((0 until items.size).mapNotNull {
column.getCellData(it)
}.map {
it.toString().fxWidth
}.toMutableList() + listOf(
column.text.fxWidth
)).maxOrNull() ?: 0.0) + 10.0
)
}
}
This will set the minimum width of columns based on the font and the text, so that the column names wont be cropped.
public static void setDataTableMinColumnWidth(TableView<?> dataTable)
{
for (Node columnHeader : dataTable.lookupAll(".column-header"))
{
var columnString = columnHeader.getId();
if (columnString != null)
{
for (Node columnHeaderLabel : columnHeader.lookupAll(".label"))
{
var tableColumn = dataTable.getColumns()
.stream()
.filter(x -> x.getId()
.equals(columnString))
.findFirst();
if (columnHeaderLabel instanceof Label && tableColumn.isPresent())
{
var label = (Label) columnHeaderLabel;
/* calc text width based on font */
var theText = new Text(label.getText());
theText.setFont(label.getFont());
var width = theText.getBoundsInLocal()
.getWidth();
/*
* add 10px because of paddings/margins for the button
*/
tableColumn.get()
.setMinWidth(width + 10);
}
}
}
}
}
How to use:
dataTable.needsLayoutProperty()
.addListener((obs, o, n) -> setDataTableMinColumnWidth(dataTable));
For the Columns, the id property needs to be set first:
TableColumn<BundImportTask, String> columnTask = new TableColumn<>("My Column");
columnTask.setId("MyColumnId");
columnTask.setCellValueFactory(data -> new SimpleStringProperty(data.getValue()
.fileName()));
I implemented a solution that it's fairly more complicated than the ones that I found here, but that allows a specific column to be resized by double clicking on the header, while still letting the user resize columns manually.
This is achieved by listening to click events on the header of the table (TableHeaderRow). When a double click occurs, the specific column header is found by matching the mouse event X and Y.
Note: to make this work it's necessary that each column has an ID set.
// when skin is loaded (hence css), setup click listener on header to make column fit to content max width on double click
tableView.skinProperty().addListener((a, b, newSkin) -> {
TableHeaderRow headerRow = (TableHeaderRow) tableView.lookup("TableHeaderRow");
NestedTableColumnHeader headers = (NestedTableColumnHeader) (headerRow.getChildren().get(1));
headerRow.setOnMouseClicked(evt -> {
if (evt.getClickCount() != 2 || evt.getButton() != MouseButton.PRIMARY) return;
// find the header column that contains the click
for (TableColumnHeader header : headers.getColumnHeaders()) {
if (header.contains(header.parentToLocal(evt.getX(), evt.getY()))) {
fitColumnWidthToContent(header.getId());
}
}
evt.consume();
});
});
The method that takes care of the resizing is the following:
private void fitColumnWidthToContent (String colId) {
// find column matching id
TableColumn column = null;
for (TableColumn tempCol : tableView.getColumns()) {
if (tempCol.getId().equals(colId)) {
column = tempCol;
break;
}
}
if (column == null) {
throw new IllegalStateException("Column ID doesn't match any actual column");
}
// set default width to column header width
Text text = new Text(column.getText());
double max = text.getLayoutBounds().getWidth();
for (int i = 0; i < tableView.getItems().size(); i++ ) {
if (column.getCellData(i) == null) continue;
text = new Text(column.getCellData(i).toString());
double textWidth = text.getLayoutBounds().getWidth();
if (textWidth > max) {
max = textWidth;
}
}
column.setPrefWidth(max + 12);
}
I hope this can be useful to anyone.
In order to allow also manual resizing, it's necessary to add a bit more code on table initalization:
// listen to width changes in columns and set to pref width (otherwise if for example width changes because of
// user resizing the column, applying the old pref width won't work because it stayed the same)
for (TableColumn col : tableView.getColumns()) {
col.widthProperty().addListener((obs, oldVal, newVal) -> {
col.setPrefWidth(newVal.doubleValue());
});
}
I have implemented a solution for TreeTableView. It is still in evolution but it manifests now promising results. Hereafter a description of the solution.
In the control skin class, I added to the control children the TreeTableView and an invisible VBox. A cell factory provide derived cells to the target TreeTableColumn. The derived cells wrap a Label node which is added or removed to the invisible VBox according to the empty property, and which its prefWidth is set according to the cell width. The cells make use of:
getProperties().put(Properties.DEFER_TO_PARENT_PREF_WIDTH, Boolean.TRUE)
I override the cell's computePrefWidth() method as follow:
#Override
protected double computePrefWidth(double height) {
return Double.max(_box.prefWidth(-1.0), super.computePrefWidth(height) + 24.0);
}
The Vbox width property is bind to the TreeTableColumn's prefWidth. This is required to resize as well the header of the column.
Is worth to note, that at the time being, to simplify the development of a solution, this approach works well with built in sort, order, and resize feature disabled. Ie.
_nameColumn = new TreeTableColumn<>("Name");
_nameColumn.setResizable(false);
_nameColumn.setReorderable(false);
_nameColumn.setSortable(false);
Happy coding
After long research. Best Solution is..
tblPlan.setColumnResizePolicy((param) -> true );
Platform.runLater(() -> customResize(tblPlan));
"Custom Resize"
public void customResize(TableView<?> view) {
AtomicLong width = new AtomicLong();
view.getColumns().forEach(col -> {
width.addAndGet((long) col.getWidth());
});
double tableWidth = view.getWidth();
if (tableWidth > width.get()) {
view.getColumns().forEach(col -> {
col.setPrefWidth(col.getWidth()+((tableWidth-width.get())/view.getColumns().size()));
});
}
}
<TableView fx:id="datalist" layoutX="30.0" layoutY="65.0" prefHeight="400.0" AnchorPane.bottomAnchor="100.0" AnchorPane.leftAnchor="30.0" AnchorPane.rightAnchor="30.0" AnchorPane.topAnchor="100.0">
<columns>
<TableColumn fx:id="number" minWidth="-1.0" prefWidth="-1.0" style="width: auto;" text="number" />
<TableColumn fx:id="id" minWidth="-1.0" prefWidth="-1.0" text="id" />
<TableColumn fx:id="name" minWidth="-1.0" prefWidth="-1.0" text="name" />
<TableColumn fx:id="action" minWidth="-1.0" prefWidth="-1.0" text="todo" />
</columns>
**<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>**
</TableView>

adding an image component to Table cell by overidding `createCell`

I am using LWUIT and showing data with Table, say, flight information!
Instead of writing air companies with text I just like to replace them with icons.
So, I need to override protected Component createCell(Object value, final int row, final int column, boolean editable) method of Table.
This is how I've implemented:
Initializing
imgAln[i]=null;
try {
imgAln[i] = Image.createImage(strPathToImage[i]);
//e.g /uta.png,/somonair.png and so on
lAln[i] = new Label(imgAln[i]);
} catch (IOException e) { }
Creating Table object
Table table = new Table(model) {
protected Component createCell(Object value, final int row,
final int column, boolean editable) {
final Component c = super.createCell(value, row, column, editable);
if (column == 6) {
return lAln[value]; //it does not work here
}
}
};
need help to add Image to table cell!!!
Is there any example??? links are welcome!
The problem in your createCell(...) implementation is that it does not return the super.createCell(...) when the column is not 6. Also your array of labels (lAln) may not be properly created. Try my implementation below, but make sure you store the appropriate image name in the table models' column 0.
This should solve it:
TableModel model = new DefaultTableModel(
new String[]{"Uneditable", "Editable", "CheckBox", "Multiline"},
new Object[][]{
{"/animations.png", "", new Boolean(false), "Multi-line text\nright here"},
{"/buttons.png", "", new Boolean(true), "Further text that\nspans lines"},
{"/dialogs.png", "", new Boolean(true), "No span"},
{"/fonts.png", "", new Boolean(false), "Spanning\nFor\nEvery\nWord"},
});
Table table = new Table(model) {
protected Component createCell(Object value, final int row,
final int column, boolean editable) {
if (row != -1 && column == 0) {
try {
//In my case Column 0 store the resource path names
return new Label(Image.createImage((String)value));
} catch (Exception ex) {
ex.printStackTrace();
}
}
return super.createCell(value, row, column, editable);
}
};
NOTE: If you see the names instead of images in column 0 it means the image path is incorrect, fix it to see the images.
Did you manage to have a look at TableLayoutDemo.java in project LWUITDemo? If i remember it correct, this comes bundled download package LWUIT1.5.zip (or you can always google it).
Let me know if you need more specific help.

Is there an existing PropertyGrid UITypeEditor for type "ChartColorPalette"?

I'm trying to write a simple property grid to allow the users to modify the colours of a Chart. By default, a Chart has a "Palette" property, which is of the enumeration type "ChartColorPalette". If the object which underlies my property grid also has a "Palette" property of the same type, I get the drop-down list of possible values. What I don't get however, is the little stripey images to the left of the value names.
Now, I can write a UITypeEditor derived class and have the "PaintValue" draw little resource bitmaps which I have culled from the screen using "Paint" or somesuch, but this seems rather tedious.
Does anyone know if there is already a type editor for the "ChartColorPalette" enumeration which I can use to get the little bitmaps ?
as it happens, writing the UITypeEditor is not that tricky, and not that much code either.
Firstly I created a type editor that looked like this:
private class ChartColorPaletteEditor : UITypeEditor
{
public override bool GetPaintValueSupported(ITypeDescriptorContext context)
{
return true;
}
public override void PaintValue(PaintValueEventArgs e)
{
String paletteName = e.Value.ToString();
String baseName = this.GetType().Namespace + ".MyChart";
ResourceManager mgr = new ResourceManager(baseName, this.GetType().Assembly);
Bitmap bmp = mgr.GetObject(paletteName) as Bitmap;
if (bmp != null)
{
e.Graphics.DrawImage(bmp, e.Bounds);
bmp.Dispose();
}
}
}
I attached this to my control property in the usual way:
[DefaultValue(typeof(ChartColorPalette), "BrightPastel")]
[Editor(typeof(ChartColorPaletteEditor), typeof(System.Drawing.Design.UITypeEditor))]
[Category("Appearance")]
[Description("The named palette to use when choosing the colour scheme for the chart series lines.")]
public ChartColorPalette Palette { get; set; }
Then I added a small PNG resource for each of the little palette images. I had a derived control "MyChart" which inherited from "Chart" and I added the images to that as resources (making sure to set the "Persistance" property to "Embedded in .resx" to save having to keep the PNG files about). The names of the PNG files matched the names in the ChartColorPalette enumeration.
The only issue was where to get the little 20 x 14 images from. I originally just culled them using Paint.exe but didn't like that, so I wrote some code to generate them for me. That was fairly simple, once I had found the colour values that are used by the Charting control. One subtlety is that, where there are more than 12 colours in a palette, the little bitmap uses every other colour. That code looked like this:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Windows.Forms.DataVisualization.Charting;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
Enum.GetValues(typeof(ChartColorPalette)).OfType<ChartColorPalette>().ToList().ForEach(GeneratePNG);
}
static void GeneratePNG(ChartColorPalette palette)
{
if (palette == ChartColorPalette.None) return;
Color[] colours = palette.GetColors();
if (colours.Length >= 12)
{
colours = new Color[] { colours[0], colours[2], colours[4], colours[6], colours[8], colours[10] };
}
else
{
colours = new Color[] { colours[0], colours[1], colours[2], colours[3], colours[4], colours[5] };
}
using (Bitmap bmp = new Bitmap(20, 14))
{
using (Graphics gr = Graphics.FromImage(bmp))
{
using (SolidBrush b1 = new SolidBrush(colours[0]),
b2 = new SolidBrush(colours[1]),
b3 = new SolidBrush(colours[2]),
b4 = new SolidBrush(colours[3]),
b5 = new SolidBrush(colours[4]),
b6 = new SolidBrush(colours[5]))
{
int height = bmp.Height - 2;
gr.DrawRectangle(Pens.Black, 0, 0, bmp.Width - 1, bmp.Height - 1);
gr.FillRectangle(b1, new Rectangle(1, 1, 3, height));
gr.FillRectangle(b2, new Rectangle(4, 1, 3, height));
gr.FillRectangle(b3, new Rectangle(7, 1, 3, height));
gr.FillRectangle(b4, new Rectangle(10, 1, 3, height));
gr.FillRectangle(b5, new Rectangle(13, 1, 3, height));
gr.FillRectangle(b6, new Rectangle(16, 1, 3, height));
}
}
String path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = Path.Combine(path, #"Visual Studio 2010\Projects\DataVisualization.Charting\Palette Bitmaps");
String filename = palette.ToString() + ".png";
bmp.Save(Path.Combine(path, filename), ImageFormat.Png);
}
}
}
public static class Extensions
{
public static Color[] GetColors(this ChartColorPalette value)
{
switch (value)
{
case ChartColorPalette.Berry:
return GetColors(0x8a2be2, 0xba55d3, 0x4169e1, 0xc71585, 0x0000ff, 0x8a2be2, 0xda70d6, 0x7b68ee, 0xc000c0, 0x0000cd, 0x800080);
case ChartColorPalette.Bright:
return GetColors(0x008000, 0x0000ff, 0x800080, 0x00ff00, 0xff00ff, 0x008080, 0xffff00, 0x808080, 0x00ffff, 0x000080, 0x800000, 0xff0000, 0x808000, 0xc0c0c0, 0xff6347, 0xffe4b5);
case ChartColorPalette.BrightPastel:
return GetColors(0x418cf0, 0xfcb441, 0xe0400a, 0x056492, 0xbfbfbf, 0x1a3b69, 0xffe382, 0x129cdd, 0xca6b4b, 0x005cdb, 0xf3d288, 0x506381, 0xf1b9a8, 0xe0830a, 0x7893be);
case ChartColorPalette.Chocolate:
return GetColors(0xa0522d, 0xd2691e, 0x8b0000, 0xcd853f, 0xa52a2a, 0xf4a460, 0x8b4513, 0xc04000, 0xb22222, 0xb65c3a);
case ChartColorPalette.EarthTones:
return GetColors(0xff8000, 0xb8860b, 0xc04000, 0x6b8e23, 0xcd853f, 0xc0c000, 0x228b22, 0xd2691e, 0x808000, 0x20b2aa, 0xf4a460, 0x00c000, 0x8fbc8b, 0xb22222, 0x8b4513, 0xc00000);
case ChartColorPalette.Excel:
return GetColors(0x9999ff, 0x993366, 0xffffcc, 0xccffff, 0x660066, 0xff8080, 0x0066cc, 0xccccff, 0x000080, 0xff00ff, 0xffff00, 0x00ffff, 0x800080, 0x800000, 0x008080, 0x0000ff);
case ChartColorPalette.Fire:
return GetColors(0xffd700, 0xff0000, 0xff1493, 0xdc143c, 0xff8c00, 0xff00ff, 0xffff00, 0xff4500, 0xc71585, 0xdde221);
case ChartColorPalette.Grayscale:
return GetColors(0xc8c8c8, 0xbdbdbd, 0xb2b2b2, 0xa7a7a7, 0x9c9c9c, 0x919191, 0x868686, 0x7b7b7b, 0x707070, 0x656565, 0x5a5a5a, 0x4f4f4f, 0x444444, 0x393939, 0x2e2e2e, 0x232323);
case ChartColorPalette.Light:
return GetColors(0xe6e6fa, 0xfff0f5, 0xffdab9, 0xfffacd, 0xffe4e1, 0xf0fff0, 0xf0f8ff, 0xf5f5f5, 0xfaebd7, 0xe0ffff);
case ChartColorPalette.Pastel:
return GetColors(0x87ceeb, 0x32cd32, 0xba55d3, 0xf08080, 0x4682b4, 0x9acd32, 0x40e0d0, 0xff69b4, 0xf0e68c, 0xd2b48c, 0x8fbc8b, 0x6495ed, 0xdda0dd, 0x5f9ea0, 0xffdab9, 0xffa07a);
case ChartColorPalette.SeaGreen:
return GetColors(0x2e8b57, 0x66cdaa, 0x4682b4, 0x008b8b, 0x5f9ea0, 0x3cb371, 0x48d1cc, 0xb0c4de, 0xffffff, 0x87ceeb);
case ChartColorPalette.SemiTransparent:
return GetColors(0xff6969, 0x69ff69, 0x6969ff, 0xffff69, 0x69ffff, 0xff69ff, 0xcdb075, 0xffafaf, 0xafffaf, 0xafafff, 0xffffaf, 0xafffff, 0xffafff, 0xe4d5b5, 0xa4b086, 0x819ec1);
case ChartColorPalette.None:
default:
return GetColors(0x000000, 0x000000, 0x000000, 0x000000, 0x000000, 0x000000);
}
}
private static Color[] GetColors(params Int32[] values)
{
return values.Select(value => Color.FromArgb(255, Color.FromArgb(value))).ToArray(); // alpha channel of 255 for fully opaque
}
}
}
Hope this is useful to someone out there...

Resources