Replace Text with number in TextField - javafx-2

I have this field in which I insert port number. I would like to convert the string automatically into number:
fieldNport = new TextField();
fieldNport.setPrefSize(180, 24);
fieldNport.setFont(Font.font("Tahoma", 11));
grid.add(fieldNport, 1, 1);
Can you tell how I can do this? I cannot find suitable example in stack overflow.
EDIT:
Maybe this:
fieldNport.textProperty().addListener(new ChangeListener()
{
#Override
public void changed(ObservableValue o, Object oldVal, Object newVal)
{
try
{
int Nport = Integer.parseInt((String) oldVal);
}
catch (NumberFormatException e)
{
}
}
});

Starting with JavaFX 8u40, you can set a TextFormatter object on a text field:
UnaryOperator<Change> filter = change -> {
String text = change.getText();
if (text.matches("[0-9]*")) {
return change;
}
return null;
};
TextFormatter<String> textFormatter = new TextFormatter<>(filter);
fieldNport = new TextField();
fieldNport.setTextFormatter(textFormatter);
This avoids both subclassing and duplicate change events that you will get when you add a change listener to the text property and modify the text in that listener.

You can write something like this :
fieldNPort.text.addListener(new ChangeListener(){
#Override public void changed(ObservableValue o,Object oldVal, Object newVal){
//Some Code
//Here you can use Integer.parseInt methods inside a try/catch
//because parseInt throws Exceptions
}
});
Here are all the things you'd need about properties and Listeners in JavaFX:
http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm
If you have any question, I'll be glad to help.

Maybe this is what you need:
fieldNPort= new TextField()
{
#Override
public void replaceText(int start, int end, String text)
{
if (text.matches("[0-9]*"))
{
super.replaceText(start, end, text);
}
}
#Override
public void replaceSelection(String text)
{
if (text.matches("[0-9]*"))
{
super.replaceSelection(text);
}
}
};
This will restrict the users from entering anything but numbers(you can modify the regex expression to your needs) and then you do not have to worry about Integer.parseInt throwing any exception.

Related

thelinmichael/spotify-web-api-java: How to get value from Async/Sync methods

