Wait for user input Java Swing - java

I am using JAVA Swing to create a very basic UI. When I run the program, a window will open with a message and browse button(using frame and JButtons for the same). On click of browse button, another window will open to navigate to the file. This I have achieved by calling a FileChooser on the click event of Browse button. However, my program does not wait for user input. The first window with browse button opens and program keeps on executing and ends up in an error as no file has been selected. How do I halt the execution till user input is provided?
In a forum it was advised to use showOpenDialog() method of browser but that straightway opens a browsing window, whereas I want to give the provision to user to click on Browse buttonbrowsewindow
pick file window
My code is below
frame.setLayout(new FlowLayout());
// set up a file picker component
JFilePicker filePicker = new JFilePicker("Pick a file", "Browse...");
filePicker.setMode(JFilePicker.MODE_OPEN);
filePicker.addFileTypeFilter(".jpg", "JPEG Images");
filePicker.addFileTypeFilter(".mp4", "MPEG-4 Videos");
// access JFileChooser class directly
JFileChooser fileChooser = filePicker.getFileChooser();
fileChooser.setCurrentDirectory(new File("C:/"));
// add the component to the frame
frame.add(filePicker);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(520, 100);
frame.setLocationRelativeTo(null); // center on screen
frame.setVisible(true);
System.out.println();
JPicker is the custom class which creates a filechooser and sets things to be done on click of Browse button

Of Course, You set the JFrame visible at the end of its' initialization. You need to do this within the main() method of your startup class. Where is yours?
The JFilePicker (created by: Nam Ha Minh) is applied to a JFrame as a Java Component in order to save a little time in GUI development. I personally would just use the JFileChooser directly within a JButton ActionPerformed event. If you had followed the directions properly then you would see that you need a main() method which only makes sense. What your application Startup class should look like is something like this:
import java.awt.FlowLayout;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestJFilePicker extends JFrame {
private static final long serialVersionUID = 1L;
public TestJFilePicker() {
super("Test using JFilePicker");
setLayout(new FlowLayout());
// set up a file picker component
JFilePicker filePicker = new JFilePicker("Pick a file", "Browse...");
filePicker.setMode(JFilePicker.MODE_OPEN);
filePicker.addFileTypeFilter(".jpg", "JPEG Images");
filePicker.addFileTypeFilter(".mp4", "MPEG-4 Videos");
// access JFileChooser class directly
JFileChooser fileChooser = filePicker.getFileChooser();
fileChooser.setCurrentDirectory(new File("D:/"));
// add the component to the frame
add(filePicker);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(520, 100);
setLocationRelativeTo(null); // center on screen
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestJFilePicker().setVisible(true);
}
});
}
}
The above code (which is the work of Nam Ha Minh) of course assumes that you have already applied the JFilePicker and the FileTypeFilter class files to your project. Without them the above code will not work.

Related

JFilechooser change default appearance

A JFileChooser used to select a directory is initialized using:
JFileChooser directoryChooser = new JFileChooser();
directoryChooser.setDialogTitle("Choose Directory");
directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
directoryChooser.setAcceptAllFileFilterUsed(false);
and opened using:
directoryChooser.updateUI();
directoryChooser.showOpenDialog(null);
File selectedFile = directoryChooser.getSelectedFile();
which works and i can select a directory but i don't like it's appearance:
I would like it to have the same appearance as the DirectoryChooser in JavaFx, which is also the same appearance for example as the open/save dialog in Chrome & Firefox. That would also make it possible to enter the path manually.
Is it possible to achieve what i want without using JavaFx and if so how can i change it's appearance?
Update
I noticed that you edited your question to include the text "without using JavaFx". As this answer is using JavaFX, and you don't wish to use that technology, you can ignore it.
As you state "I would like it to have the same appearance as the DirectoryChooser in JavaFx", then you may as well just use the DirectoryChooser from JavaFX from within your Swing application.
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.DirectoryChooser;
import javax.swing.*;
import java.io.File;
public class SwingWithJavaFXDirectoryChooser {
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// creating a new JFXPanel (even if we don't use it), will initialize the JavaFX toolkit.
new JFXPanel();
DirectoryChooser directoryChooser = new DirectoryChooser();
JButton button = new JButton("Choose directory");
button.addActionListener(e ->
// runLater is called to create the directory chooser on the JavaFX application thread.
Platform.runLater(() -> {
File selectedDirectory = directoryChooser.showDialog(null);
System.out.println(selectedDirectory);
})
);
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(SwingWithJavaFXDirectoryChooser::createAndShowGUI);
}
}

JTextArea print dialog

