Using IntelliJ for Swing GUI - java

this is my first post on stack overflow. I just started out trying to learn how to code (big big noob) and stumbled across a problem that seems impossible to fix for me:
My Uni uses Eclipse for Java programming. I started with IntelliJ which I very much prefer by now and I would like to keep using it. In todays lecture, our professor introduced us to Swing GUI. In Eclipse, she uses Window Builder which is not available for IntelliJ. I thought this would for sure not be a problem until she created a new GUI Class (uploaded a pic with all the options available in Eclipse to create a new GUI). She created a "Application Window" and instantly has some lines of code that are able to run an empty Panel which she uses as a basis to add more content (added the code that comes with creating a new "Application Window" in Eclipse). This option is not available in IntelliJ.
Please forgive me my bad English and super beginner, non existing knowledge of Java.
I've tried to get around this for the whole evening and can't seem to find a working solution.
Basically if someone knows how I can get a working GUI window in IntelliJ that I can use as a basis - that would already help a lot.
How creating a new Swing Project looks in Eclipse
public class guiVorlage {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
guiVorlage window = new guiVorlage();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public guiVorlage() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I really don't want to switch to Eclipse.
Tried:
Copying + Adjusting the code from Eclipse in an IntelliJ GUI
Watched tutorials but the ones that I watched did not achieve the exact same thing as in the lecture
Write the code manually
I need to be able to have a running GUI in IntelliJ that is empty an can be used as a basis to add more content.

Related

How to add a seekbar to a video played using vlcj in Java Swing?

I’ve trimmed down the code to only the relevant parts and posted it below. The code works fine. The video plays when you run it but it doesn’t have a seekbar.
public class Screen {
//JFrmae
private JFrame frame;
// Panel which I add the canvas to
private JPanel pVid = new JPanel();
// Canvas
Canvas canvas = new Canvas();
// Embedded Media Player
EmbeddedMediaPlayer emp;
/**
* Create the application.
*/
public Screen() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
//Frame
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//Adding the panel to the frame
frame.getContentPane().add(pVid);
//Adding the canvas to the panel
pVid.add(canvas);
//Setting canvas size
canvas.setSize(715, 402);
//Loading the VLC native library
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "lib");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
//Initializing the media player
MediaPlayerFactory mpf = new MediaPlayerFactory();
//Misc
emp = mpf.newEmbeddedMediaPlayer(new Win32FullScreenStrategy(frame));
emp.setVideoSurface(mpf.newVideoSurface(canvas));
//Video file name and playing
String file = "video.mp4";
emp.prepareMedia(file);
emp.play();
//pack method
frame.pack();
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Screen window = new Screen();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
I’ve looked for an answer online for the last 4 days. Finally I decided to ask here. The official website for vlcj has pictures of a vlcj player they’ve made. There is a seekbar in those pictures. Link to the webpage which has the pics: http://capricasoftware.co.uk/#/projects/vlcj
They have a number of useful tutorials there but they don’t have any instructions for adding the seekbar.
Then I tried downloading their vlcj-player project from their GitHub page. It showed an error because it couldn’t resolve the “com.google.common.collect.ImmutableList” which is supposed to be imported. (At the moment I’m reading about ImmutableList and stuff and see if there’s a way to fix it.) Since I couldn’t figure that out yet, I looked for a class named seekbar or the like in their project. I couldn’t find any.
I also searched elsewhere online for the answer but I just couldn’t find it. I’d really appreciate any help. Thank you.
Edit:
(This edit is in response to the suggestion given to me by #caprica. Read their comment to this question and my reply to that in the comment to understand what I'm talking about here in this edit. I think it'll be useful for others in the future.)
All right, there must have been some problem with my Eclipse or computer. (I’ll type out how I fixed it at the end of this comment.) It’s working now. I’ll type out what I did step by step so that may be it’ll be useful to others in the future to download and install the project.
Download the project.
Import it as a Maven project. (Import > Maven > Existing Maven Project)
Now in Eclipse right click the imported project and select Run As > Maven Install
And that’s it. Now you can just run the project normally. If you don’t know how to run the project, do it like this. Right click the project and select Run As > Java Application and then Select VlcjPlayer – uk.co.caprica.vlcplayer.
Alternatively you can open the class where the main method is and run it. VlcjPlayer class is where the main method is located. The class is in the package uk.co.caprica.vlcplayer.
The problem I faced was that somehow all the necessary files didn’t get downloaded when I ran it as Maven Install. But it worked fine in another computer. Since I knew where the files are downloaded to, I just copied the folder from that PC and put it in the same place in my PC. The folder name is ‘repository’. It’s location is C:\Users\User Name\ .m2. Perhaps Eclipse in this PC has some problem. I’ll reinstall it later to avoid problems in the future.
And this may be useful, the VLC that’s installed in this PC is 64 bit. Not sure if that makes a difference but mentioning it just in case.
Now that the app is working fine I will see the code and see how the seekbar is made. Thanks a lot #caprica for telling me that I should import it as a Maven project. :)
The Basic Controls tutorial shows the essential approach: Add a panel of buttons to the frame and give each button an ActionListener that invokes the relevant media player command. As an example, this notional Rewind button would "skip backwards 10 seconds (-10,000 milliseconds)."
JPanel controlsPane = new JPanel();
JButton rewindButton = new JButton("Rewind");
rewindButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mediaPlayerComponent.getMediaPlayer().skip(-10000);
}
});
controlsPane.add(rewindButton);
frame.add(controlsPane, BorderLayout.SOUTH);
The software design is up to you, but you should at least be aware of
JToolBar, seen here and here.
Action, seen here and cited here.
Timer, seen here as a way to repeat an Action.
All right, guys. I’ve figured out how to do it. I’m not sure how it was done in the official Vlcj project but I’ve figured out my own simple way by learning from the official project.
It just takes a few lines of code. It’s very simple.
These are the steps you have to follow:
Create a JSlider.
To the JSlider, add a mouseMotionListener (‘mouseDragged’ to be exact).
Inside that put in the code which would update the video position based on
the change in the JSlider.
Create a Timer.
Put the code inside it to set the value of the JSlider based on the position
of the video.
And that’s it!
This is the code. It comes inside the initialize() method which you can see in the code I’ve given in the question. (And of course you'll also have to create the JSlider and add it to the panel. I haven't shown the code since it's simple.)
js.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
if (js.getValue() / 100 < 1) {
emp.setPosition((float) js.getValue() / 100);
}
}
});
Timer timer = new Timer(100, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
js.setValue(Math.round(emp.getPosition() * 100));
}
});
timer.start();
Some explanation.
The value you get when you use emp.getPosition always seems to be in decimals. It’s something like 0.1334344 at the start of the video and it’s something like 0.998988 at the end. But the value of JSlider is in int. From 0 to 100. So in the mouseMotionListener added to the JSlider I’ve converted the int value of the JSlider to float by dividing it by 100.
And in the action listener inside the timer I’ve multiplied the value of the video position by 100 and then rounded it off to make it an int value. So that value can be set in the JSlider to make it move in sync with the video.
I’m sure the code is rudimentary and there could be some best practices which I may not have followed. Sorry about that but I’m just getting into java by learning the stuff which I find interesting. Those who are good at java and have used such code in an actual project can comment below with how it can be improved.

