JavaFX change single style in CSS stylesheet - css

I've created a small text editor window that allows the user to change some basic properties of a text area included within the screen. Two of the options available to change the properties of the textArea are font color and font color fill, which are both handled by separate color pickers.
I ran into an issue when testing these buttons using the setStyle method that only one property could be saved at a time. Example, if text color was set to BLUE, and afterwards fill color was set to YELLOW, text color would not remain blue, but instead revert back to its default defined in the stylesheet (black).
To fix this problem, I have created the following method;
private void updateTheSyle()
{
this.textArea.setStyle("-fx-control-inner-background: " + toRgbString(this.colorPickerFill.getValue()) +
"; -fx-text-fill: " + toRgbString(this.colorPickerFont.getValue()) + ";");
}
The toRgbString() method is also called, this is simply passing the user input from the color picker into a string such that the setStyle method can pass the correct parameters to the stylesheet.
This solution does work, as it enables me to change both the fill and the font color without reverting back to default upon selection. However, my program includes more than just fill and font color, which will contribute to a far longer setStyle statement as these options are added.
TLDR: Is there a way to edit a single style included in a CSS stylesheet without affecting the other styles in a given class?

For your first question (longer setStyle statement), If we take into account that the style is defined by a String, and it takes a whole set of details to provide for a single Style, so why not use a List<String> :
List<String> example = new ArrayList<>();
String style = "";
//For example if you use 2 textField to get the (value) and (type):
example.add("-fx-"+textFieldType+":"+textFieldValue + "; ");
//To gather all the properties in a single string
for(String property: example){
style += example;
}
yourNode.setStyle(style);
I do not know if there is a better approach but it works, good luck !
Edit :
I think this tip answers your second question:
private void Update(String type,String newValue){
for(int i = 0; i < example.size(); i++){
if(example.get(i).contains(type)){
example.set(i, "-fx-"+type+":"+newValue + "; ");
//Here you add a (break;) to not alter the other similar styles !
}
}
//Here you use a loop to update the new elements changed
}
I hope this will help you solve your problem !

Related

Pulling a style from a TinyMCE selection

