Java program exits when I click OK button in JOptionPane.showMessageDialog - java

when I click the OK button in second.java program, the program exit the program. I want it not to exit (since there is a thread running). I tried removing setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE).
CODE
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.JTextField;
public class second extends JFrame implements ActionListener {
JLabel enterName;
JTextField name;
JButton click;
String storeName;
public second(){
setLayout(null);
setSize(300,250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
enterName = new JLabel("Enter Your Name: ");
click = new JButton("Click");
name = new JTextField();
enterName.setBounds(60,30,120,30);
name.setBounds(80,60,130,30);
click.setBounds(100,190,60,30);
click.addActionListener(this);
add(click);
add(name);
add(enterName);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == click) {
storeName = name.getText();
JOptionPane.showMessageDialog(null, "Hello" + storeName);
System.exit(0);
}
}
public static void main(String args[]){
second s = new second();
s.setVisible(true);
}
}
Many Thanks

You'll need to remove the System.exit(0); line. That's all.

Related

Swing window not opening

I am creating a NotePad app in Java Swing but when I am trying to open a popup to set a title, it is not showing up.
The class that calls the popup:
import java.io.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class NewFile implements ActionListener{
public static String title;
public void actionPerformed(ActionEvent e){
PopupFileName popup = new PopupFileName();
/*try{
Thread.sleep(30000);
}catch (InterruptedException o){
o.printStackTrace();
}*/
JTextArea titl = popup.title;
title = titl.getText();
try{
File writer = new File(title+".txt");
if(writer.createNewFile()){
System.out.println("file created");
}else{
System.out.println("file exists");
}
}catch (IOException i) {
System.out.println("An error occurred.");
i.printStackTrace();
}
}
}
The popup class that is supposed to open:
import javax.swing.*;
public class PopupFileName{
static JFrame popup = new JFrame("File Title");
static JLabel titlel = new JLabel("Title:");
static public JTextArea title = new JTextArea();
public static void main(String[] args){
popup.setSize(200,300);
popup.setVisible(true);
popup.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
popup.add(titlel);
popup.add(title);
}
}
Is there any way I can make it visible and make it able to get the text before it is created?
Start by taking a look at:
Creating a GUI With Swing
How to Write an Action Listener
How to Use Scroll Panes
How to Use Buttons, Check Boxes, and Radio Buttons
How to Make Dialogs
You're running in an event driven environment, this means, something happens and then you respond to it.
The problem with your ActionListener is, it's trying to present a window and then, immediately, trying to get some result from it. The problem is, the window probably isn't even present on the screen yet.
What you need is some way to "stop" the code execution until after the user responds. This is where a modal dialog comes in.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
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;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Test");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String title = PopupFileName.getTitle(TestPane.this);
System.out.println(title);
}
});
add(btn);
}
}
public static class PopupFileName extends JPanel {
private JLabel titlel = new JLabel("Title:");
private JTextArea title = new JTextArea(20, 40);
public PopupFileName() {
setLayout(new BorderLayout());
add(titlel, BorderLayout.NORTH);
add(new JScrollPane(title));
}
public String getTitle() {
return title.getText();
}
public static String getTitle(Component parent) {
PopupFileName popupFileName = new PopupFileName();
int response = JOptionPane.showConfirmDialog(parent, popupFileName, "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
switch (response) {
case JOptionPane.OK_OPTION:
return popupFileName.getTitle();
default: return null;
}
}
}
}

user input for JLabel

