Can't Show JOptionPane - Java Swing - java

I am new to Java. And I need your help.
My code is working well until it shows JDialog. I have a button to show a message dialog (JOptionPane). The problem exist when the button is clicked. Message dialog doesn't seems to appear. It more like stuck, can't be closed and it must be terminated from my Eclipse.
Please anyone tell me why JOptionPane can't show? And I don't know what the meaning of parentComponent on its parameter.
Here is my code.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JOptionPane;
#SuppressWarnings("serial")
public class Test extends JDialog implements ActionListener {
private JButton testPane = new JButton(" Test Pane ");
Test() {
initComp();
}
private void initComp() {
this.setSize(300, 200);
this.setLocationRelativeTo(null);
this.setTitle("Test");
this.setAlwaysOnTop(true);
this.setResizable(false);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setLayout(null);
testPane.setBounds(47, 25, 200, 120);
this.add(testPane);
testPane.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Does it show?");
}
}

First, you need to add the following statement in initComp so that the JFrame gets visible:
private void initComp() {
...
this.setVisible(true); // add this to show the frame
...
}
When displaying the dialog, set the parent component to the current JFrame so that it gets displayed in the frame itself:
#Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(this, "Does it show?"); // add this as parent
}

Related

How to mimic the behavior of JPopupMenu with JDialog?

I'm implementing an "in app" search engine with Swing and I want it to behave exactly like Windows 10's search box.
The search box should:
Open above and to the right of the search button, touching the button's edge.
Have the focus when open.
Close (if open) on a press of the search button.
Close (if open) when pressing with the mouse anywhere out of the search box.
It was perfect if JPopUpMenu could have JDialog as it's child but since it can't I need to implement the behaviors from scratch (or do I?).
This is my first time using Swing and I'm having difficulties implementing everything by myself.
I tried looking for examples online but I couldn't find much helpful information.
Is there a workaround to the fact that JPopUpMenu can't host JDialog?
Are there examples of implementing the behaviors I described?
Thanks
===============================Edit============================
Thanks for the comments so far. I've managed to get the behavior I wanted except one issue.
The following code creates a frame with a button:
public static void main(String[] args){
JFrame mainWindow = new JFrame();
mainWindow.setSize(420,420);
mainWindow.setVisible(true);
JFrame popUp = new JFrame();
popUp.setSize(210, 210);
JButton button = new JButton("button");
mainWindow.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!button.isSelected()){
button.setSelected(true);
popUp.setVisible(true);
}
else{
button.setSelected(false);
popUp.setVisible(false);
}
}
});
popUp.addWindowFocusListener(new WindowAdapter() {
#Override
public void windowLostFocus(WindowEvent e) {
popUp.setVisible(false);
}
});
}
When I click the button, a pop-up window appears and if I click out of the main window the pop up disappear but then when I want to re-open the pop-up I need to press the button twice.
How can I get the button to operate correctly when the pop-up was closed due to lose of focus?
Your "solution" is very brittle. Try moving the main JFrame before left-clicking on the JButton.
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Netbeans section. Study the rest of the tutorial.
I created a main JFrame that pops up a JDialog. I put the close JButton on the JDialog. The JDialog is modal, meaning you cannot access the main JFrame while the JDialog is visible.
You can place the JDialog anywhere you wish on the screen. Normally, you have a JDialog appear in the center of the parent JFrame. That's where users expect a dialog to appear. I placed the JDialog towards the upper left, just to show you how it's done.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PopupExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new PopupExample().createAndShowGUI());
}
private JFrame mainWindow;
public void createAndShowGUI() {
mainWindow = new JFrame("Main Window");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.add(createMainPanel(), BorderLayout.CENTER);
mainWindow.pack();
mainWindow.setLocationByPlatform(true);
mainWindow.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(200, 200, 200, 200));
JButton button = new JButton("button");
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
createAndShowDialog(mainWindow);
}
});
return panel;
}
private void createAndShowDialog(JFrame frame) {
JDialog dialog = new JDialog(frame, "Dialog", true);
dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.add(createDialogPanel(dialog), BorderLayout.CENTER);
dialog.pack();
// Here's where you set the location of the JDialog relative
// to the main JFrame
Point origin = frame.getLocation();
dialog.setLocation(new Point(origin.x + 30, origin.y + 30));
dialog.setVisible(true);
}
private JPanel createDialogPanel(JDialog dialog) {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
JButton button = new JButton("Close");
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
return panel;
}
}

How to hide a JFrame but then open it when the message box closes

