COD3BOY
COD3BOY

Reputation: 12092

Adding components to JPanels dynamically during runtime

During the development of a software, I need to execute a statement which is stored as a string. Say for example:

String test = " int a; ";

In the above example, I want to declare a variable a.

Another example is the execution of a mysql statement from a string:

String sqlquery ="SELECT * FROM FULLDETAILS WHERE Classname = 'test' ";
            con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/executable","root","mysql");
             st = (Statement) con.createStatement();
             rs = st.executeQuery(sqlquery);
                          ^

I want to achieve this for Java statements too. Is there a way?

EDIT :

The above given is an example, the real situation is much different (but the thing I basically need is the same).

The situation is that, I have a number of jpanels and I want to add some components to it, say a label, the content of the label is obtained from a database, and its only during runtime I can know, to which panel I should add the component. In this case, I cannot designate the panel by name, say if I have 10 jpanels, I thought I could use a string like:

String test = " jpanel " + i + " .add(jlabel1); " ;

will result in the value of test will be:

jpanel1.add(jlabel1); // provided i is a string with value of i is 1

now I want to execute this. Is there a way?

Upvotes: 2

Views: 612

Answers (2)

Volker
Volker

Reputation: 470

Maybe that's not what you want, but you may use Java's Reflection API carefully to call methods or something else based on (for example) strings.

SQL statements are far different, as they are not really executed by inside Java, they are processed by some additional SQL Server on the other side of the JDBC connection.

Somewhere, you should have an initial list of all your panels or create it at startup or whatever if I am right? You should go and find a datastructure to hold them (a HashMap seems suitable, for example), add all Panels and use a key to get them back and add labels as you want.

Rough example:

Map<Integer, Panel> panelMap = ...
for(int i = 1; i < 10; i++) {
    Panel panel = new Panel();
    panelMap.put(i, panel); 
}

panelMap.get(1).addLabel(labelForPanel1); (for all labels)

Variable names are more or less irrelevant when the program executes, they are all objects then. Hope that suits your needs a bit more...or maybe now I missed totally :)

Upvotes: 8

Raku
Raku

Reputation: 591

What you seem to want to do is something like an eval() function for Java. As far as I know, Java doesn't provide one, but it has support for scripting languages, so you might want to fall back to that.

I found a question on StackOverflow. See the answers there. Alternatively, check out JEXL. It's an Apache Project and I've used it successfully in a project before.

Upvotes: 3

Related Questions