01 /*
02 * SPDX-License-Identifier: Apache-2.0
03 *
04 * Copyright 2008-2017 the original author or authors.
05 *
06 * Licensed under the Apache License, Version 2.0 (the "License");
07 * you may not use this file except in compliance with the License.
08 * You may obtain a copy of the License at
09 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package griffon.lanterna.widgets;
19
20 import com.googlecode.lanterna.gui.Action;
21 import com.googlecode.lanterna.gui.component.Button;
22 import griffon.exceptions.GriffonException;
23 import griffon.lanterna.support.LanternaAction;
24
25 import java.beans.PropertyChangeEvent;
26 import java.beans.PropertyChangeListener;
27 import java.lang.reflect.Field;
28
29 import static griffon.util.GriffonNameUtils.isNotBlank;
30
31 /**
32 * @author Andres Almiray
33 */
34 public class MutableButton extends Button {
35 private LanternaAction lanternaAction;
36
37 public MutableButton() {
38 this("", new LanternaAction());
39 }
40
41 public MutableButton(Action action) {
42 this("", action instanceof LanternaAction ? action : new LanternaAction(action));
43 }
44
45 public MutableButton(String text) {
46 this(text, new LanternaAction());
47 }
48
49 public MutableButton(String text, Action action) {
50 super(text, action instanceof LanternaAction ? action : new LanternaAction(action));
51 try {
52 Field field = getClass().getSuperclass().getDeclaredField("onPressEvent");
53 field.setAccessible(true);
54 lanternaAction = (LanternaAction) field.get(this);
55
56 lanternaAction.addPropertyChangeListener(LanternaAction.NAME, new PropertyChangeListener() {
57 public void propertyChange(PropertyChangeEvent event) {
58 setText(event.getNewValue().toString());
59 }
60 });
61 if (isNotBlank(lanternaAction.getName())) {
62 setText(lanternaAction.getName());
63 }
64 } catch (NoSuchFieldException | IllegalAccessException e) {
65 throw new GriffonException(e);
66 }
67 }
68
69 public void setAction(Runnable runnable) {
70 lanternaAction.setRunnable(runnable);
71 }
72
73 public LanternaAction getAction() {
74 return lanternaAction;
75 }
76 }
|