I'm trying to implement a TinyMCE button that will apply the style of the selection to the entire box. I'm having trouble, though, reading the style of the selection when the selection is buried in a span in a span in a paragraph. Let's consider 'color' for example. Below I have a box with some text and I've selected "here" in the paragraph and made it red.
The HTML for the paragraph is now:
The code behind my button to apply the style of the selection to the box is
var selected_color = $(ed.selection.getNode()).css('color');
console.log("color pulled is ", selected_color);
$(ed.bodyElement).css('color', selected_color);
It doesn't work because the color pulled is black, not red, so the third line just re-applies the black that's already there. (If I replace selected_color in the third line with 'blue' everything goes blue.) So the problem is pulling the color of the current selection.
Does anyone know how I can do this reliably, no matter how buried the selection is?
Thanks for any help.
I also noticed somewhat a strange behavior up and there, with selections of nested span's and div's, but honestly i'm not able to recognize if this is a bug of TinyMCE, a browser issue or a combination of both (most probably).
So, waiting for some more information from you (maybe also your plugin code) in the meanwhile i realized two proposal to achieve what you want: the first plugin behaves like the format painter in word, the second is simply applying the current detected foreground color to the whole paragraph.
As you move throug the editor with the keyboard or mouse, you will see the current detected foreground color highlighted and applied as background to the second plugin button.
Key point here are two functions to get the styles back from the cursor position:
function findStyle(el, attr) {
var styles, style, color;
try {
styles = $(el).attr('style');
if(typeof styles !== typeof undefined && styles !== false) {
styles.split(";").forEach(function(e) {
style = e.split(":");
if($.trim(style[0]) === attr) {
color = $(el).css(attr);
}
});
}
} catch (err) {}
return color;
}
function findForeColor(node) {
var $el = $(node), color;
while ($el.prop("tagName").toUpperCase() != "BODY") {
color = findStyle($el, "color");
if (color) break;
$el = $el.parent();
}
return color;
}
The try...catch block is needed to avoid some occasional errors when a selected text is restyled. If you look at the TinyMCE sorce code you will notice a plenty of timing events, this is a unavoidable and common practice when dealing with styles and css, even more with user interaction. There was a great job done by the authors of TinyMCE to make the editor cross-browser.
You can try out the first plugin in the Fiddle below. The second plugin is simpler as the first one. lastForeColor is determined in ed.on('NodeChange'), so the code in button click is very easy.
tinymce.PluginManager.add('example2', function(ed, url) {
// Add a button that opens a window
ed.addButton('example2', {
text: '',
icon: "apply-forecolor",
onclick: function() {
if(lastForeColor) {
var applyColor = lastForeColor;
ed.execCommand('SelectAll');
ed.fire('SelectionChange');
ed.execCommand('forecolor', false, applyColor);
ed.selection.collapse(false);
ed.fire('SelectionChange');
}
return false;
}
});
});
Moreover: i think there is a potential issue with your piece of code here:
$(ed.bodyElement).css('color', selected_color);
i guess the style should be applied in a different way, so in my example i'm using standard TinyMCE commands to apply the foreground color to all, as i wasn't able to exactly convert your screenshot to code. Please share your thoughts in a comment.
Fiddle with both plugins: https://jsfiddle.net/ufp0Lvow/
deblocker,
Amazing work! Thank you!
Your jsfiddle did the trick. I replaced the HTML with what was in my example and changed the selector in tinymce.init from a textarea to a div and it pulls the color out perfectly from my example. The modified jsfiddle is at https://jsfiddle.net/79r3vkyq/3/ . I'll be studying and learning from your code for a long time.
Regarding your question about
$(ed.bodyElement).css('color', selected_color);
the divs I attach tinymce to all have ids and the one the editor is currently attached to is reported in ed.bodyElement. I haven't had any trouble using this but I have no problem using your
ed.execCommand('SelectAll');
ed.fire('SelectionChange');
ed.execCommand('forecolor', false, applyColor);
Thanks again! Great job!

Tinymce4 Remove background-color from text with colorpicker

When the user marks a text, he can define a backgroundcolor with the colorpicker (textcolor.plugin).
Once saved he can change the background-color but not get rid of it.
background-color:white is no solution as the bodycolor can be RGB or even a picture.
How is the colorpicker to configure to remove the style-tag or at least insert a background-color:none?
Found a solution changing the plugin (textcolor). If there is a better way please be free to post it.
I added additional colors to the colorpicker. The Color #FFFFFe (near White) i marked as NO COLOR and changed the plugin as shown.
function onPanelClick(e) {
var buttonCtrl = this.parent(), value;
if ((value = e.target.getAttribute('data-mce-color'))) {
buttonCtrl.hidePanel();
value = '#' + value;
buttonCtrl.color(value);
if (value == '#FFFFFe') { //Changing the value to -1 causes deletion :-)
value = -1;
}
editor.execCommand(buttonCtrl.settings.selectcmd, false, value);
}
}
Researched a bit more since the given answer did not work in my version 4.5.0 of tinymce.
The textcolor plugin uses 'editor.formatter.remove(...)' to remove text color or background color upon selecting 'x' in the last option of the color palette for 'no color'.
While that function is used elsewhere successfully in tinymce (e.g. when removing italics from text), in the context of the textcolor plugin it does not remove color formatting.
Solution:
Replace the following in the textcolor's plugin.js:
editor.formatter.remove(format, {value: null}, null, true);
with:
editor.dom.removeAllAttribs(editor.selection.getNode());
...or in the minified version plugin.min.js:
a.formatter.remove(b,{value:null},null,!0),
with:
a.dom.removeAllAttribs(a.selection.getNode()),
...and things start working as intended.

smartgwt button cannot override skin_styles.css