How to restart a java program within the program

I'm working on a small Java game using Swing for school, and we need to implement a button that "starts a new game" when pressed. The problem is, the game takes multiple parameters from String[] args, so I can't just call the "main" function (where everything is instansiated) again from another class. Any way to do this?
You certainly can call main() from inside your application. But it's also certainly not what you want to do. Instead try moving the instantiation code into another function, most likely a constructor of some type of Game object. Then you can instantiate a new game from both main as well as some kind of restart function without any unintended consequences of calling main from inside your application.
You can use the following code to run a program. Unless your button and game are in the same package, be sure to import it (which will look like import packageName.className).
JButton newbutton = new JButton("New");
newbutton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new className(); //run the class you want to here
}
});
}
});
If you have any questions about this code, please comment below.
You have to lauch your program before exit it.
Runtime rs = Runtime. getRuntime(); try { rs. exec("java -jar your_restartable_program.jar"); }

open application with key pressing

I am building this pop up learning new languages application which if user found an unknown word he can simply press any keyboard key (like e.g alt+p) so that the app pops up and allow him to insert the new word
and in order to make the key get listened to from anywhere i coded the following
public class IsKeyPressed extends JFrame implements KeyListener {
public IsKeyPressed() {
this.setExtendedState(MAXIMIZED_BOTH);
this.setUndecorated(true);
this.setBackground(new Color(0, 0, 0, 0));
this.addKeyListener(this);
this.setAlwaysOnTop(true);
this.setVisible(true);
while (true) {
this.toFront();
this.requestFocus();
this.repaint();
}
}
public static void main(String[] args) {
new IsKeyPressed();
}
#Override
public void keyPressed(KeyEvent ke) {
//open the pop up application
}
but it does only work fine if the frame is focused from taskbar
so basically it ّdoesn`t work
any idea how to fix ? thanks!
but it does only work fine if the frame is focused from taskbar so basically it ّdoesn`t work
any idea how to fix ?
Not with core Java, that's for sure. You're asking how to create a general key listener, one that works even if the application doesn't have focus, and this is something core Java GUI libraries can't do on there own, for the very reason that this functionality would require the coder to get close to the OS to make OS-specific calls, and Java was built to be as OS-agnostic as possible.
So possible solutions include
writing your own OS routines in C and meshing them with your Java program using JNI
writing Java OS routines using JNA
Or (my favorite) use an OS specific tool, such as Auto-It for Windows, to capture the key press and revive your program, and then meshing this with your program via streams.

Jframe not showing anything and "cannot be cast to java.applet.Applet"

I just want to add a button in my empty frame and it's very very simple.
The frame is not showing anything and although the program runs, IDE tells me :"
java.lang.ClassCastException: Spots cannot be cast to java.applet.Applet
at sun.applet.AppletPanel.createApplet(AppletPanel.java:793)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:722)
at sun.applet.AppletPanel.run(AppletPanel.java:379)
at java.lang.Thread.run(Thread.java:744)"
So I extend the JApplet for it and it doesn't complain anymore, the frame now is grey and still nothing. Also, the title is not showing.
What is interesting is that even if I fully copy the example code on the Oracle tutorial site(Official) : Tutorial Site, the same happens and it compains the applet thing.
Please help and Thank you very much!!!
public class Spots{
private static void createAndShowGUI() {
JFrame frame = new JFrame();
JButton jButton = new JButton("Click Me");
jButton.setSize(20,20);
jButton.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(jButton);
frame.setSize(500, 500);
frame.setTitle("Bar Code Scanner");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
createAndShowGUI();
}
}
To everybody who has this issue-- please check your IDE running setting to see it runs as an applet or application. Thanks for your kindly help again!
If you're making an applet your code shouldn't even have a JFrame variable. Instead in the init method, add your JButton to the applet's contentPane() or to a JPanel that is added to the contentPane as just about any tutorial will tell you.
Of course this doesn't hold if you're not trying to create an applet, but if so, why would you be running it as if it were an applet. Please clarify this for us.
Edit
You ask in comment:
Thanks for the help! but what if I want to do it in Jframe way? Because I don't want to create an applet so I didn't extends Japplet or create init(). But the ide complains "you need to extends applet" Is anywhere in my code telling it I'm creating an applet? I dont want to :(
The IDE shouldn't care what type of class you're creating as long as it compiles. It's when you try to run the code that the JVM might complain that it's not an applet, if 1) you try to run it as an applet called in some HTML code, or 2) try to run it with your IDE's applet simulator. If the former, don't do it. Run it as a stand alone program. If the latter, don't do it. Tell the IDE that you're trying to run a Java program, and for both, make sure that you've got a valid main method.
filename cannot be cast to java.applet.Applet:
check points:
1. extends JFrame -> Extends JApplet
2. public constructor() -> public void init()
3. /public static void main(String[] args) { ... }/. It means no need this method.
4. When you've done all above, then save and compile. Because When you run(appletviewer index.html), you need filename.class. This filename.class should be the one that you've done 1~3 and compile already.

