Good evening,
I ask myself the following head breaks:
I would like to create a Favorites button that has the two following states:
1st state: "Add to Favorites"
2nd state (on OnClick event): "Remove from favorites"
But I'd also be able to return to the 2nd state: "Add to Favorites" by a 2nd OnClick event ect..
Does anyone have a solution for it with a simple OnClickListener it seems impossible.
I finally solved my problem using a custom checkbox !!Is the best way to use favorite things because you can get the state of your drawable !!
like that :
favoris_button = (CheckBox) findViewById(R.id.star);
favoris_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
favoris_button.setText("Supprimer des categories");
}
else
favoris_button.setText("Ajouter aux favoris");
}
});
Run this code inside your listener or wrap a function around it and pass it the boolean and call it when you need to. Startup, reset or whenever you want to change the state. If the button is clicked you need to flip the state.
private Boolean check;
favoris_button = (Button) findViewById(R.id.promotion_favoris);
favoris_button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (check == true)
{
favoris_button.setBackgroundColor(R.drawable.btn_orange9);
favoris_button.setText("Supprimer des favoris");
}
else
{
favoris_button.setBackgroundColor(R.drawable.btn_red9);
favoris_button.setText("Ajouter aux favoris");
}
check ^= true;
}
});
Related
How can I disable button in MaterialAlertDialogBuilder?
I want to make similar functionality like in this screenshot:
enter image description here
I wrote the following code (dialog contains EditText where user should input his favorite food name).
final MaterialAlertDialogBuilder dialogEnterDishName = new MaterialAlertDialogBuilder(context);
//...
final EditText editTextEnterDishName = new EditText(context);
dialogEnterDishName.setView(editTextEnterDishName);
dialogEnterDishName.setPositiveButton(getString(R.string.dialog_enter_dish_name_positive_button), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!editTextEnterDishName.getText().toString().equals(""))
//...
else {
//TODO Make posititve button disabled until the user enters any character
}
}
});
//...
dialogEnterDishName.show();
}
I already knew, that class AlertDialog (MaterialAlertDialogBuilder extends AlertDialog.Builder) have a method public Button getButton(int whichButton), but I can't use it in MaterialAlertDialogBuilder.
Please, help!
Make sure that you are calling getButton() function after you inflate your AlertDialog (through .show() call). If you are doing it other way around there is no button to get.
In order to enable button back you can use TextWatcher. More details here: Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged
val customLayout = LayoutInflater.from(context).inflate(R.layout.your_alert_dialog, null, false)
val dialog = MaterialAlertDialogBuilder(context)
.setTitle("Provide name")
.setView(customLayout)
.setNeutralButton("Cancel") { dialog, _ -> dialog.dismiss() }
.setPositiveButton("Confirm") { _, _ -> }
.create()
dialog.show()
dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false
JavaFX does not execute events like the ActionEvent for Button or CheckBox, if a modifier key like CTRL or SHIFT is pressed. As far as I understand this behavior is implemented in ButtonBehavior (e.g. note the expression ! keyDown in the following method from that class):
#Override public void mouseReleased(MouseEvent e) {
// if armed by a mouse press instead of key press, then fire!
final ButtonBase button = getControl();
if (! keyDown && button.isArmed()) {
button.fire();
button.disarm();
}
}
First of all, I do not really understand the reason for this. What is the purpose of not firing a button if a key is pressed?
This is my use-case: I want to implement a checkbox that can be checked/unchecked as normal. It will toggle some state in a model. But it should have an additional feature: if the user presses some key like CTRL while checking/unchecking with the mouse, an additional flag called "locked" or "protected" should be set in the model, which will prevent that the state can be overwritten by some other logic of the application.
This should give an idea about the use-case, but if not it doesn't really matter for my actual question: How can I make it possible that a CheckBox can still be toggled (or a Button be pressed) even though the user presses a modifier key?
Thanks for your help!
That is odd you can implement it yourself like so
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
VBox vBox = new VBox();
vBox.setAlignment(Pos.CENTER);
CheckBox checkBox = new CheckBox();
checkBox.setOnMouseClicked(event -> {
if(event.isControlDown()) {
System.out.print("Control down click ");
checkBox.setSelected(!checkBox.isSelected());
}
else
System.out.print("Normal click ");
System.out.println("Checked Status:"+checkBox.isSelected());
});
Button button = new Button("Button");
button.setOnMouseClicked(event -> {
if(event.isControlDown())
System.out.println("Control down click");
else
System.out.println("Normal click");
});
vBox.getChildren().addAll(new Label("Click the box"),checkBox,button);
primaryStage.setScene(new Scene(vBox));
primaryStage.show();
}
public static void main(String[] args) { launch(args); }
}
The output for CheckBox:
Normal click Checked Status:true
Normal click Checked Status:false
Control down click Checked Status:true
Control down click Checked Status:false
The output for Button:
Normal click
Control down click
Hello fellow coders of the night,
I am stuck with a moral dilemma (well not moral, but mostly i don't know what to do).
Suppose I have one button that can do several actions, depending on the menu item which is chosen.
Basically, I've imagined this
private void menuButtonActionPerformed(ActionEvent b)
ActionEvent a
if(a.getSource()==menuItem)
if(b.getSource()==button)
do this and that
Is this the correct way to do this? because if it is I'd have to add ActionListeners on the menuItem but I get stuck with some stupid error code somewhere!
Thanks in advance for helping me!
Post Scriptum : #David, I've tried this, however the initial condition isn't verified.
private void buttonValidateActionPerformed(java.awt.event.ActionEvent evt)
ActionListener l = (ActionEvent e) -> {
if(e.getSource()==menuItemAdd)
{
System.out.println("eureka!");
buttonSearch.setEnabled(false);
if (evt.getSource()==buttonValidate)
{
DataTransac dt = new DataTransac();
dt.addCoders("...");
}
}
if(e.getSource()==itemDelete)
{
DataTransac dt = new DataTransac();
dt.deleteCoders("...");
}
};
menuItemAdd.addActionListener(l);
itemDelete.addActionListener(l);
That won't work; your listener will get a different invocation for each time the listener is used -- so the event source will be either a button or a menu item for a single invocation.
You'll need to respond to the menu item with one ActionListener that stores state, and then separately handle the button action. You could do this with one listener, but I wouldn't; I'd do this:
private MenuItem selected;
private class MenuItemListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
// if you really want to have one listener for multiple menu items,
// continue with the .getSource() strategy above, but store some
// state outside the listener
selected = (MenuItem)event.getSource();
// you could alternatively have a different listener for each item
// that manipulates some state
}
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
// take conditional action based on selected menu item, as you describe
// in the question
}
}
void setup() {
JMenuItem first = /* ... */;
JMenuItem second = /* ... */;
MenuItemListener listener = new MenuItemListener();
first.addActionListener(listener);
second.addActionListener(listener);
JButton button = /* ... */;
button.addActionListener(buttonListener);
}
Generally speaking this is the preferred approach -- use a different listener for each semantic action, rather than one that introspects the source. Your code will be cleaner, simpler, and easier to understand.
For the same reasons, some people prefer to use anonymous classes for Java event listeners. Here's a Gist that shows several syntaxes: https://gist.github.com/sfcgeorge/83027af0338c7c34adf8. I personally prefer, if you are on Java 8 or higher:
button.addActionListener( event -> {
// handle the button event
} );
I have a TableView with a ComboBoxTableCell, when using the default implementation the user have to click three times to select a value from of the ComboBox's list.
I want when the user clicks on the cell to show the combo box list. I based my solution on this one:
JavaFX editable ComboBox in a table view
The cell does get into edit mode (startEdit() is called) but it takes another click to show the list of values, what am I missing?
table.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) ->
{
if (table.getEditingCell() == null)
{
TablePosition focusedCellPos = table.getFocusModel().getFocusedCell();
table.edit(focusedCellPos.getRow(), focusedCellPos.getTableColumn());
}
});
Thanks.
Interesting problem - bubbling up again after quite a while :)
Looks like the approach of the OP is indeed working (as of fx11, some bugs around its editing seem to be fixed) - with a little help from the combo cell:
start editing in a single click handler on the tableView (from OP)
extend ComboBoxTableCell and override its startEdit to open the dropDown
Code snippet:
// set editable to see the combo
table.setEditable(true);
// keep approach by OP
table.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {
TablePosition<Person, ?> focusedCellPos = table.getFocusModel()
.getFocusedCell();
if (table.getEditingCell() == null) {
table.edit(focusedCellPos.getRow(),
focusedCellPos.getTableColumn());
}
});
// use modified standard combo cell shows its popup on startEdit
firstName.setCellFactory(cb -> new ComboBoxTableCell<>(firstNames) {
#Override
public void startEdit() {
super.startEdit();
if (isEditing() && getGraphic() instanceof ComboBox) {
// needs focus for proper working of esc/enter
getGraphic().requestFocus();
((ComboBox<?>) getGraphic()).show();
}
}
});
Maybe not the cleanest solution to this problem, but I found a workaround to make the ComboBoxTableCells drop down its menu in just 1 click:
column.setCellFactory(new Callback<TableColumn<Person, String>, TableCell<Person, String>>() {
#Override
public TableCell<Person, String> call(TableColumn<Person, String> column) {
ComboBoxTableCell cbtCell = new ComboBoxTableCell<>(cbValues);
cbtCell.setOnMouseEntered(new EventHandler<Event>() {
#Override
public void handle(Event event) {
// Without a Person object, a combobox shouldn't open in that row
if (((Person)((TableRow)cbtCell.getParent()).getItem()) != null) {
Robot r = new Robot();
r.mouseClick(MouseButton.PRIMARY);
r.mouseClick(MouseButton.PRIMARY);
}
}
});
return cbtCell;
}
});
PS: I know that this topic is a bit old, but I also stumbled upon this problem recently and could not find any working solution to it online. As I sad, it's not the cleanest workaround, but at least it does its job. ;)
I have like 10 buttons on my UI and I gotta check which one was touched. I was using the following logic and it was working fine, but now I am getting this error for some reason:
NullReferenceException: Object reference not set to an instance of an object
DetectButton.Start () (at Assets/Scripts/DetectButton.cs:14)
Any ideas what could be going on? Here is my code (attached to the canvas), and I am using Unity version 5.1.0f3. If you need any other info I will gladly provide, thanks in advance
void Start()
{
this.GetComponent<Button>().onClick.AddListener(() =>
{
if (this.name == "btnJogadores2")
{
print ("2 jogadores");
jogadores = 2;
}
//QuantidadeJogadores(this.name);
//QuantidadePartidas(this.name);
});
}
You don't have to all this the way you are doing.
An Easier and good practice would be to create 10 separate GameObjects for each button inside your canvas. and then create a single script with 10 separate functions for all those buttons in it. Attach that script to you canvas. and then on the button GameObject select the script on the desired function. Sample below
void Start() { }
void Update() { }
public void button1()
{
Debug.Log("Button3");
}
public void button2()
{
Debug.Log("Button1");
}
public void button3()
{
Debug.Log("Button3");
}
NOTE: button1, button2 and button3 are the functions for 3 separate buttons
Then inside your unity Inspector:
Select your script with you button functions.
Assign you desired method to you button.
After this run your scene and your button will call the assigned methods properly.
Code is not tested, but it should get you started to get all the Buttons.
void Start() {
var buttons = this.GetComponents<Button> ();
foreach(var button in buttons) {
button.onClick.AddListener(() = > {
if (this.name == "btnJogadores2") {
print("2 jogadores");
jogadores = 2;
}
//QuantidadeJogadores(this.name);
//QuantidadePartidas(this.name);
});
}
}
Actually it will be hard to distinguish between the buttons.
The more practical aproach would be to make 10 GameObjects (Child of the Canvas) and attach your Script to everyone of them.