I want to add red background and white color for titleStyle for ibutton in smartgwt. I cannot override skin_styles.css. How to override skin_styles for button in smartgwt? Simple addStyleName() or setPrimaryStyleName does not work. Have somebody tried it?setBase Style also.
It seems you have issues with skinning and style, If you want to add a style to a widget(your previous post) you can use some sort of code:
String newStyle;
String actualStyle= o.getStyleName();
if(actualStyle!= null){
newStyle= actualStyle+ " " + styleNameYouWant;
}else{
newStyle= styleNameYouWant;
}
o.setStyleName(newStyle);

Resetting Qt Style Sheet

I've managed to style my QLineEdit to something like this:
alt text http://www.kimag.es/share/54278758.png
void Utilities::setFormErrorStyle(QLineEdit *lineEdit)
{
lineEdit->setStyleSheet(
"background-color: #FF8A8A;"
"background-image: url(:/resources/warning.png);"
"background-position: right center;"
"background-repeat: no-repeat;"
"");
}
I called the function using
Utilities *util = new Utilities;
util->setFormErrorStyle(lineNoStaf);
The flow should be something like this:
User open form
User fill data
User submit data
Got error
Use setFormErrorStyle()
User edit the text in the QLineEdit and the style disappear
This function should be reusable over and over again, but how can I connect QLineEdit signal such as textChanged() to a function in other class that will reset the Style Sheet and then disconnect the signal so that it won't be running continuously every time the text changed ?
Qt also allows dynamic properties in its stylesheet, that means you don't need to code your own class for every widget type in your form.
From http://qt-project.org/doc/qt-4.8/stylesheet-examples.html
Customizing Using Dynamic Properties
There are many situations where we need to present a form that has mandatory fields. To indicate to the user that the field is mandatory, one effective (albeit esthetically dubious) solution is to use yellow as the background color for those fields. It turns out this is very easy to implement using Qt Style Sheets. First, we would use the following application-wide style sheet:
*[mandatoryField="true"] { background-color: yellow }
This means that every widget whose mandatoryField Qt property is set to true would have a yellow background.
Then, for each mandatory field widget, we would simply create a mandatoryField property on the fly and set it to true. For example:
QLineEdit *nameEdit = new QLineEdit(this);
nameEdit->setProperty("mandatoryField", true);
QLineEdit *emailEdit = new QLineEdit(this);
emailEdit->setProperty("mandatoryField", true);
QSpinBox *ageSpinBox = new QSpinBox(this);
ageSpinBox->setProperty("mandatoryField", true);
Works also in Qt 4.3!
Allright, this is not compile but should work in principle, you should be able to change the look by calling editWidget->setProperty('isError',true) or editWidget->setError(false)
class ErrorTextEdit : QLineEdit
{
Q_OBJECT
QPROPERTY(bool isError, READ isError, WRITE setError);
public:
ErrorTextEdit(QWidget* parent) : QLineEdit(parent), m_isError(false)
{
m_styleSheet = "" // see below
setStyleSheet(m_styleSheet);
}
void setError(bool val)
{
if (val != m_isError)
{
m_isError = val;
setStyleSheet(m_styleSheet);
}
}
bool isError() {return m_isError;}
private:
QString m_styleSheet;
bool m_isError;
}
for the stylesheet
ErrorTextEdit[isError="false"]
{
optional ...
Style for textedit that is NOT an error
}
ErrorTextEdit[isError="true"]
{
background-color: #FF8A8A;
background-image: url(:/resources/warning.png);
background-position: right center;
background-repeat: no-repeat;
}
the term
[<property>="<value>"]
restricts the application of the stylesheet to instances of the class whose <property> has the appropriate <value> the only caveat is that the style is not changed when the property changes its' value, so the stylesheet has to be reapplied for the look of the widget to actually change, see Stylesheet Documentation -> Property Selector
This construction moves the stylesheet into the widget that uses it and makes switch internal to the widget, the widget changes in accordance to its state.
In general you have a couple of ways to handle invalid inputs in your form
a) observe every change and update the style appropriately, you should be able to use QValidator for that too, but that is a separate topic, using QValidator you will probably be able to completely internalize the state of a single QTextEdit and not have to deal with its validity from the outside
b) Do it in the submit loop that you have described above, whenever the user clicks on submit change the state of the correct and incorrect fields
it all depends the structure of your app and the view
See, the other idea is you need to override the paint evet of line edit and then set the background image and color.
here the implimentation is presetn here button, follow up the same to your line edit