Create a simple form application to edit a textfile

I think I need to restate my question ...
I want to create a SIMPLE form application that edits certain areas of one very specific text file. Though I have some web development experience, I do not want to create a browser based application. Basically I want to give a Desktop application a try and I am looking for some help to get started including suggestions for the language of choice. The application should run on Mac OS X. Besides there's no restriction: Java, Cocoa, Python, even a some interactive shell script would be ok.
If you are interested in the details, continue to read here, but not that my question is not LaTex specific...:
I have an automatically generated report file that contains LaTex Code. Now I want to build a little application that creates a form field for every section and it's header. The document contains only a few hundred lines and the should work the following:
\section{ This is were the header text should go inside the document }
\normalsize{ This is where the normal text should go}
The header / normalsize pairs occur 5-6 times within the document. All I want is a little GUI that allows user to edit between the curly braces without seeing any TeX code. I know that there's LyX and other WYSIWYG approaches to LaTeX – I do not want to reinvent the wheel. I just want to protect the auto-generated code a litte from users and make it a little more comfortable to them.
EDIT:
here's my very first try. I guess I should use PlainDocument instead of directly sending it, but I´ll figure that out, since I got plenty of help from trashgod with the editor / Text Component links. The major problem is to single out the content from \section{} and \normalsize{} stuff. Probably I will some regexp here. I need to get a new text area for every appearance.
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileReader;
import javax.swing.*;
public class basicFrame extends JFrame {
// Declare Variables
JScrollPane bildlauf = new JScrollPane();
JTextArea txtfeld = new JTextArea();
public basicFrame() {
super();
// Main window
setTitle("ReportEditor");
setBackground(Color.LIGHT_GRAY);
// components
try {
File datei = new File("report.Rnw");
FileReader in = new FileReader(datei);
txtfeld.read(in, datei);
in.close();
} catch (Exception e) {
System.out.println("Error !");
}
// setLayout(new GridLayout(2,2));
// Scroll Shizzle
bildlauf.getViewport().add(txtfeld, null);
getContentPane().add(bildlauf, BorderLayout.CENTER);
//txtfeld.setSize(500,680);
//add(txtfeld);
//this.getContentPane().add(txtfeld);
// close
addWindowListener(new WindowLauscher());
}
// event handlers...
protected static final class WindowLauscher extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public static void main(String[] args) {
//Fesnter erzeugen und anzeigen, die main Sache halt
basicFrame hf = new basicFrame();
hf.setSize(500, 700);
hf.setLocation(100, 100);
hf.setVisible(true);
}
}
Thx in advance for any suggestions!
The TeX on Mac OS X wiki recommends jEdit, which supports plugins. LaTeXTools might be a good start.
Addendum:
I do not want to reinvent the wheel.
All I want to do is create a form application.
Although these goals are somewhat contradictory, you can always parse the file and use a suitable JTextComponent for each editable section. Here's an overview of Using Text Components; see Text Component Features if you want to create your own editor kit, as discussed in Customizing a Text Editor.
Addendum: In addition to the tutorial, you might look at this text field layout example. Also, consider a two-column JTable, which would allow you to cleanly separate your document model from your form view.
Addendum: A few notes on your code.
Class names are usually capitalized, e.g. BasicFrame.
Don't extend JFrame if you're not changing it's behavior; JPanel is a good container for other components, and it can be displayed in a JFrame.
Always buid your GUI on the EDT.
Keep you view and model separate.

Categories

Resources