I'm trying to create a MessageBox Creator.
I Have tried to hide the Creator when the Message Box Opens
and then show when the Message Box Closes. I am using the following plugins for Eclipse Neon:
WindowBuilder
Swing Designer
to help me create the program.
A similar one is here but it did not help: Click Me
The source code is here:
package org.us.me.****.messagebox.creator;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JProgressBar;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MessageBoxCreator {
private JFrame frmD;
private JTextField txtMessageGoesHere;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MessageBoxCreator window = new MessageBoxCreator();
window.frmD.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MessageBoxCreator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmD = new JFrame();
frmD.setTitle("MessageBox: Creator");
frmD.setBounds(100, 100, 260, 113);
frmD.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmD.getContentPane().setLayout(null);
JTextField MessageBox = new JTextField();
MessageBox.setText("Message goes here...");
MessageBox.setBounds(10, 11, 222, 20);
frmD.getContentPane().add(MessageBox);
MessageBox.setColumns(10);
JButton btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, MessageBox);
}
});
btnGenerate.setBounds(10, 42, 86, 23);
frmD.getContentPane().add(btnGenerate);
}
}
Please Help.
Seems like you are trying to hide the Frame on button click and then on popup's button click you want the initial frame back as visible.
The easiest and straight way forward way to do so is to create your own popup box.
Try this out:
class CustomPopup extends JFrame
{
public CustomPopup()
{
frmD.setVisible(false);
this.setName("Popup");
this.setLayout(new BorderLayout());
JLabel l = new JLabel("Enter Message here");
JButton b = new JButton("Submit");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frmD.setVisible(true);
CustomPopup.this.setVisible(false);
CustomPopup.this.dispose();
}
});
this.add(l,BorderLayout.CENTER);
this.add(b,BorderLayout.SOUTH);
this.setSize(300, 150);
this.setResizable(false);
this.setDefaultCloseOperation(0);
this.setVisible(true);
}
}
Then in your button action listener do this:
btnGenerate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
new CustomPopup();
}
});
Note: The above example is in with respect to your code. I have used Border layout for popup in the example as it is the simplest to implement. I believe you can customize the look and feel of your custom popup on your own. There are also more options to create popups with custom settings.
Refer to this for more info:http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
I think the design is not good, but to make the frame hide and show change
this line:
JOptionPane.showMessageDialog(null, MessageBox);
To
frmD.setVisible(false);
JOptionPane.showMessageDialog(null, MessageBox);
frmD.setVisible(true);

how to define action listener for buttons in java