Recently I have been working on a project which uses Java Swing to build the GUI. I want to print the text in a JTextArea and therefore I wrote something like
boolean printed = textArea.print();
This brings up a modal dialog. However the dialog seems to have no parent and the main frame (the one containing textArea) blocks the print dialog.
As you see, the print dialog (the thin line at the bottom) goes behind the main JFrame.
Code:
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;
public class JTextAreaPrintBug {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,600);
frame.setLocationRelativeTo(null);
frame.setAlwaysOnTop(true);
//now add JTextArea
frame.setLayout(new BorderLayout());
JTextArea textArea = new JTextArea();
frame.add(textArea, BorderLayout.CENTER);
frame.setVisible(true);
try {
textArea.print();
} catch (PrinterException ex) {}
}
});
}
}
Is it possible to bring the print dialog to front (or explicitly set the parent of the print dialog), preferably not reinventing the wheel? Thanks in advance.
Edit: I know there is a line frame.setAlwaysOnTop(true);. What I really want is to bring the print dialog to the very front even if the main frame is always on top.
Edit (2): I finally opted for a workaround which uses a WindowFocusListener and the getOppositeWindow() method in WindowEvent to obtain a reference to the print dialog. Still I resort to reflection (getting the name of the instance's class) to check whether the "opposite window" is a print dialog, or just an ordinary dialog in my application. Anyway, welcome for more elegant solutions.
It's because of this
frame.setAlwaysOnTop(true);
So change it to false to see the print window.
or
Remove that line, if you don't want your main window to block other windows. Default value is false anyway.

Java: how to open one Jframe from another Jframe which is not in the same file but in the same package;

Java: how to open one Jframe from another Jframe which is not in the same file but in the same package; For eg: project package is test1 and it has 2 Jframes ( home1 and home2 ) Need to open that second frame from the first one (home2 from home1) while clicking on a JButton called 'NEXT'.
can anyone help..
So your problem is to open a new frame from a departure frame ? It's simple you just need to instanciate a new frame object like in the following :
JFrame home2 = new Home2(); // don't forget the import since it's a custom made Frame ;)
home2.setVisible(true);
Now you want that to be done when you click on a JButton. To do so you need to add an ActionListener, using an anonyous class, to the JButton with the previous code.
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//stuff
}
});
See the addActionListener() method of JButton and the ActionListener.
You can show the other JFrame simply by calling
home2 h2 = new home2();
h2.setVisible(true);

Open JFrame from JDialog and it shows on top of JDialog

This is the scenario,
My JFrame has a button it will open a JDialog when click it and it is a model dialog.
JDialog has another button and i want to open another JFrmae open when click it.
Result : another Jframe open but it will not come to the top.It shows under the dialog.I want to open the 2nd JFrame on top of that dialog.
can use secondFrame.setAlwaysOnTop(true); but i don't have control to close it or move it.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class FrameTest
{
public static void main(String args[])
{
JFrame firstFrame = new JFrame("My 1st Frame");
JButton button = new JButton("Frame Click");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JDialog dialog = new JDialog();
dialog.setSize(100, 100);
dialog.setModal(true);
JButton button1 = new JButton("Dialog Click");
button1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JFrame secondFrame = new JFrame("My 2nd Frame");
secondFrame.setVisible(true);
secondFrame.setSize(400, 200);
secondFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
secondFrame.setAlwaysOnTop(true);
}
});
dialog.add(button1);
dialog.setVisible(true);
}
});
firstFrame.add(button);
firstFrame.setVisible(true);
firstFrame.setSize(400, 200);
firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
JDialog has another button and i want to open another JFrmae open when
click it.
Don't do that. A tipical Swing application has a single main JFrame and several JDialogs. See this topic The Use of Multiple JFrames, Good/Bad Practice?
Result : another Jframe open but it will not come to the top.It shows
under the dialog.I want to open the 2nd JFrame on top of that dialog.
Of course it does because the dialog is modal.
can use secondFrame.setAlwaysOnTop(true); but i don't have control to
close it or move it.
It won't solve anything because the problem has to do with modality in dialogs. See this article: How to Use Modality in Dialogs to understand how modality works. There's an explanation in this answer too.
Try
secondFrame.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
It worked for me in the same situation.

How to restart a Java Application launching a specific class of my application?

I have the following situatation:
I have a Java Swing application.
In the class that implement my GUI I have a button named Log Out tath is binding to an event listener that handle the click event, something like it:
JButton logOutButton = new JButton("LogOut");
header.add(logOutButton);
Then in the same class that implement my GUI I have declared the ActionListener that handle this event using an inner class:
logOutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("logOutButton clicked !!!");
System.exit(0);
}
});
In this moment when I click the logOutButton button the program end. I would that instead exit it is restarted by running a specific class called LoginForm (the class that implement the login form GUI)
What can I do to do this thing?
Tnx
Andrea
You don't really need to close/open window junky approach at all. Just use Card Layout:
set Frame's content pane's layout to card layout.
getContentPane().setLayout(new CardLayout());
Put your different Form's content code inside different panel and
add them to the content pane with their corresponding name, for example:
getContetnPane().add(logInFormPanel, "logIn Form");
Now you can simulate the card to appear whenever necessary by calling CardLayout.show(Container parent, String name). For example:
logOutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("logOutButton clicked !!!");
CardLayout cl = (CardLayout)(getContentPane().getLayout());
cl.show(getContentPane(), "logIn Form");
}
});
Check out a CardLayout demo from my another answer.

Categories