I have a problem with a piece of code. When I click on it in my GUI, it reopens once I've inputted text. Can anyone explain to me what is wrong with the code. I'm using this to set a name in a JLabel in my GUI
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput;
String defaultUsername = "dom" + "baker";
usernameinput = JOptionPane.showInputDialog(
setNameButton, "Enter a username",
"Set username", JOptionPane.OK_CANCEL_OPTION);
{
username.setText(String.valueOf(usernameinput));
}
});
I've created a simple GUI to test your code and the dialog opens just once.
I have cleaned up a bit your listener, but basically it's the same code.
Your problem may be in another part of your code.
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SimpleFrameTest extends JFrame {
JLabel username = new JLabel("Press button to enter your name here");
public SimpleFrameTest() {
setSize(300, 300);
setTitle("Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
initComponents();
setVisible(true);
}
private void initComponents() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
username.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton setNameButton = new JButton("Set name");
setNameButton.setAlignmentX(Component.CENTER_ALIGNMENT);
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput = JOptionPane.showInputDialog(setNameButton, "Enter a username", "Set username", JOptionPane.OK_CANCEL_OPTION);
if (usernameinput != null) {
username.setText(String.valueOf(usernameinput));
}
});
panel.add(Box.createRigidArea(new Dimension(5,10)));
panel.add(username);
panel.add(Box.createRigidArea(new Dimension(5,10)));
panel.add(setNameButton);
add(panel);
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SimpleFrameTest();
}
});
}
}
your code is behaving like that because of this
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput;
String defaultUsername = "dom"
+ "baker";
usernameinput = JOptionPane.showInputDialog(null,
as you can see, the JOptionPane.showInputDialog(setNameButton is taking the setNameButton as a parameter so you are in some kind of recursive infinite loop
use another button for the modalDialog:
Example:
setNameButton.addActionListener((ActionEvent e) -> {
String usernameinput;
String defaultUsername = "dom"
+ "baker";
usernameinput = JOptionPane.showInputDialog(null, "Enter a username", "Set username", JOptionPane.OK_CANCEL_OPTION);
{
username.setText(String.valueOf(usernameinput));
}
});

How can I add text to combobox from textfield?

I want to create a combobox and a textbox. And user will enter a text into the textbox, and the text will be added as an item of combobox.
How can I do it? I wrote a code, but I couldn't find what will I write in actionlistener.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Q2 extends JFrame {
JTextField t;
JComboBox combobox = new JComboBox();
public Q2() {
t = new JTextField("Enter text here", 20);
t.setEditable(true);
t.addActionListener(new act());
add(t);
add(combobox);
combobox.addItem(t.getText().toString());
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public class act implements ActionListener {
public void actionPerformed(ActionEvent e) {
}
}
public static void main(String[] args) {
Q2 test = new Q2();
}
}
I added a button, and put the functionality on adding to the JComboBox on the button. Here's an example:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Q2 extends JFrame {
JTextField t;
JComboBox combobox;
JButton b;
public Q2() {
combobox = new JComboBox();
t = new JTextField("Enter text here", 20);
t.setEditable(true);
b = new JButton("Add");
b.addActionListener(new act()); //Add ActionListener to button instead.
add(t);
add(combobox);
add(b);
//combobox.addItem(t.getText().toString()); //Moved to ActionListener.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public class act implements ActionListener {
public void actionPerformed(ActionEvent e) {
combobox.addItem(t.getText()); //Removed .toString() because it returns a string.
}
}
public static void main(String[] args) {
Q2 test = new Q2();
}
}
private JTextComponent comboboxEditor;
Vector ComboData = new Vector();
public void addActionListners() {
//adding action listner to the NameComboBox
this.comboboxEditor = (JTextComponent) yourCombo.getEditor().getEditorComponent();
comboboxEditor.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
int i = evt.getKeyCode();
if (i == 10) {
//combobox action on enter
ComboData.add(comboboxEditor.getText());
yourCombo.setListData(ComboData);
}
}
});
}
you have to set your editable property in comboBox to true otherwise you wont able to write on comboBox. make sure you call addActionListners() method
at the startup(constructor). i am giving the combobox the functionality of a jtext field by changing the editor of the combobox to jtextComponent. try this example

Adding an int per click (java)

I am making a "fake virus" in java. when you run it a window called "Your computer has a virus" pops up and the window has a button that says "Your computer has (1) viruses. Click here to uninstall them" but when you click it one more window pops up. but i want it to be like each time you click it the number of "viruses" is added 1 to. (For example the second window that pops up after clicking button says "Your computer has (2) viruses"). I have tried to add it but it didn't work. (sorry for my terrible grammar). Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class FirstWindow extends JFrame {
int virusAmount = 1;
private static final long serialVersionUID = 1L;
public FirstWindow(){
super("Your computer has a virus");
setSize(400, 75);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
JButton b = new JButton("Your computer has (" + virusAmount++ + ") virus(es). Click here to uninstall them.");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FirstWindow f2 = new FirstWindow();
f2.setVisible(true);
}
});
p.add(b);
add(p);
}
}
Just define it in the constructor:
public FirstWindow(int i){}
Full example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FirstWindow extends JFrame {
int virusAmount;
private static final long serialVersionUID = 1L;
public FirstWindow(int i) {
virusAmount = i;
setSize(400, 75);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
JButton b;
if(virusAmount == 1){
b = new JButton("Your computer has a virus");
}
else{
b = new JButton("Your computer has (" + virusAmount + ") virus(es). Click here to uninstall them.");
}
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
FirstWindow f2 = new FirstWindow(virusAmount+1);
f2.setVisible(true);
}
});
p.add(b);
add(p);
}
}
public class Main {
public static void main(String[] args) {
FirstWindow fw = new FirstWindow(1);
fw.setVisible(true);
}
}

Should open new window while clicking a button?

I know that it is very simple question, but I can't find a solution.
I have a main swing dialog and other swing dialog. Main dialog has a button.
How can I make that after clicking a button the other dialog opens?
EDIT:
When I try this:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
NewJDialog okno = new NewJDialog();
okno.setVisible(true);
}
I get an error:
Cannot find symbol NewJDialog
The second window is named NewJDialog...
You'll surely want to look at How to Make Dialogs and review the JDialog API. Here's a short example to get started. You might compare it with what you're doing now.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class DialogTest extends JDialog implements ActionListener {
private static final String TITLE = "Season Test";
private enum Season {
WINTER("Winter"), SPRING("Spring"), SUMMER("Summer"), FALL("Fall");
private JRadioButton button;
private Season(String title) {
this.button = new JRadioButton(title);
}
}
private DialogTest(JFrame frame, String title) {
super(frame, title);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(0, 1, 8, 8));
ButtonGroup group = new ButtonGroup();
for (Season s : Season.values()) {
group.add(s.button);
radioPanel.add(s.button);
s.button.addActionListener(this);
}
Season.SPRING.button.setSelected(true);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.add(radioPanel);
this.pack();
this.setLocationRelativeTo(frame);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton b = (JRadioButton) e.getSource();
JOptionPane.showMessageDialog(null, "You chose: " + b.getText());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new DialogTest(null, TITLE);
}
});
}
}

Categories