I'm building an application which has a few radio buttons and based on the selection the user makes I have to do one thing or another. Now I've used an OptionGroup to create the radio buttons but I don't seem to be able to understand how I can differentiate between radio buttons. In pure java it's pretty straightforward as I would create each radio button and then group them together with a ButtonGroup object but in vaadin I really don't know. The documentation is as usual abysmal, so I'm a bit stuck. Here is some code for you:
public class ConverterComponent extends CustomComponent{
private TextField name2 = new TextField();
private OptionGroup single;
private TextField userInput;
private TextField result;
private Button submit;
private Button reset;
private static final String conversion1 = "Km to miles";
private static final String conversion2 = "Miles to Km";
private static final long serialVersionUID = 1L;
public ConverterComponent(){
submit = new Button("Submit");
reset = new Button("Reset");
result = new TextField();
userInput = new TextField();
result.setEnabled(false);
result.setVisible(false);
userInput.setVisible(false);
reset.setVisible(false);
submit.setVisible(false);
single = new OptionGroup("Select the conversion");
single.addItems(conversion1, conversion2);
reset.addClickListener(new Button.ClickListener(){
#Override
public void buttonClick(ClickEvent event){
clearFields();
getResult().setVisible(false);
}
});
submit.addClickListener(new Button.ClickListener(){
#Override
public void buttonClick(ClickEvent event) {
getResult().setVisible(true);
//NEED TO KNOW WHICH RADIO BUTTON HAS BEEM CLICKED SO THAT i CAN DECIDE WHICH CONVERSION TO USE
}
});
single.addValueChangeListener(new Property.ValueChangeListener(){
#Override
public void valueChange(ValueChangeEvent event) {
clearFields();
/*System.out.println("You chose: " + event.getProperty().getValue().toString() + "\n");
System.out.println("other line " + event.getProperty() + "\n" + " id is " + single.getId() + " size " + single.size());*/
//System.out.println("event is " + event.getProperty().getValue());
switch(event.getProperty().getValue().toString()){
case conversion1:
System.out.println(conversion1);
break;
case conversion2:
System.out.println(conversion2);
break;
}
displayFields();
}
});
}
public OptionGroup getRadioButtons(){
return single;
}
public TextField getResult(){
return result;
}
public TextField getUserInput(){
return userInput;
}
public void displayFields(){
//getResult().setVisible(true);
getUserInput().setVisible(true);
getResetButton().setVisible(true);
getSubmitButton().setVisible(true);
}
public Button getResetButton(){
return reset;
}
public Button getSubmitButton(){
return submit;
}
public void clearFields(){
getResult().setValue("");
getUserInput().setValue("");
}
public void validateInputs(){
}
}
Bear in mind that I have to add more options in the future, but what I'm trying to get to is, when the the user selects a radio button, no matter which, he will get two input boxes one for his input and the other one - read only - displaying the conversion. The point is that when the selection is made and the input boxes are displayed I have to know already what selection the user has made because I have to be able to grab the input and convert it correctly. In the code above I'm displaying the user's choice but I don't have anything to check it or compare it to. Ideally what I would like to do is:
-click the first radio button
-determine which radio button has been selected so I know which conversion to use.
You can use any objects as item ids in Vaadin. For example you could do something like this:
If you for example have an enum presenting different conversions
public enum Conversion {
KM_TO_MILES,
MILES_TO_KM
}
then you could do something like this:
OptionGroup optionGroup = new OptionGroup();
optionGroup.addItem(Conversion.KM_TO_MILES);
optionGroup.setItemCaption(Conversion.KM_TO_MILES, "Km to miles");
optionGroup.addItem(Conversion.MILES_TO_KM);
optionGroup.setItemCaption(Conversion.MILES_TO_KM, "Miles to Km");
optionGroup.addValueChangeListener(e -> {
if (e.getProperty().getValue() == Conversion.KM_TO_MILES) {
// km to miles selected
}
});
Related
I have a button on a JFrame that when clicked I want a dialog box to popup with multiple text areas for user input. I have been looking all around to try to figure out how to do this but I keep on getting more confused. Can anyone help?
If you don't need much in the way of custom behavior, JOptionPane is a good time saver. It takes care of the placement and localization of OK / Cancel options, and is a quick-and-dirty way to show a custom dialog without needing to define your own classes. Most of the time the "message" parameter in JOptionPane is a String, but you can pass in a JComponent or array of JComponents as well.
Example:
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JPasswordField password = new JPasswordField();
final JComponent[] inputs = new JComponent[] {
new JLabel("First"),
firstName,
new JLabel("Last"),
lastName,
new JLabel("Password"),
password
};
int result = JOptionPane.showConfirmDialog(null, inputs, "My custom dialog", JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println("You entered " +
firstName.getText() + ", " +
lastName.getText() + ", " +
password.getText());
} else {
System.out.println("User canceled / closed the dialog, result = " + result);
}
Try this simple class for customizing a dialog to your liking:
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
public CustomDialog()
{
components = new ArrayList<>();
setTitle("Custom dialog");
setMessageType(JOptionPane.PLAIN_MESSAGE);
setRootPane(null);
setOptions(new String[] { "OK", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
JLabel label = new JLabel("<html>" + messageText + "</html>");
components.add(label);
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public int show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
return selection;
}
public static String getLineBreak()
{
return "<br>";
}
}
This lesson from the Java tutorial explains each Swing component in detail, with examples and API links.
If you use the NetBeans IDE (latest version at this time is 6.5.1), you can use it to create a basic GUI java application using File->New Project and choose the Java category then Java Desktop Application.
Once created, you will have a simple bare bones GUI app which contains an about box that can be opened using a menu selection. You should be able to adapt this to your needs and learn how to open a dialog from a button click.
You will be able to edit the dialog visually. Delete the items that are there and add some text areas. Play around with it and come back with more questions if you get stuck :)
Well, you essentially create a JDialog, add your text components and make it visible. It might help if you narrow down which specific bit you're having trouble with.
i created a custom dialog API. check it out here https://github.com/MarkMyWord03/CustomDialog. It supports message and confirmation box. input and option dialog just like in joptionpane will be implemented soon.
Sample Error Dialog from CUstomDialog API:
CustomDialog Error Message
I have 10 toggle buttons say tb1, tb2,.. and so on. Each one has one user data attached to it. I need to attach a listener for a action (sequence of instructions) to be performed when button are clicked and unclicked. I would prefer the listener to be generic (usable for all the buttons).
The problem I am facing is that, how can I access the user data of clicked button in the listener.Please help through this.
#FXML
private ToggleButton tb1;
#FXML
private ToggleButton tb2;
String cpuLoad1 ="D:/myWorkspace/TestAttacks/input_folder/app_debug.apk";
String cpuLoad2 = "D:/myWorkspace/TestAttacks/input_folder/cpuLoad1.apk";
public void initialize(){
tb1.setUserData(cpuLoad1);
tb2.setUserData(cpuLoad2);
ChangeListener clt1 = new ChangeListener() {
public void changed(ObservableValue ov,
Object toggle, Object new_toggle){
if(new_toggle.equals(true)){
/*how can I acces togglebutton userdata here.
*I would like to pass it as argument to this class object*/
App load = new App(buttonClicked.getUserData()); //button clicked could tb1 or tb2
load.installApp();
load.launchApp();
}else{
System.out.println("OFF");
/*how can I acces togglebutton userdata here.
*I would like to pass it as argument to this class object.*/
App load = new App(buttonClicked.getUserData());
load.unInstallApp();
}
}
};
tb1.selectedProperty().addListener(clt1);
tb2.selectedProperty().addListener(clt1);
}
You have several options.
Option1: Collect the ToggleButtons into a collection and use the reference directly in the listener:
List<ToggleButton> toggles = new ArrayList<>(Arrays.asList(tb1, tb2));
for(ToggleButton toggle:toggles)
toggle.selectedProperty().addListener((observable, oldValue, newValue) ->
System.out.println(toggle.getText() + " - Selected: " + toggle.isSelected() + "; UserData: " + toggle.getUserData()));
Option2: You can use the onActionProperty:
tb1.setOnAction(e -> {
ToggleButton toggle = (ToggleButton) e.getSource();
System.out.println(toggle.getText() + " - Selected: " + toggle.isSelected()
+ "; UserData: " + toggle.getUserData());
});
Option3: If you need to store the listeners, you can implement you own ChangeListener.
public class Toggles extends Application {
public static void main(String[] args) { launch(args); }
#Override
public void start(Stage primaryStage) throws Exception {
VBox vBox = new VBox();
for (int i = 0; i < 20; i++) {
ToggleButton tb = new ToggleButton("ToggleButton" + i);
tb.setUserData("UserData" + i);
tb.selectedProperty().addListener(new ToggleButtonSourcedChangeListener(tb));
vBox.getChildren().add(tb);
}
Scene scene = new Scene(new BorderPane(vBox), 320, 240);
primaryStage.setScene(scene);
primaryStage.show();
}
private abstract static class SourcedChangeListener<T extends Node> implements ChangeListener<Boolean> {
T source;
SourcedChangeListener(T source) {
this.source = source;
}
}
private static class ToggleButtonSourcedChangeListener extends SourcedChangeListener<ToggleButton> {
ToggleButtonSourcedChangeListener(ToggleButton source) {
super(source);
}
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
System.out.println(source.getText() + " - Selected: " + source.isSelected()
+ "; UserData: " + source.getUserData());
}
}
}
In this SSCE I created an abstract SourceChangeListener that can be extended by concrete implementations. The intention behind the generic parameter <T extends Node> is to avoid casts.
When you execute this code, and click on the toggles, the output will be like:
ToggleButton4 - Selected: true; UserData: UserData4
ToggleButton5 - Selected: true; UserData: UserData5
ToggleButton4 - Selected: false; UserData: UserData4
ToggleButton8 - Selected: true; UserData: UserData8
ToggleButton5 - Selected: false; UserData: UserData5
ToggleButton2 - Selected: true; UserData: UserData2
I would propose one of the options that use the selectedProperty as the onActionProperty will change only if the button was pressed (by mouse, touch or key) or if you programatically call the fire() method. The other two options will work always, even if you change the selected state programatically.
I have two Textfields that can be input by user and will be used for calculation later (Number only), lets say InputX and InputY. And two radio button, Rad1 and Rad2.
When user Choose Rad1, Both TextFiled are Input-able by User and Stored to memory/variable when user input in it. But when user choose Rad2, only InputX is available and InputY is InputY.setText("InputX only"). If User choose the Rad1 back, i want to restore the value that user input to the InputY previously, not showing "InputX Only".
So, My Question is: How to get the previous value from userinput when user choose the Rad1 back, since its has been overridden by Rad2 InputY.setText("InputX Only") ?
Please create a full code example with all possible/alternative code, i'm new in java.
Note: Im using Netbeans v8.0.2 and create form using built in form builder/designer
public class InputValidator extends javax.swing.JFrame {
private static final String INPUT_X_ONLY = "InputX Only";
private String temp = "";
public InputValidator() {
initComponents();
jRadioButton1.setSelected(true);
buttonGroup1.add(jRadioButton1);
buttonGroup1.add(jRadioButton2);
jRadioButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
jTextField2.setEditable(true);
jTextField2.setText(temp);
}
});
jRadioButton2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
jTextField2.setEditable(false);
temp = jTextField2.getText();
jTextField2.setText(INPUT_X_ONLY);
}
});
}
I am making a simple currency convertor which takes the initial value in a JTextField then the user clicks the JCheckBox corresponding to their desired currency, the converted value will then be displayed in another JTextField. Basically i would like to know is there any way of assigning a value to a checked JCheckBoxi have looked around and cannot find a clear answer to this, any help would be appreciated.
For example if the current conversion rate from Sterling to euro is 1.12244 this value would be assigned when the JCheckBox is checked, so the the original value would be multiplied by the conversion rate.
Think it'd be easier if you assign an action-listener to your JCheckBox and make the conversion on trigger of this event. To check is a JCheckBox is checked or not you can use the isSelected() method
EDIT
Actually i think you need to use JRadioButton's in a ButtonGroup for this, as if you are using a checkbox then there is a chance that more than one is selected. Here is an example of how to do use ButtonGroup and trigger action on the radio button
This would give you the value of the check box.
JCheckBox cb = ...;
// Determine status
boolean isSel = cb.isSelected();
if (isSel) {
// The checkbox is now selected
} else {
// The checkbox is now deselected
}
You can change the value on the action-listener of the JCheckBox
// Create an action
Action action = new AbstractAction("CheckBox Label") {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
JCheckBox cb = (JCheckBox)evt.getSource();
// Determine status
boolean isSel = cb.isSelected();
if (isSel) {
// The checkbox is now selected
} else {
// The checkbox is now deselected
}
}
};
// Create the checkbox
JCheckBox checkBox = new JCheckBox(action);
// this is whole working code i hope this this will help
public class CConvertor extends JFrame {
private JLabel result;
private JCheckBox pk;
private JCheckBox ch;
public CConvertor(){
result = new JLabel();
ch = new JCheckBox();
pk = new JCheckBox();
init();
}
public void init(){
setTitle("JCheckBox Test");
getContentPane().setLayout(new FlowLayout());
add(result);
add(new JLabel(" "));
add(new JLabel(" China "));
add(ch);
add(new JLabel(" Pakistan "));
add(pk);
setSize(400,80);
pk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ch.setSelected(false);
result.setText("Pakistan selected");
}
});
ch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pk.setSelected(false);
result.setText("China is Selected");
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new CConvertor();
}
}
This could not be the best solution but you can try this.
Take an array of JCheckBox.
Make sure only one checkbox gets selected at a time.
Take an array of currency conversion value.
Now based on the index of the selected checkbox get the currency conversion value from array.
Instead of using JCheckBox you can use JRadioButton as suggested by #Balanivash. More simpler and proper solution will be using JComboBox.[I'm with #Riduidel in this.]
I also think that JCheckBox isn't the best option to do what you want, however...
Why don't you extend the JCheckBox class to a CurrencyConverterCheckBox where you can
pass as arguments the currencies and the current value of the conversion.
e.g.:
public class CurrencyConverterCheckBox extends JCheckBox {
private String from;
private String to;
private double value;
public CurrencyConverterCheckBox(String from, String to, double value) {
super();
this.from = from;
this.to = to;
this.value = value;
}
}
Then you will be able to do the conversion when the user clicks the checkbox. You can also provide labels next to the checkboxes (USD to EUR). And you can also provide a method in your new checkbox to flip the currencies and calculate the multiplication factor in the other direction.
kind regards
What it's easiest to do is something like this:
String[] ccys = {"USD", "EUR", "CHF", "JPY"};
public void initUI(){
...
ButtonGroup grp = new ButtonGroup();
for(String ccy : ccys){
JCheckBox cb = new JCheckBox(ccy);
cb.setActionCommand(ccy);
cb.addActionListener(this);
grp.add(cb);
...(add CheckBox to ui)
}
}
private double getRate(String ccy){
...(retrieve the current conversion rate, f.ex from a map)
}
public void actionPerformed(ActionEvent evt){
Double rate = getRate(evt.getActionCommand());
...(calculation, display)
}
I have a button on a JFrame that when clicked I want a dialog box to popup with multiple text areas for user input. I have been looking all around to try to figure out how to do this but I keep on getting more confused. Can anyone help?
If you don't need much in the way of custom behavior, JOptionPane is a good time saver. It takes care of the placement and localization of OK / Cancel options, and is a quick-and-dirty way to show a custom dialog without needing to define your own classes. Most of the time the "message" parameter in JOptionPane is a String, but you can pass in a JComponent or array of JComponents as well.
Example:
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JPasswordField password = new JPasswordField();
final JComponent[] inputs = new JComponent[] {
new JLabel("First"),
firstName,
new JLabel("Last"),
lastName,
new JLabel("Password"),
password
};
int result = JOptionPane.showConfirmDialog(null, inputs, "My custom dialog", JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println("You entered " +
firstName.getText() + ", " +
lastName.getText() + ", " +
password.getText());
} else {
System.out.println("User canceled / closed the dialog, result = " + result);
}
Try this simple class for customizing a dialog to your liking:
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
public CustomDialog()
{
components = new ArrayList<>();
setTitle("Custom dialog");
setMessageType(JOptionPane.PLAIN_MESSAGE);
setRootPane(null);
setOptions(new String[] { "OK", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
JLabel label = new JLabel("<html>" + messageText + "</html>");
components.add(label);
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public int show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
return selection;
}
public static String getLineBreak()
{
return "<br>";
}
}
This lesson from the Java tutorial explains each Swing component in detail, with examples and API links.
If you use the NetBeans IDE (latest version at this time is 6.5.1), you can use it to create a basic GUI java application using File->New Project and choose the Java category then Java Desktop Application.
Once created, you will have a simple bare bones GUI app which contains an about box that can be opened using a menu selection. You should be able to adapt this to your needs and learn how to open a dialog from a button click.
You will be able to edit the dialog visually. Delete the items that are there and add some text areas. Play around with it and come back with more questions if you get stuck :)
Well, you essentially create a JDialog, add your text components and make it visible. It might help if you narrow down which specific bit you're having trouble with.
i created a custom dialog API. check it out here https://github.com/MarkMyWord03/CustomDialog. It supports message and confirmation box. input and option dialog just like in joptionpane will be implemented soon.
Sample Error Dialog from CUstomDialog API:
CustomDialog Error Message