Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use Java Swing in c++

This may be a bit of an odd question, but I would like to know if you can use Java inside c++14. I don't really care for GTK (I find it confusing and over complicated). Swing, however, is very easy to use, and you can get a working project very quickly. So I would like to know if you can use Java Swing inside c++, so I can use Swing as the foreground, as in what you see like graphics, and use c++ for the background, as in stuff you cant see, like calculations and objects and stuff. So if I can have c++ code tell Swing what to look like, or when to update, that would be very useful for the project I have in mind. Thanks in advance for any advice I may receive.

EDIT: Being able to use c++14 inside Java would be acceptable as well. Also, if anyone could get me example code also, this would be very helpful. Thanks!

like image 721
Cody Richardson Avatar asked Feb 27 '26 10:02

Cody Richardson


2 Answers

You shouldn't run Java from C++, but rather C++ from Java. Oracle gives you a way to load native shared libraries, using JNI.

So you would create your view in Java, using Swing, then you would update your view by calling C++ functions that were pre-compiled and exported in a shared library.

That said, using JNI is quite tricky and the speed improvements of C++ might not be worth it; so you should consider using only Java (or only C++ and a library to create your GUI, such as Qt)

like image 127
Angivare Avatar answered Feb 28 '26 23:02

Angivare


In which direction you go is a matter of taste (loading the JVM from a C++ program or loading DLLs from the JVM side).

Usually you go the way which is more logical, e.g. if you already have a C++ program you likely want to load the JVM from the C++ side. That would be your case. Especially if the Java you want to add is essentially "scripting" the C++ application.

If you already have a Java program and want to access a C++ DLL, you load the DLL from Java and write a simple JNI / native Java class.

In our times you would use tools like JNA for that (instead of JNI): https://github.com/java-native-access/jna

Or you can use SWIG to generate wrappers for your C++ classes: http://www.swig.org/

like image 41
Angel O'Sphere Avatar answered Mar 01 '26 00:03

Angel O'Sphere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!