How to auto-scroll to the end in WebView? - javafx-2

I've problem with Scrollbar in WebView. I want to when the web view loaded, the srollbar auto scroll to the end of web view.
How can I do it?
This is my sample
package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.ScrollBar;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Set;
public class Controller implements Initializable {
#FXML
WebView webView;
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
loadWebView();
}
private void loadWebView() {
webView.setStyle("-fx-background-color: #cccccc; -fx-border-color: #00a7c8");
StringBuilder html= new StringBuilder().append("<html><body>");
for (int i=0; i<100; i++) {
html.append("<h1>" + i + ". AAAAAAAAAAAA</h1></br>");
}
html.append("</body></html>");
Set<Node> nodes = webView.lookupAll(".scroll-bar");
for (Node node : nodes) {
if (ScrollBar.class.isInstance(node)) {
System.out.println("Scrollbar here!!!");
ScrollBar scroll = (ScrollBar) node;
scroll.setValue(scroll.getMax());
}
}
WebEngine webEngine = webView.getEngine();
webEngine.loadContent(html.toString());
}
}
Thanks 4 your reading

From https://forums.oracle.com/message/11243184#11243184 :
package sample;
import com.sun.javafx.scene.control.skin.ScrollBarSkin;
import com.sun.webpane.sg.theme.ScrollBarThemeImpl;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ListChangeListener;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.TextArea;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Set;
public class Controller implements Initializable {
#FXML
WebView webView;
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
loadWebView();
}
private void loadWebView() {
webView.setStyle("-fx-background-color: #cccccc; -fx-border-color: #00a7c8");
StringBuilder html= new StringBuilder().append("<html>");
html.append("<head>");
html.append(" <script language=\"javascript\" type=\"text/javascript\">");
html.append(" function toBottom(){");
html.append(" window.scrollTo(0, document.body.scrollHeight);");
html.append(" }");
html.append(" </script>");
html.append("</head>");
html.append("<body onload='toBottom()'>");
for (int i=0; i<100; i++) {
html.append("<h1>" + i + ". AAAAAAAAAAAA</h1></br>");
}
html.append("</body></html>");
WebEngine webEngine = webView.getEngine();
webEngine.loadContent(html.toString());
}
}

Simply execute this script after your loadContent call:
webEngine.executeScript("window.scrollTo(0, document.body.scrollHeight);");

You have to wait until the Worker has finished to then proceed tp scroll down.
webView.getEngine().loadContent("<p>my text</p>");
webView.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue<? extends Worker.State> observable, Worker.State oldValue, Worker.State newValue) {
if (newValue == Worker.State.SUCCEEDED)
webView.getEngine().executeScript("window.scrollTo(0, document.body.scrollHeight);");
}
});

Related

save last position of videoView saved by sharedprefrence and start in last position (android studio)

