Java - Change which method is used through radio buttons - java

I am trying to make the radio button selection choose which of the encryption methods is used by the program
#FXML
public void atbashChooser(ActionEvent event) {
}
#FXML
public void caesarChooser(ActionEvent evnt) {
}
#FXML
public void encryptShit(ActionEvent event) {
if (atbashButton.isSelected()){
encryptField.setText(new AtbashCipher().encrypt(messageField.getText()));
}
else if (caesarButton.isSelected()){
encryptField.setText(new CaesarCipher().encrypt(messageField.getText()));
}
}
#FXML
public void decryptShit(ActionEvent event) {
if (atbashButton.isSelected()){
decryptField.setText(new AtbashCipher().decrypt(messageField.getText()));
}
else if (caesarButton.isSelected()){
decryptField.setText(new CaesarCipher().decrypt(messageField.getText()));
}
}
This does obviously not work, but is there a way to do this in a somewhat easy way? I can share the FXML code as well if this is necessary.

Related

Thread for controlling components in JFXDrawer

I'm using a JFXDrawer, SalesDrawer containing a VBox and 2 JFXButtons inside it. The contents of the JFXDrawer have a separate controller, SalesDrawerController.java. The controller file, SalesController.java that contains the JFXDrawer consists of 2 anchor panes that I want to set visible on click of the buttons in the JFXDrawer. Till now I was using a set of static boolean variables and making sure on click of a button in the JFXDrawer one of the variables is set to true. Then in the SalesController.java, I used a TimerTask object to check which of these variables were true and set the needed anchor pane to visible. Is there a better way of doing this?
SalesDrawerController.java
public class SalesDrawerController implements Initializable {
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
private void button1Hit(MouseEvent event) {
SalesController.SD[0]=true;
}
#FXML
private void button2Hit(MouseEvent event) {
SalesController.SD[1]=true;
}
}
SalesController.java
public class SalesController implements Initializable {
public static boolean SD[]= {false,false};
static boolean tock=true;
#FXML
private AnchorPane eq_newpane;
#FXML
private AnchorPane eq_delpane;
#FXML
private JFXHamburger SalesHam;
#FXML
private JFXDrawer SalesDraw;
public void initialize(URL url, ResourceBundle rb) {
eq_newpane.setVisible(true);
eq_delpane.setVisible(false);
eq_newpane.setDisable(false);
eq_delpane.setDisable(true);
VBox box = FXMLLoader.load(getClass().getResource("/fxml/SalesDrawer.fxml"));
SalesDraw.setSidePane(box);
HamburgerBackArrowBasicTransition transition = new HamburgerBackArrowBasicTransition(SalesHam);
transition.setRate(-1);
SalesHam.addEventHandler(MouseEvent.MOUSE_PRESSED,(e)->{
transition.setRate(transition.getRate()*-1);
transition.play();
if(SalesDraw.isShown()){
SalesDraw.close();
SalesDraw.toBack();
}
else{
SalesDraw.toFront();
SalesDraw.open();
}
});
threadtock();
}
public void threadtock() {
final java.util.Timer timer = new java.util.Timer();
final TimerTask delayedThreadStartTask;
delayedThreadStartTask = new TimerTask() {
public void run() {
try
{
if(tock){
if(SD[0])
{
eq_newpane.setVisible(true);
eq_delpane.setVisible(false);
eq_newpane.setDisable(false);
eq_delpane.setDisable(true);
}
else if(SD[1]){
eq_delpane.setVisible(true);
eq_newpane.setVisible(false);
eq_newpane.setDisable(true);
eq_delpane.setDisable(false);
}
if(tock)
{
threadtock();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
};
timer.schedule(delayedThreadStartTask, 500);
};
}
Use synchronization mechanisms so you do not inherit deadlocks in your code from 2 or more threads attempting to operate on the same variable at once.
Figuring out how to properly synchronize your threads can be a pain, and it is very hard to explain, let alone debug. So, my best advice is to use google for "Java Concurrency" and "Java Thread Synchronization".
Otherwise, you should start a thread/threads from your main application to preform your intended operations

Checkbox initialization delay Java FX 8

Can someone tell me why there is a delay on Checkbox initialization with my Code?
What happens is that if I open the program, I have to click the Checkbox several times until it performes the desired Action.
The Controller also contains setter and getter methods.
Thanks a lot
public class Controller {
/* Defined variables */
#FXML
private CheckBox happyboxtick;
#FXML
private VBox topbox;
#FXML
private VBox designbox;
#FXML
public void initialize(){
happyboxtick.setSelected(true);
designbox.setVisible(false);
designbox.getChildren().removeAll();
topbox.setVisible(true);
topbox.getChildren().addAll();
}
#FXML
public void doSomething(ActionEvent e) {
//final CheckBox chk1 = new CheckBox("chk 1");
//final CheckBox chk2 = new CheckBox("chk 2");
EventHandler eh = new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (event.getSource() instanceof CheckBox) {
CheckBox chk = (CheckBox) event.getSource();
//System.out.println("Action performed on checkbox " + chk.getText());
//System.out.println(chk);
if(chk.isSelected()){
System.out.println("My box is selected.");
topbox.setVisible(false);
topbox.getChildren().removeAll();
designbox.setVisible(true);
designbox.getChildren().addAll();
} else
{
System.out.println("My box is not selected.");
topbox.setVisible(true);
topbox.getChildren().addAll();
designbox.setVisible(false);
designbox.getChildren().removeAll();
}/*
if ("Yes".equals(chk.getText())) {
chk2.setSelected(!chk1.isSelected());
} else if ("chk 2".equals(chk.getText())) {
chk1.setSelected(!chk2.isSelected());
}*/
}
}
};
happyboxtick.setOnAction(eh);
//chk1.setOnAction(eh);
//chk2.setOnAction(eh);
}
}
The Code compiles perfectly.
Initialization works.
The right Option is selected.
But when I click the box, I may have to click several times until the Elements are shown. And I don't know why.

JavaFX button not working

I started writing a simple music player, but when I tested it, I found that the button wasn't working. I replaced the code in the button's event handler with a simple System.out.println("Got to button");, but it didn't write to the console.
The fxID of the button is playButton.
The #fxml declaration is:
#FXML
private Button playButton;
Initialize:
#FXML
public void initialize() {
this.bindGuiComponentsToViewModel();
this.setEventActions();
}
SetEventActions:
private void setEventActions() {
this.playButton.setOnAction(event -> this.handlePlayAction());
}
handler:
private void handlePlayAction() {
System.out.println("got to play");
}
I haven't been able to find anything through google for the past hour, I've tried making playButton.setDisable(false);, and nothing has worked so far.
Any help is greatly appreciated!
Why not testing the regular way (using an implementation of anonymous class) if it works then the button is bound
yourButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
System.out.println("got to play");
}
});
other solutions :
-Try to use Logger
-Try to Debug the code by adding break point in
private void handlePlayAction() {
x System.out.println("got to play");
}