In a QTableWidget, changing the text color of the selected row

I'm using a QTableWidget to display several rows. Some of these rows should reflect an error and their text color is changed :
Rows reflecting that there is no error are displayed with a default color (black text on white background on my computer).
Rows reflecting that there is an error are displayed with a red text color (which is red text on white background on my computer).
This is all fine as long as there is no selection. As soon as a row is selected, no matter of the unselected text color, the text color becomes always white (on my computer) over a blue background.
This is something I would like to change to get the following :
When a row is selected, if the row is reflecting there is no error, I would like it to be displayed with white text on blue background (default behavior).
If the row is reflecting an error and is selected, I would like it to be displayed with red text on blue background.
So far I have only been able to change the selection color for the whole QTableWidget, which is not what I want !
Answering myself, here is what I ended up doing : a delegate.
This delegate will check the foreground color role of the item. If this foreground color is not the default WindowText color of the palette, that means a specific color is set and this specific color is used for the highlighted text color.
I'm not sure if this is very robust, but at least it is working fine on Windows.
class MyItemDelegate: public QItemDelegate
{
public:
MyItemDelegate(QObject* pParent = 0) : QItemDelegate(pParent)
{
}
void paint(QPainter* pPainter, const QStyleOptionViewItem& rOption, const QModelIndex& rIndex) const
{
QStyleOptionViewItem ViewOption(rOption);
QColor ItemForegroundColor = rIndex.data(Qt::ForegroundRole).value<QColor>();
if (ItemForegroundColor.isValid())
{
if (ItemForegroundColor != rOption.palette.color(QPalette::WindowText))
{
ViewOption.palette.setColor(QPalette::HighlightedText, ItemForegroundColor);
}
}
QItemDelegate::paint(pPainter, ViewOption, rIndex);
}
};
Here is how to use it :
QTableWidget* pTable = new QTableWidget(...);
pTable->setItemDelegate(new MyItemDelegate(this));
What you'll want to do is connect the selectionChanged() signal emitted by the QTableWidget's QItemSelectionModel to a slot, say OnTableSelectionChanged(). In your slot, you could then use QStyleSheets to set the selection colours as follows:
if (noError)
{
pTable->setStyleSheet("QTableView {selection-background-color: #000000; selection-color: #FFFFFF;}");
}
else
{
pTable->setStyleSheet("QTableView {selection-background-color: #FF0000; selection-color: #0000FF;}");
}
It looks ok, but you might want to look at the documentation of QStyleOption it can tell you wether the item drawn is selected or not, you don't have to look at the draw color to do that. I would probably give the model class a user role that returns whether the data is valid or not and then make the color decision based on that. I.e. rIndex.data(ValidRole) would return wether the data at this index is valid or not.
I don't know if you tried overriding data for the BackgroundRole and returning a custom color, Qt might do the right thing if you change the color there
You could, of course, inherit from the table widget and override the paint event, but I don't think that is what you want to do.
Instead, should use the QAbstractItemDelegate functionality. You could either create one to always be used for error rows, and set the error rows to use that delegate, or make a general one that knows how to draw both types of rows. The second method is what I would recommend. Then, your delegate draws the rows appropriately, even for the selected row.
You could use e.g. a proxy model for this where you return a different color if you have an error for the specific modelindex;
QVariant MySortFilterProxyModel::data(const QModelIndex & index, int role = Qt::DisplayRole) {
// assuming error state and modelindex row match
if (role==Qt::BackgroundRole)
return Qt::red;
}

Resources