save last position of videoView saved by sharedprefrence and start in last position (android studio)
hello I serch for my problam in stackaverflow and other refrences but I dont get my answer
.
I use VideoView In my app
I want to save the last position of videview in a sharedPrefrence to start again from the last position but it start in 0 every time
please check my code and tel me what should i do.
package com.rewass.qurankurdishaudiotranslatev2.activitys;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.rewass.qurankurdishaudiotranslatev2.R;
import com.rewass.qurankurdishaudiotranslatev2.adapters.RecyclerViewAdapter;
import com.rewass.qurankurdishaudiotranslatev2.model.ModelRecycler;
import com.rewass.qurankurdishaudiotranslatev2.text.Text002;
import java.util.ArrayList;
import java.util.List;
public class A002 extends AppCompatActivity {
List<ModelRecycler> listItems;
private InterstitialAd mInterstitialAd;
String AudioURL = "https://download.quranicaudio.com/quran/mishaari_raashid_al_3afaasee/002.mp3";
VideoView videoView;
ProgressBar progressBar008;
TextView te008;
int progress;
RecyclerView myrv;
String kurdish002 = "http://sirwaan.com/aaap/audios/kurdish/sound/quran/qurankurdish/002.mp3";
String v2kurdish002 = "https://sirwaan.com/aaap/audios/kurdish/sound/quran/newversionqurankurdish/002.mp3";
Handler handler;
GridLayoutManager layoutManager;
int seekkk;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a002);
audioSora();
}
SharedPreferences preferences ;
private void audioSora() {
preferences = getSharedPreferences("pref55",MODE_PRIVATE);
videoView = findViewById(R.id.videoview002);
videoView.setVideoPath(v2kurdish002);
//control media
MediaController mediaController = new MediaController(this);
//set view with controller
videoView.setMediaController(mediaController);
//set Controller to view
mediaController.setAnchorView(videoView);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
SharedPreferences.Editor editor = preferences.edit();
int progress = videoView.getCurrentPosition();
editor.putInt("seekto", progress);
editor.apply();
seekkk = preferences.getInt("seekto", 0);
Toast.makeText(A002.this, seekkk+"", Toast.LENGTH_SHORT).show();
handler.postDelayed(this, 1000); }};
handler.postDelayed(r, 1000);
videoView.seekTo(seekkk);
videoView.start();
}
});
}
}
private int time = 0;
private ScheduledExecutorService mScheduledExecutorService;
Runnable getPositionVideo = () -> {
time = binding.epVideoView.getCurrentPosition();
Log.d(TAG, ": " + time);
};
binding.epVideoView.setOnPreparedListener(mediaPlayer -> {
mediaController.setAnchorView(binding.epVideoView);
binding.epVideoView.start();
mScheduledExecutorService = new ScheduledThreadPoolExecutor(1);
mScheduledExecutorService.scheduleWithFixedDelay(() -> {
runOnUiThread(getPositionVideo);
MediaControllerCustom.init(url, time);
}, 1000, 1000, TimeUnit.MILLISECONDS);
});

adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) ); this code generates error & i am unable to solve error

adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) );This Line Generates Error & my knowlwdge is quite low about this error. the both required java file & the detailed error is given after this two java files.
ImageAdapter.java
package com.example.login;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context Context;
private List<Upload> Uploads;
private OnItemClickListener Listener;
public ImageAdapter (Context context, List<Upload> uploads1){
Context = context;
Uploads = uploads1;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent,int viewType) {
View v= LayoutInflater.from(Context).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder,int position) {
Upload uploadCurrent= Uploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.with(Context)
.load(uploadCurrent.getImageUrl())
.placeholder(R.drawable.logo)
.fit()
.centerInside()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return Uploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_product_name);
imageView = itemView.findViewById(R.id.product_image);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if(Listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Listener.OnItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem details = menu.add(Menu.NONE ,1,1,"Details");
MenuItem delete = menu.add(Menu.NONE ,2,2,"Delete");
details.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if(Listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch(item.getItemId()){
case 1:
Listener.OnDetailsClick(position);
return true;
case 2:
Listener.OnDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener{
void OnItemClick(int Position);
void OnDetailsClick(int Position);
void OnDeleteClick(int Position);
}
public void SetOnClickItemListener(OnItemClickListener listener){
Listener = listener;
}
}
MyAddsFragment.java
package com.example.login.ui.login;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.login.ImageAdapter;
import com.example.login.R;
import com.example.login.Upload;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MyAddsFragment extends Fragment implements ImageAdapter.OnItemClickListener{
private RecyclerView recyclerView;
private ImageAdapter adapter;
private ProgressBar progressBar;
private DatabaseReference databaseRef;
private List<Upload> Uploads;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_myadds, container, false);
recyclerView = v.findViewById(R.id.Recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
progressBar = v.findViewById(R.id.progress_bar_1);
Uploads = new ArrayList<>();
databaseRef = FirebaseDatabase.getInstance().getReference("uploads");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot){
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
Upload upload = postSnapshot.getValue(Upload.class);
Uploads.add(upload);
}
adapter = new ImageAdapter(getActivity(), Uploads);
recyclerView.setAdapter(adapter);
adapter.SetOnClickItemListener((ImageAdapter.OnItemClickListener) getActivity());
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
});
return v;
}
#Override
public void OnItemClick(int Position) {
Toast.makeText(getActivity(),"Normal Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
#Override
public void OnDetailsClick(int Position) {
Toast.makeText(getActivity(),"Details Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
#Override
public void OnDeleteClick(int Position) {
Toast.makeText(getActivity(),"Delete Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
}
Error is Given below
01-24 12:33:27.072 6252-6252/com.example.login E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.login, PID: 6252
java.lang.ClassCastException: com.example.login.HomeActivity cannot be cast to com.example.login.ImageAdapter$OnItemClickListener
at com.example.login.ui.login.MyAddsFragment$1.onDataChange(MyAddsFragment.java:57)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.0:55)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
....................................................................................................
your class MyAddsFragment is implementing the ImageAdapter.OnItemClickListener so to set adapter.SetOnClickItemListener you can simple use below code -
adapter.SetOnClickItemListener(MyAddsFragment.this)
You can not cast ImageAdapter.OnItemClickListener to HomeActicity.class as it might not implementing it.

Why does the program not call the method "onLocationChanged"?

i wrote this simple code for getting the GPS coordinates but it doesnt call the method "onChangedLocation". I know it should jump into the method only when the coordinates change, but at first start it always should jump into that method or not?
It should display the longtitude and latitude in the catlog.
Im using my phone for debugging.
package tabs;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import androfenix.whetoo.R;
public class Tab1 extends ListFragment implements LocationListener {
double latitude;
double longitude;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_local, container, false);
String[] abc = {"Message1", "Message2", "Message3", "Message1", "Message2", "Message3", "Message1", "Message2", "Message3", "Message1", "Message2", "Message3"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, abc);
setListAdapter(adapter);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
return v;
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "onLocationChanged wird aufgerufen");
longitude = location.getLongitude();
String name = String.valueOf(longitude);
Log.d("longtitude", name);
latitude = location.getLatitude();
String name2 = String.valueOf(latitude);
Log.d("latitude", name2);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

Issues in implementing notification to calender in android

hiii
I am new to to android.I have created a calender where I am able to set alarm.
But the problem is I am unable to receive any message i.e if i set an alarm of 2.30pm,A message should appear that alarm received.I am not receiving this message ..Please suggest..
Please help
Here is the code...
alarm.java
package com.example.notificationalarm;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
public class Alarm extends ActionBarActivity
{
TimePicker myTimePicker;
Button buttonstartSetDialog;
TextView textAlarmPrompt;
TimePickerDialog timePickerDialog;
final static int RQS_1 = 1;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
textAlarmPrompt=(TextView)findViewById(R.id.alarm);
buttonstartSetDialog = (Button)findViewById(R.id.startSetDialog);
buttonstartSetDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
textAlarmPrompt.setText("");
openTimePickerDialog(false);
}
});
}
private void openTimePickerDialog(boolean is24r){
Calendar calendar = Calendar.getInstance();
timePickerDialog = new TimePickerDialog(
Alarm.this,
onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
is24r);
timePickerDialog.setTitle("Set Alarm Time");
timePickerDialog.show();
}
OnTimeSetListener onTimeSetListener= new OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
calSet.set(Calendar.MINUTE, minute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if(calSet.compareTo(calNow) <= 0){
//Today Set time passed, count to tomorrow
calSet.add(Calendar.DATE, 1);
}
setAlarm(calSet);
}};
private void setAlarm(Calendar targetCal){
textAlarmPrompt.setText(
"\n\n***\n"
+ "Alarm is set# " + targetCal.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
}
AlarmReceiver .java
public class AlarmReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent arg1)
{
Toast.makeText(arg0, "Alarm received!", Toast.LENGTH_LONG).show();
}
}
How have you declared your AlarmManager in the Manifest?
When I look on the code I cannot find any bug, so let's try this in your manifest.xml
<receiver
android:name="your.package.AlarmReceiver"/>
This might help

javafx html editor