JavaFX HTMLEditor text change listener

I'm fairly new to the JavaFX world, and I can't seem to figure out how to listen for text-modify events in the HTMLEditor component.
I need this since I'm hooking this widget to a model, which needs updating.
The addEventFilter API, with a KeyEvent.KEY_TYPED event type doesn't seem to be working as it should. When its handler is called, the getHTMLText() isn't updated yet with the most recent character (if someone doesn't understand this paragraph, I'll provide a step-by-step example).
The TextField has a textProperty() on which a listener can be attached.
Now what about the HTMLEditor?
Also, it would be nice to have the listener called ONLY on text modify events (and not on CTRL+A, for example). You know... like SWT Text's addModifyListener().
While using JavaFX HTMLEditor in one of my project application, I also faced a similar situation. I ended up adding a button, upon whose click the parsing of the HTML text would happen, and further tasks executed. With AnchorPane, I was able to add the button on the HTMLEditor seamlessly, and it looked like a part of it.
Anyways, here's a little example of how you can achieve what you want without any extra button:
package application;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;
public class Main extends Application
{
#Override
public void start(Stage primaryStage)
{
try
{
final HTMLEditor editor = new HTMLEditor();
Scene scene = new Scene(editor);
primaryStage.setScene(scene);
editor.setOnKeyReleased(new EventHandler<KeyEvent>()
{
#Override
public void handle(KeyEvent event)
{
if (isValidEvent(event))
{
System.out.println(editor.getHtmlText());
}
}
private boolean isValidEvent(KeyEvent event)
{
return !isSelectAllEvent(event)
&& ((isPasteEvent(event)) || isCharacterKeyReleased(event));
}
private boolean isSelectAllEvent(KeyEvent event)
{
return event.isShortcutDown() && event.getCode() == KeyCode.A;
}
private boolean isPasteEvent(KeyEvent event)
{
return event.isShortcutDown() && event.getCode() == KeyCode.V;
}
private boolean isCharacterKeyReleased(KeyEvent event)
{
// Make custom changes here..
switch (event.getCode())
{
case ALT:
case COMMAND:
case CONTROL:
case SHIFT:
return false;
default:
return true;
}
}
});
primaryStage.show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
launch(args);
}
}
UPDATE:
Upon a bit more of thinking, I found a way to get event handling done even on those button clicks. Here's how:
EventHandler<MouseEvent> onMouseExitedHandler = new EventHandler<MouseEvent>()
{
#Override
public void handle(MouseEvent event)
{
System.out.println(editor.getHtmlText());
}
};
for (Node node : editor.lookupAll("ToolBar"))
{
node.setOnMouseExited(onMouseExitedHandler);
}
If you see the HTMLEditor, it has two ToolBars.
What I'm doing in the code is looking up for those two toolbars, and setting an onMouseExited event handler. The analogy is that if the user enters and makes some changes on the HTML Text and exits the toolbar, an event will be fired, which can then be handled.
You can even set different kind of event handlers on these two toolbars, based on your needs, but in my opinion, these onMouseExited event handlers provide a very wide coverage when used with the onKeyReleased event handlers. The coverage based on onMouseExited handler is not exact though.
here is a simple one
public class HtmlEditorListener {
private final BooleanProperty editedProperty;
private String htmlRef;
public HtmlEditorListener(final HTMLEditor editor) {
editedProperty = new SimpleBooleanProperty();
editedProperty.addListener((ov, o, n) -> htmlRef = n? null: editor.getHtmlText());
editedProperty.set(false);
editor.setOnMouseClicked(e -> checkEdition(editor.getHtmlText()));
editor.addEventFilter(KeyEvent.KEY_TYPED, e -> checkEdition(editor.getHtmlText()));
}
public BooleanProperty editedProperty() {
return editedProperty;
}
private void checkEdition(final String html) {
if (editedProperty.get()) {
return;
}
editedProperty.set(htmlRef != null
&& html.length() != htmlRef.length()
|| !html.equals(htmlRef));
}
}
HtmlEditor is based on Web view
HTMLEditor editor = getEditor();
WebView webView = (WebView) getEditor().lookup("WebView");
new WebViewEditorListener(webView, new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
}
});
Add Callback for tracking html changes.
public static class WebViewEditorListener {
private final ChangeListener<String> listener;
private final WebPage webPage;
private String htmlRef, innerText;
public WebViewEditorListener(final WebView editor, ChangeListener<String> listener) {
this.listener = listener;
webPage = Accessor.getPageFor(editor.getEngine());
editor.setOnMouseClicked(e -> onKeyTyped(webPage.getHtml(webPage.getMainFrame())));
editor.addEventFilter(KeyEvent.KEY_TYPED, e -> onKeyTyped(webPage.getHtml(webPage.getMainFrame())));
}
public String getHtmlContent(){
return htmlRef == null ? "" : htmlRef ;
}
private void onKeyTyped(final String html) {
boolean isEqual = htmlRef != null ? htmlRef.length() == html.length() : html == null;
if (!isEqual){
String text = webPage.getInnerText(webPage.getMainFrame());
listener.changed(null, innerText, text);
innerText = text;
htmlRef = html;
}
}
}

