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