Is there a lib that can build a simple GUI by looking at a class or method signature?
For Example:
class MyMath{
public static double sqrt(double d){
//impl
}
}
To
So that when the button is clicked the method is invoked and the result is shown.
Do you know any examples of something like that in Java or other languages?
thanks
I coded a very basic example, which shows how this can be achieved using a few lines reflection code and little swing. Maybe init() should return the number of methods found for use in the GridLayout, then it would be more dynamic.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Method;
import java.util.HashMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MathPanel extends JFrame {
public static double sqrt(double d) {
return Math.sqrt(d);
}
public static double sin(double d) {
return Math.sin(d);
}
public static double cos(double d) {
return Math.cos(d);
}
class Item implements ActionListener {
JTextField result = new JTextField();
JTextField param = new JTextField();
JButton button;
Method m;
public Item(JFrame frame,String name, Method m) {
button = new JButton(name);
button.addActionListener(this);
this.m = m;
frame.getContentPane().add(param);
frame.getContentPane().add(button);
frame.getContentPane().add(result);
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
Item item = map.get(cmd);
try {
double dbl = Double.parseDouble(item.param.getText());
Object invoke = item.m.invoke(this, dbl);
item.result.setText("" + invoke );
}
catch (Exception x) {
x.printStackTrace();
}
}
}
HashMap<String,Item>map = new HashMap<String, Item>();
public MathPanel() {
setLayout(new GridLayout(3,3));
setTitle("Test");
setSize(400, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void init() {
try {
Method[] allMethods = MathPanel.class.getDeclaredMethods();
for (Method m : allMethods) {
String mname = m.getName();
Class<?> returnType = m.getReturnType();
if ( returnType.getName().equals("double")) {
Item item = new Item(this,mname,m);
map.put(mname,item);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
MathPanel mp = new MathPanel();
mp.init();
}
}
Actually there is in the form of Java Management Extensions or JMX. But it is a very heavy hammer for the kind of example you are giving here. But it exposes methods and properties in a standard way and you can get to them using tools like web interfaces, JConsole, remote procedure call and so forth.
It is used to instrument and manage application servers and the like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With