In GWT is there a way to create a KeyPressEvent for the entire view instead of a single input element?

Right now I have the following code working:
#UiHandler("usernameTextBox")
void onUsernameTextBoxKeyPress(KeyPressEvent event) {
keyPress(event);
}
#UiHandler("passwordTextBox")
void onPasswordTextBoxKeyPress(KeyPressEvent event) {
keyPress(event);
}
void keyPress(KeyPressEvent event) {
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
submit();
}
}
I would like the ability to have just one listener for all elements on the view without duplicating an event for each textbox.
The end goal is that if they press enter, regardless of where they are on the page, it should submit the form.
Thanks!
What works, but still requires you to specify it for each widget, but doesn't require duplicate code:
#UiHandler({"usernameTextBox", "passwordTextBox"})
void onPasswordTextBoxKeyPress(KeyPressEvent event) {
keyPress(event);
}
Yes jackcrews is correct. Also you can try the following. It may be VerticalPanel, DockLayoutPanel etc....
UiBinder.ui.xml
<gwt:VerticalPanel ui:field="mainPanel">
<gwt:Label>Name</gwt:TextBox>
<gwt:TextBox ui:field="textBox">
</gwt:VerticalPanel>
Main.java
#UiField
VerticalPanel mainPanel;
public Main() {
focushandler();
}
void focusHandler() {
mainPanel.addDomHandler(new Handler(), KeyPressEvent.getType());
}
final class Handler implements KeyPressHandler {
#Override
public void onKeyPress(KeyPressEvent event) {
//Code what you expect
}
}
Actually this has more number of lines. But it is good practice.
Regards,
Gnik
I found out that the g:FocusPanel allows me to capture events for everything inside the panel.
#UiHandler("focusPanel")
void onFocusPanelKeyPress(KeyPressEvent event) {
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
submit();
}
}

Categories

Resources