I have a jframe that includes JButton.I have six buttons in this frame, but I don't know how to define action listener for this buttons.please help to solve this problem.
First you have to import the package java.awt.event.* to enable events. After the class name you have to add implements ActionListener so that the class can handle events. When you have created the buttons you have to add an actionlistener to each button. Since you haven't showed which code you use I make an example with a simple program that counts votes, if the user clicks the yesButton the votes are increased with 1 and if the user clicks the noButton the votes are decreased with 1.
Here is the code to add an ActionListener to each button:
yesButton.addActionListener(this);
noButton.addActionListener(this);
Then write the following code to handle the events:
public void actionPerformed(ActionEvent e) {
JButton src = (JButton) e.getSource();
if(src.getActionCommand().equals("Yes")) {
yesCount++;
} else {
noCount++;
}
label.setText("Difference: " + (yesCount - noCount));
}
If you have 6 buttons you need to have an if statement and then 5 "else if" statements instead of only an if and an else statement.
Have a look at the Java tutorials on how to use ActionListeners:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Here's a simple example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Hello extends JPanel implements ActionListener {
JButton button;
public Hello() {
super(new BorderLayout());
button = new JButton("Say Hello");
button.setPreferredSize(new Dimension(180, 80));
add(button, BorderLayout.CENTER);
button.addActionListener(this); // This is how you add the listener
}
/**
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e) {
System.out.println("Hello world!");
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Hello");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Hello();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
buttons have a method called addActionListener, use that for adding the action listener that you can implement for the click...
Example:
dummyButton = new JButton("Click Me!"); // construct a JButton
add(dummyButton); // add the button to the JFrame
dummyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(" TODO Auto-generated method stub");
}
});
It's really simple.
I suppose you have an instance of your button, right? Let's say that instance is called myButton.
You can just add an action listener by calling addActionListener:
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do whatever you like here
}
});
Protip: next time you don't know what method to call, just type the instance name and .. Then, your IDE will show you all the methods you can call, unless you are not using an IDE. If that is the case, download one.

How I enable parent JFrame after close child?

I have a frame, on this frame I have a Menu with About MenuItem. When we select it the program opens a new JPanel with texts and with OK button and the enabled status of parent panel is set to false.
And now comes a problem. When we click on OK, then I want to close this About panel, and I want to turn to parent panel, and I want to enable it!
Please tell me, how?
Consider using a WindowListener that reacts to the closing event of the about-dialog. You can add this in your frame or in the constructor of your dialog, just set the variables accordingly.
myDialog.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
parentFrame.setEnabled(true);
}
});
If you really only have a switching JPanel, use a ButtonListener.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
frame.setEnabled(true);
}
});
As mentioned in the comments, using a modal JDialog would be a more elegant way of solving the problem of disabling a parent frame while a dialog is active. Here is a tutorial.
Why don't you use simply a JOptionPane (particularly the showMessageDialog method)? You can specify there an Object (for example a JPanel) which will be presented in a modal dialog. Take a look at this sample code I've written for you (I've used a JButton, but it will be the same for JMenuItem):
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class AboutDialogDemo extends JFrame {
private final JButton btnAbout = new JButton("About...");
public AboutDialogDemo() {
final JFrame thisFrame = this;
btnAbout.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(thisFrame, new AboutPanel());
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(btnAbout, BorderLayout.PAGE_END);
pack();
}
public static void main(String[] args) {
AboutDialogDemo frame = new AboutDialogDemo();
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class AboutPanel extends JPanel {
private final JLabel lblAbout = new JLabel("Sample about text");
public AboutPanel() {
setLayout(new BorderLayout());
add(lblAbout, BorderLayout.PAGE_START);
}
}
I hope you'll find it useful

Waiting till button is pressed

There are a lot questions on this, but they weren't able to help me or I didn't understand it..
Basically I want user to press the button before system goes back to main method. In this case if system goes back to main method, system will quit.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test123 implements ActionListener{
JTable table;
JButton button;
JFrame frame;
public test123 (){
frame = new JFrame();
frame.setLayout(null);
button = new JButton("Finish");
button.setBounds(200, 10, 70, 40);
button.addActionListener(this);
frame.add(button);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(600, 200);
frame.setVisible(true);
frame.setTitle("TEst123");
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == button){
System.out.println("message....");
}
}
public static void main(String arg[]){
test123 gui = new test123();
System.exit(0);
}
}
Sorry if it was just me lacking the understanding and thank you for help.
EDIT:
Maybe I explained this incorrectly or displayed it incorrectly. Lets say if the system goes back to main system it will do something I don't want, therefor I want the user to press the button to go back to the main system or do "the thing". Sorry for bad explanation, including this one.
This class is separate from my work and I just used it to test stuff... In my project, user can choose from several buttons (lets say main method is the menu in this case). The user presses a button goes to a new window/frame, if the program doesn't pause or waits for button to be pressed, it will go back to main method.
The quick answer is what Andrew Thompson wrote in his comment:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
public class test123 implements ActionListener {
JTable table;
JButton button;
JFrame frame;
public test123() {
frame = new JFrame();
frame.setLayout(null);
button = new JButton("Finish");
button.setBounds(200, 10, 70, 40);
button.addActionListener(this);
frame.add(button);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(600, 200);
frame.setVisible(true);
frame.setTitle("TEst123");
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println("message....");
// System.exit(0);
frame.dispose(); // better than exit
}
}
public static void main(String arg[]) {
test123 gui = new test123();
}
}
but Java class name should start with upper case test123 -> Test123 (but you can find a lot better name for sure).
Why not to extend JFrame also?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test123 extends JFrame implements ActionListener {
private static final long serialVersionUID = 3378774311250822914L;
// private JTable table;
private JButton button;
// JFrame frame;
public Test123() {
// frame = new JFrame();
this.setLayout(null);
button = new JButton("Finish");
button.setBounds(200, 10, 70, 40);
button.addActionListener(this);
this.add(button);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(600, 200);
this.setTitle("Test123");
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println("message....");
// System.exit(0);
this.dispose();
}
}
public static void main(String arg[]) {
Test123 gui = new Test123();
}
}
Read more in Concurrency in Swing tutorial to find out how to deal with long running tasks out of dispatch thread...
From your question it seems, that you do not know how swing application behaves. You create a GUI and the you are waiting for user's input. So basically you do not care what was your program executing, when user pressed the button...
(and therefore it doesn't matter where it returns to)

Categories

Resources