actually i'm looking for something very similar to this thread:
How to hide the controls of HTMLEditor?
so basically i try to add a custom button to the javafx html editor but with the difference that it's implemented through FXML.
So my question is:
Is there a "work-around" to add custom buttons to the html-editor when it's implemented through FXML?
Sample solution is :
htmlEditor.setVisible(false);
Platform.runLater(new Runnable() {
#Override
public void run() {
Node[] nodes = htmlEditor.lookupAll(".tool-bar").toArray(new Node[0]);
for (Node node : nodes) {
node.setVisible(false);
node.setManaged(false);
}
htmlEditor.setVisible(true);
}
});
I have modified the #jewelsea answer for javaFX9.
I have also added some customization to move toolbars. The main idea is to get all the components by css selector, then modify or hide them. Read the class HTMLEditorSkin to get the CSS classes names, like ".html-editor-align-center" for the align button.
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.ToolBar;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;
public class HTMLEditorCustomizationSample2 extends Application {
// limits the fonts a user can select from in the html editor.
private static final ObservableList<String> limitedFonts = FXCollections.observableArrayList("Arial",
"Times New Roman", "Courier New", "Comic Sans MS");
private HTMLEditor htmlEditor;
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("unchecked")
#Override
public void start(Stage stage) {
htmlEditor = new HTMLEditor();
stage.setScene(new Scene(htmlEditor));
stage.show();
customizeEditor(htmlEditor);
}
private void customizeEditor(HTMLEditor htmlEditor) {
// hide controls we don't need.
Node seperator = htmlEditor.lookup(".separator");
seperator.setVisible(false);
seperator.setManaged(false);
hideByClass(htmlEditor, ".separator");
hideByClass(htmlEditor, ".html-editor-cut", ".html-editor-copy", ".html-editor-paste", ".html-editor-strike",
".html-editor-hr");
hideByClass(htmlEditor, ".html-editor-align-left"
, ".html-editor-align-center"
, ".html-editor-align-right"
, ".html-editor-align-justify", ".html-editor-outdent"
, ".html-editor-indent", ".html-editor-bullets"
, ".html-editor-numbers");
// Move the toolbars
Node top= htmlEditor.lookup(".top-toolbar");
GridPane.setConstraints(top,1,0,1,1);
Node bottom= htmlEditor.lookup(".bottom-toolbar");
GridPane.setConstraints(bottom,0,0,1,1);
Node web= htmlEditor.lookup("WebView");
GridPane.setConstraints(web,0,1,2,1);
// modify font selections.
int i = 0;
Set<Node> fonts = htmlEditor.lookupAll(".font-menu-button");
Iterator<Node> fontsIterator = fonts.iterator();
fontsIterator.next();
ComboBox<String> formatComboBox = (ComboBox<String>) fontsIterator.next();
formatComboBox.itemsProperty().addListener((obs, old, value) -> {
if (value.size() != limitedFonts.size()) {// should loop on array for equality
Platform.runLater(() -> {
value.clear();
// stop.set(true);
value.addAll(limitedFonts);
formatComboBox.setValue(limitedFonts.get(0));
});
}
});
// add a custom button to the top toolbar.
Node node = htmlEditor.lookup(".top-toolbar");
if (node instanceof ToolBar) {
ToolBar bar = (ToolBar) node;
ImageView graphic = new ImageView(
new Image("http://bluebuddies.com/gallery/title/jpg/Smurf_Fun_100x100.jpg", 16 , 16, true, true));
graphic.setEffect(new DropShadow());
Button smurfButton = new Button("", graphic);
bar.getItems().add(smurfButton);
smurfButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
htmlEditor.setHtmlText("<font face='Comic Sans MS' color='blue'>Smurfs are having fun :-)</font>");
}
});
}
}
private void hideByClass(HTMLEditor htmlEditor, String... selectors) {
for (String selector : selectors) {
Set<Node> nodes = htmlEditor.lookupAll(selector);
for (Node node : nodes) {
node.setVisible(false);
node.setManaged(false);
}
}
}
#Override
public void stop() throws Exception {
super.stop();
System.out.println(htmlEditor.getHtmlText());
}
}
Here is some sample code which customizes the HTMLEditor and adds a custom button to it. The sample code does not use fxml but really it's very similar if fxml is used. You could define the HTMLEditor in fxml and inject it into your Controller using the standard #FXML annotation. Once you have a reference to the editor, customize it in Java code using an appropriate variation of the sample code. For the added button, just create it in Java rather than fxml and it will be simpler.

Resources