For instance, I want to obtain the uri of a Spotify track and put it in another method as a String value, however I'm lost on how I'd go about doing that. I tried experimenting with SharedPreferences to get the value but getString method wasn't working. I was just wondering if there's a simpler way to getting say track.getUri (or any) in another method from the Async/Sync method. Any assistance would be greatly appreciated.
The code so far:
private static final String accessToken = "...";
private static final String id = "01iyCAUm8EvOFqVWYJ3dVX";
public static SharedPreferences.Editor editor;
private static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
.setAccessToken(accessToken)
.build();
private static final GetTrackRequest getTrackRequest = spotifyApi.getTrack(id)
// .market(CountryCode.SE)
.build();
public static void getTrack_Sync() {
try {
final Track track = getTrackRequest.execute();
System.out.println("Name: " + track.getName());
} catch (IOException | SpotifyWebApiException | ParseException e) {
System.out.println("Error: " + e.getMessage());
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
public void getTrack_Async() {
try {
final CompletableFuture<Track> trackFuture = getTrackRequest.executeAsync();
// Thread free to do other tasks...
// Example Only. Never block in production code.
final Track track = trackFuture.join();
String uri = track.getUri();
editor = getSharedPreferences("uri", 0).edit();
editor.putString("uri", uri);
editor.commit();
editor.apply();
System.out.println("Name: " + track.getUri());
} catch (CompletionException e) {
System.out.println("Error: " + e.getCause().getMessage());
} catch (CancellationException e) {
System.out.println("Async operation cancelled.");
}
}
public void go() {
getTrack_Async();
// String value = editor.getString("uri", )
}
To get the track you need some kind of information to start with. e.g. I have the spotify trackId and can find the track (synchronously) like this:
public Track getTrack(String trackId) {
return spotifyApi.getTrack(trackId).build().execute();
}
Now the Track object (specifically com.wrapper.spotify.model_objects.specification.Track) provides a lot of information. e.g. the field uri.
So you could do just:
public void run(String trackId) {
Track track = spotifyApi.getTrack(trackId).build().execute();
String uri = track.uri;
// now call something else with the uri?
}
Does that help? Your question was not entirely clear for me.

Changing the font colour of TreeNode in GXT 3

How do I change the font colour of a TreeNode in GXT 3?
I've tried returning SafeHtml from the ValueProvider, but that just seems to call toString() on the SafeHtml object. I've also tried to get hold of the Element in ValueProvider.getValue() but it always returns null.
In GXT 2 we were using a ModelStringProvider and returning HTML, but I can't find anything similar that exists.
Here's some example code I've tried:
tree=new Tree<NavigableModel<Integer>, String>(treeStore, new ValueProvider<NavigableModel<Integer>, String>() {
public String getValue(NavigableModel<Integer> _model) {
TreeNode<NavigableModel<Integer>> treeNode=tree.findNode(_model);
StringBuilder sb=new StringBuilder();
if (!_model.getActive()) {
// All elements return null
XElement elem=tree.getView().getElement(treeNode);
if(elem!=null) {
elem.getStyle().setColor("red");
}
// treeNode.getElement().getStyle().setColor("red");
// treeNode.getTextElement().getStyle().setColor("red");
// sb.appendHtmlConstant("<span class=\"item-deleted\">");
}
sb.append(_model.get("name"));
if (idsCheckBox.getValue()) {
sb.append(" ("+_model.get("id")+")");
}
// if (!_model.getActive()) {
// sb.appendHtmlConstant("</span>");
// }
return(sb.toString());
}
public String getPath() {
return("name");
}
public void setValue(NavigableModel<Integer> object, String value) {
}
});
Figured it out!
I needed to use SafeHtml for the ValueProvider and set the Tree cell to a SafeHtmlCell e.g.
tree=new Tree<NavigableModel<Integer>, SafeHtml>(treeStore, new ValueProvider<NavigableModel<Integer>, SafeHtml>() {
public SafeHtml getValue(NavigableModel<Integer> _model) {
SafeHtmlBuilder sb=new SafeHtmlBuilder();
if(_model==null) return sb.toSafeHtml();
if (!_model.getActive()) {
// My class to make the text red if this model isn't active
sb.appendHtmlConstant("<span class=\"item-deleted\">");
}
sb.appendEscaped((String)_model.get("name"));
if (!_model.getActive()) {
sb.appendHtmlConstant("</span>");
}
return(sb.toSafeHtml());
}
public void setValue(NavigableModel<Integer> object, SafeHtml value) {
}
public String getPath() {
return("name");
}
});
// Set the cell to SafeHtmlCell to use the SafeHtml returned by ValueProvider
tree.setCell(new SafeHtmlCell());
Hopefully this will help someone else.

Cannot capture javafx CheckBoxTableCell CellEditEvent

I have defined a CheckBoc TableColumn as
#FXML private TableColumn<Batch, Boolean> sltd;
And have defined the CellValueFactory & CellFactory
sltd.setCellValueFactory(new PropertyValueFactory<Batch, Boolean>("pr"));
sltd.setCellFactory(CheckBoxTableCell.forTableColumn(sltd));
My problem is i am not able to capture the edit column event for the checkbox. I use the following code:
sltd.setOnEditStart(new EventHandler<TableColumn.CellEditEvent<Batch, Boolean>>() {
#Override
public void handle(TableColumn.CellEditEvent<Batch, Boolean> t) {
//System.out.println("CheckBox clicked.");
}
});
I don't think the check boxes in the CheckBoxTableCell invoke the startEdit(...) method on the table.
The only thing that can happen in an edit is that the boolean property of one of the items in the table changes from true to false, or vice versa. So you can check for this just by listening directly to those boolean properties.
If you want a single listener that will catch changes to any of the properties, you can create an observableList with an "extractor" and register a list change listener with the list. This looks like:
ObservableList<Batch> items = FXCollections.observableArrayList(new Callback<Batch, Observable[]>() {
#Override
public Observable[] call(Batch batch) {
return new Observable[] { batch.prProperty() } ;
}
}
// populate items
table.setItems(items);
items.addListener(new ListChangeListener<Batch>() {
#Override
public void onChanged(Change<? extends Batch> change) {
while (change.hasNext()) {
if (change.wasUpdated()) {
System.out.println("Item at "+change.getFrom()+" changed value");
}
}
}
});

Dependency Property usage in Silverlight

I am just following the code examples of a Beginning SilverLight book and here is part of the code about user controls and Dependeny Property that I have typed from the book into my IDE:
public class CoolDownButtonControl: Control
{
public static readonly DependencyProperty CoolDownSecondsProperty =
DependencyProperty.Register(
"CoolDownSeconds",
typeof(int),
typeof(CoolDownButtonControl),
new PropertyMetadata(
new PropertyChangedCallback(
CoolDownButtonControl.OnCoolDownSecondsPropertyChanged
)
)
);
public int CoolDownSeconds
{
get
{
return (int)GetValue(CoolDownSecondsProperty);
}
set
{
SetValue(CoolDownSecondsProperty, value);
}
}
private static void OnCoolDownSecondsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CoolDownButtonControl cdBuutton = d as CoolDownButtonControl;
cdBuutton.OnCoolDownButtonChange(null);
}
}
The problem is that IDE highlights the line of cdBuutton.OnCoolDownButtonChange(null); complaining about
CoolDownButtonControl does not contain a definition for
OnCoolDownButtonChange
As I am new to this and hoping to learn it from this example I couldn't figure out what is wrong and how to fix it?
You should add that method too, something like this:
protected virtual void OnCoolDownButtonChange(RoutedEventArgs e)
{
}

How to get current used color theme of Visual Studio

I'm creating my own IntelliSense Presenter, since Visual Studio2012 support change theme, so I want my background color of the presenter can be auto-changed when the theme been changed. Is there a way to track the theme changes event, or get the current color theme of the Visual Studio?
Yes, this is possible. I had to solve a similiar issue with one of my extensions...
The current theme is stored in the Windows Registry; so I implemented the following utility class.
public enum VsTheme
{
Unknown = 0,
Light,
Dark,
Blue
}
public class ThemeUtil
{
private static readonly IDictionary<string, VsTheme> Themes = new Dictionary<string, VsTheme>()
{
{ "de3dbbcd-f642-433c-8353-8f1df4370aba", VsTheme.Light },
{ "1ded0138-47ce-435e-84ef-9ec1f439b749", VsTheme.Dark },
{ "a4d6a176-b948-4b29-8c66-53c97a1ed7d0", VsTheme.Blue }
};
public static VsTheme GetCurrentTheme()
{
string themeId = GetThemeId();
if (string.IsNullOrWhiteSpace(themeId) == false)
{
VsTheme theme;
if (Themes.TryGetValue(themeId, out theme))
{
return theme;
}
}
return VsTheme.Unknown;
}
public static string GetThemeId()
{
const string CategoryName = "General";
const string ThemePropertyName = "CurrentTheme";
string keyName = string.Format(#"Software\Microsoft\VisualStudio\11.0\{0}", CategoryName);
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName))
{
if (key != null)
{
return (string)key.GetValue(ThemePropertyName, string.Empty);
}
}
return null;
}
}
Okay; this just helps to figur out the current settings... listening for the theme changed notification is a bit trickier. After your package is loaded, you must obtain an IVsShell instance via the DTE; once you have this object you can utilize the AdviceBroadcastMessages method to subscribe for event notifications. You have to provide an object whose type implements the IVsBroadcastMessageEvents interface...
I don´t want to post the whole implementation, but the following lines might illustrate the key scenario...
class VsBroadcastMessageEvents : IVsBroadcastMessageEvent
{
int IVsBroadcastMessageEvent.OnBroadcastMessage(uint msg, IntPtr wParam, IntPtr lParam)
{
const uint WM_SYSCOLORCHANGE = 0x15;
if (msg == WM_SYSCOLORCHANGE)
{
// obtain current theme from the Registry and update any UI...
}
}
}
Consider implementing IDisposable on that type as well, in order to be able to unsubscribe from the event source, when the package gets unloaded.
This is how I subscribe for event notifications...
class ShellService
{
private readonly IVsShell shell;
private bool advised;
public ShellService(IVsShell shellInstance)
{
this.shell = shellInstance;
}
public void AdviseBroadcastMessages(IVsBroadcastMessageEvents broadcastMessageEvents, out uint cookie)
{
cookie = 0;
try
{
int r = this.shell.AdviseBroadcastMessages(broadcastMessageEvents, out cookie);
this.advised = (r == VSConstants.S_OK);
}
catch (COMException) { }
catch (InvalidComObjectException) { }
}
public void UnadviseBroadcastMessages(uint cookie)
{
...
}
}
Keep the value of the cookie parameter; you´ll need it to successfully unsubscribe.
Hope that helps (-:
Just wanted to put an update just in case anyone else comes along.. #Matze and #Frank are totally right.. However in VS 2015.. they added a easy way to detect the theme change. So you need to include PlatformUI an dyou get a super easy event
using Microsoft.VisualStudio.PlatformUI;
....
//Then you get an event
VSColorTheme.ThemeChanged += VSColorTheme_ThemeChanged;
You should make sure your control is disposable so you can unsubscribe from the event...
BONUS!
It also give you easy access to the colors.. even if the user has changed them from the default .. so you can do stuff like this in when set your colors
var defaultBackground = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowBackgroundColorKey);
var defaultForeground = VSColorTheme.GetThemedColor(EnvironmentColors.ToolWindowTextColorKey);
For VS 2015 this has changed, the solution #Matze has still works but you need to update the GetThemeId() function to check for the version and if it's 14.0 (VS2015) look in a different place in the registry. The way the value is stored has changed also, it's still a string but now contains other values seperated by a '*'. The theme guid is the last value in the list.
if (version == "14.0")
{
string keyName = string.Format(#"Software\Microsoft\VisualStudio\{0}\ApplicationPrivateSettings\Microsoft\VisualStudio", version);
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName))
{
if (key != null)
{
var keyText = (string)key.GetValue("ColorTheme", string.Empty);
if (!string.IsNullOrEmpty(keyText))
{
var keyTextValues = keyText.Split('*');
if (keyTextValues.Length > 2)
{
return keyTextValues[2];
}
}
}
}
return null;
}

Resources