JAVA - I have 2 windows and i need to close 1 window - java

My java program is opening new window when i press one button in first window. Then i need to close first window. When i try to close first window with System.exit(0); it closes second window. I tryed setVisible(false); then first window doesn't close. Please help!
Whole code:
public class NameChooser extends JFrame implements ActionListener {
public NameChooser() {
RunNC();
}
public final void RunNC() {
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter your name that will be shown in game!");
label.setBounds(20, 10, 500, 25);
panel.add(label);
JLabel error = new JLabel("");
error.setForeground(Color.red);
panel.add(error);
JTextField name = new JTextField(30);
name.setBounds(50, 40, 180, 25);
panel.add(name);
JButton playButton = new JButton( new AbstractAction("Play") {
#Override
public void actionPerformed(ActionEvent e) {
String enteredname = name.getText();
if("".equals(enteredname)) {
error.setVisible(true);
error.setText("Invalid name!");
error.setBounds(105, 95, 100, 25);
System.out.println("Invalid name!");
}
else if(enteredname.length() > 10) {
error.setVisible(true);
error.setText("Name cant have more than 10 characters!");
error.setBounds(25, 95, 600, 25);
System.out.println("Name cant have more than 10 characters!");
}
error.setVisible(false);
GameWindow game = new GameWindow();
game.StartGame();
// I need to close window on this line!
}
});
playButton.setBounds(110, 70, 60, 25);
panel.add(playButton);
}
Any help?

Your problem is caused because System.exit() causes the Java VM to terminate completely - and both of your windows are running on the same VM instance.
Use Jframe.dispose() instead on the one you want to close.

System.exit(0);
doesn't "close a window", it terminates the JVM in which your entire application is running, hence, it terminates the entire application.
If we're talking about JFrames, try by using the dispose() method to close your seperate screens.
If you want us to comment on your setVisible(false), show us the code where you call it, it might be you're calling it on the wrong variable.

Related

How to store and display user input in JList?

I don't know what I am doing wrong. I am trying to take a JTextField user input to be stored and displayed in a JList, but every time the button is pressed to store the user input the JList remains blank. Any help would be greatly appreciated.
DefaultListModel<String> model = new DefaultListModel<String>();
menuList = new JList<String>(model);
menuList.setBounds(500, 65, 300, 400);
menuList.setSelectionBackground(Color.LIGHT_GRAY);
menuList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
btnCreateMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
childFrame = new JFrame("New Menu");
childFrame.setBounds(340, 300, 400, 200);
childFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
childFrame.getContentPane().setLayout(null);
childFrame.setVisible(true);
lblNewMenu = new JLabel("Menu Name:");
lblNewMenu.setBounds(30, 60, 200, 20);
childFrame.getContentPane().add(lblNewMenu);
input = new JTextField();
String userInput = input.getText();
input.setBounds(lblNewMenu.getX() + 80, lblNewMenu.getY(), 250, 30);
childFrame.getContentPane().add(input);
btnMenuInput = new JButton("Create New Menu");
btnMenuInput.setBounds(120, 100, 200, 30);
btnMenuInput.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
model.addElement(userInput);
menuList.setModel(model);
childFrame.setVisible(false);
Entree selectedEntree = (Entree)cboEntrees.getSelectedItem();
Side selectedSide = (Side)cboSides.getSelectedItem();
Salad selectedSalad = (Salad)cboSalads.getSelectedItem();
Dessert selectedDessert = (Dessert)cboDesserts.getSelectedItem();
Menu menu = new Menu(userInput, selectedEntree, selectedSide, selectedSalad, selectedDessert);
menuArray.add(menu);
}
});
childFrame.getContentPane().add(btnMenuInput);
}
});
mainframe.setVisible(true);
This line
userInput = input.getText();
needs to be called first in the ActionListener. Otherwise you never get the latest String from the text field.
e.g.,
public void actionPerformed(ActionEvent e){
userInput = input.getText();
model.addElement(userInput);
//menuList.setModel(model); // not needed
Also, as mentioned by camickr in comment, avoid using null layouts and setBounds as this fights against the Swing GUI library rather than working with it, making it much harder to create flexible easy to update and edit GUI's.
Also, the childFrame top-level window should be a JDialog and not a second JFrame. Please see The Use of Multiple JFrames: Good or Bad Practice? for more on this.
Also note that you should create the entire dialog or Frame before you make it visible, or else some of the items may not be visible at first.
Another problem is the use of JFrame.HIDE_ON_CLOSE. You should probably be using DISPOSE_ON_CLOSE instead. Otherwise the frame will just be hidden, but will still exist, possibly for the life of the program.

Java loop only if checkbox is selected

private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 148, 120);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
while(chckbxNewCheckBox.isSelected()){
try {
Robot auto = new Robot();
auto.delay(2300);
auto.mouseMove(377, 182);
auto.mousePress(InputEvent.BUTTON3_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);
//
auto.delay(1000);
auto.mouseMove(466, 293);
auto.mousePress(InputEvent.BUTTON1_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
//
auto.delay(1000);
auto.mouseMove(1061, 217);
auto.mousePress(InputEvent.BUTTON1_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
//
auto.delay(8000);
auto.mouseMove(601, 493);
auto.mousePress(InputEvent.BUTTON1_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
//
auto.delay(60000);
auto.mouseMove(387, 355);
auto.mousePress(InputEvent.BUTTON1_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
//
auto.delay(8000);
auto.mouseMove(705, 652);
auto.mousePress(InputEvent.BUTTON1_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
} catch (AWTException e) {
e.printStackTrace();
}
}
} });
btnStart.setBounds(10, 47, 89, 23);
frame.getContentPane().add(btnStart);
JCheckBox chckbxNewCheckBox = new JCheckBox("New check box");
chckbxNewCheckBox.setBounds(2, 7, 97, 23);
frame.getContentPane().add(chckbxNewCheckBox);
}
I'd like some advice on putting the commands for my robot in a loop and the loop only execute when a checkbox is selected. I've tried a few different ways of doing it but none seem to be working. I'm sure I'm missing something simple but I can't seem to find what it was. Although doing it for me would help, explaining it would be great too. I am using eclipse, and the windowbuilder to add items.
Use threads:
You can run your commands in a different thread. The UI will be running in its own thread.
you could write you code in you new thread as ;
Class Robot implements Runnable{
public void run(){
while(programRunning)){
if(checkBox.isSelected())
{
//Perform commands.
}
else {// you may choose to sleep this thread here as well in case of not selected}
}
}
}
programRunning is another variable you can choose so as to keep the loop running even if the checkbox is not selected and the UI is program/application is still running.
You can do something like this:
while(CheckBox.isSelected()) {
// do the stuff
}
Update: I now understand the question. It is good to run long period task in a separate thread, so here you can use SwingWorker to perform the task. If you don't use thread, then the UI became hang by the while loop

Improper Alignment Error with Java AWT. Cannot get my label to move

I have put a label into my frame, but it refuses to move. SetBounds() is not working, and I get an improper alignment error if I put any argument past "Result" below that isn't 0, 1, or 2, none of which put it in the correct place. Here's where I declare the Label:
Label result = new Label("Result.", 3);
Here's the SetBounds statement:
result.setBounds(0, 1500, 100, 20);
This program I am writing, I simply just want to have the user input 2 numbers, add them, and print the result using GUI components. The result is the label which refuses to change. The code of the entire program is below, and the program is still not done yet, but if you compile it, result is always stuck to the left and I want it to be at the same level as the TextFields. This problem is actually happening with the other labels, Help1, and Help2. Please don't tell me I have to use swing! I dislike swing.
I have yet to change the event to where it adds the user inputs. I copied the event from a previous program.
The code: (Sorry for no comments, but it's not a huge program)
import java.awt.*;
import java.awt.event.*;
public class MouseClick {
TextField number1;
TextField number2;
public static void main(String[] args) {
MouseClick MC = new MouseClick();
}
public MouseClick() {
Frame f = new Frame("Addition Time!");
Button button = new Button("Click Here To Add The Two Numbers.");
button.setBounds(175, 250, 230, 30);
button.addMouseListener(new MyMouseListener());
f.add(button);
Label help1 = new Label("Enter the first number below.");
Label help2 = new Label("Enter the second number below.");
Label exprsn1 = new Label("+", 0);
Label exprsn2 = new Label("=", 0);
Label result = new Label("Result.", 3);
number1 = new TextField("TextField1", 100);
number2 = new TextField("TextField2", 100);
help1.setBounds(50, 80, 150, 20);
help2.setBounds(250, 80, 150, 20);
exprsn1.setBounds(00, 80, 30, 30);
exprsn2.setBounds(00, 80, 30, 30);
number1.setBounds(50, 100, 100, 20);
number2.setBounds(250, 100, 100, 20);
result.setBounds(0, 1500, 100, 20);
f.add(number1);
f.add(number2);
f.add(help1);
f.add(help2);
f.add(result);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
f.setSize(600, 300);
f.setVisible(true);
}
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
String S = number1.getText();
number2.setText(S);
}
}
}
The error is because 3 is not an allowed value for parameter "alignment" in the constructor
Label(String text, int alignment)
Are you getting confused with TextField() which has a similar constructor?
TextField(String text, int columns)
The reason the label is not appearing in the correct location is because you've not specified your using null layout explicitly. You need this line:
public MouseClick() {
Frame f = new Frame("Addition Time!");
f.setLayout(null); // add this line

Java Window Duplication Prevention

JButton btnNewButton = new JButton("Register Student");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
RegisterStudent panel_1 = new RegisterStudent();
panel_1.setVisible(true);
}
});
btnNewButton.setBounds(0, 162, 167, 37);
panel.add(btnNewButton);
Is there a way, that IF one specific window is open already, it cant be opened once again?
Because, i don't want the user to click on a button several times, causing several windows to be opened with the same content?
Create the panel_1 variable outside of the mouse listener block and initialize it to null. When the mouse is clicked, check if panel_1 is null, and if it is, create it.
final RegisterStudent panel_1 = new RegisterStudent();
JButton btnNewButton = new JButton("Register Student");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
panel_1.setVisible(true);
}
});
btnNewButton.setBounds(0, 162, 167, 37);
panel.add(btnNewButton);
You can get an array of all open windows from Window.getWindows() since 1.6 or all open Frames with Frame.getFrames() since 1.2. You can use the name property or the window class (RegisterStudent) to test if the windows is already open and set the focus on it instead open another one.

expected ), illegal start of expression

I can't get my program to compile!
i think im missing a curly brace but can't for the life of me see where!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.text.*;
import java.net.*;
import java.util.Scanner;
public class AddressBook extends JFrame
{
FlowLayout leftLayout;
JFrame frame;
JPanel panel;
JTextField txtname,txtsurname, txtphone, txtmobile, txtaddress, txtpostcode;
JButton btnadd, btnnext, btnprevious, btnsave, btndelete;
JLabel jlbname, jlbsurname, jlbphone, jlbmobile, jlbaddress, jlbpostcode;
String fileInput,readline;
ArrayList<String> arrayOfFile = new ArrayList<String>();
ArrayList<Contact> records = new ArrayList<Contact>();
int index = 0;
public static void main(String[] args) throws IOException
{
new AddressBook();
}
public AddressBook()
{
//sets window
frame = new JFrame();
frame.setTitle("Bournemouth University Address Book");
frame.setSize(760, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//sets up panel
panel = new JPanel();
panel.setLayout(null);
frame.getContentPane().add(panel);
//Labels
jlbname = new JLabel("Name:");
jlbname.setBounds(10, 50, 100, 20);
panel.add(jlbname);
jlbsurname = new JLabel("Surname:");
jlbsurname.setBounds(350, 50, 100, 20);
panel.add(jlbsurname);
jlbphone = new JLabel("Home Number:");
jlbphone.setBounds(10, 90, 150, 20);
panel.add(jlbphone);
jlbmobile = new JLabel("Mobile:");
jlbmobile.setBounds(350, 90, 150, 20);
panel.add(jlbmobile);
jlbaddress = new JLabel("Address:");
jlbaddress.setBounds(10, 130, 200, 20);
panel.add(jlbaddress);
jlbpostcode = new JLabel("PostCode:");
jlbpostcode.setBounds(10, 170, 250, 20);
panel.add(jlbpostcode);
//Text Fields
txtname = new JTextField("");
txtname.setBounds(120, 50, 200, 20);
panel.add(txtname);
txtsurname = new JTextField("");
txtsurname.setBounds(440, 50, 200, 20);
panel.add(txtsurname);
txtphone = new JTextField("");
txtphone.setBounds(120, 90, 200, 20);
panel.add(txtphone);
txtmobile = new JTextField("");
txtmobile.setBounds(440, 90, 200, 20);
panel.add(txtmobile);
txtaddress = new JTextField("");
txtaddress.setBounds(120, 130, 520, 20);
panel.add(txtaddress);
txtpostcode = new JTextField("");
txtpostcode.setBounds(120, 170, 250, 20);
panel.add(txtpostcode);
//Buttons
btnadd = new JButton("Add", new ImageIcon("../files/add.png"));
btnadd.setBounds(330, 320, 100, 50);
btnadd.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnadd.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
txtname.setText("Add new details here");
txtsurname.setText("");
txtphone.setText("");
txtmobile.setText("");
txtaddress.setText("");
txtpostcode.setText("");
}
});
panel.add(btnadd);
btndelete = new JButton("Delete", new ImageIcon("../files/delete2.png"));
btndelete.setBounds(390, 250, 100, 50);
btndelete.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btndelete.setForeground(Color.red);
// btndelete.addActionListener(this);
panel.add(btndelete);
btnsave = new JButton("Save", new ImageIcon("../files/save.png"));
btnsave.setBounds(490, 250, 100, 50);
btnsave.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnsave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
BufferedWriter fileOut = new BufferedWriter(new FileWriter("../files/contacts.buab", true));
fileOut.append(txtname.getText());
fileOut.append("\n");
fileOut.append(txtsurname.getText());
fileOut.append("\n");
fileOut.append(txtphone.getText());
fileOut.append("\n");
fileOut.append(txtmobile.getText());
fileOut.append("\n");
fileOut.append(txtaddress.getText());
fileOut.append("\n");
fileOut.append(txtpostcode.getText() + "\r");
fileOut.close();
}
catch (IOException ioe)
{
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
}
});
panel.add(btnsave);
btnprevious = new JButton("Prev", new ImageIcon("../files/left.png"));
btnprevious.setBounds(280, 250, 100, 50);
btnprevious.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnprevious.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent event)
{
index--;
displaycontact();
}
});
panel.add(btnprevious);
btnnext = new JButton("Next", new ImageIcon("../files/right.png"));
btnnext.setBounds(180, 250, 100, 50);
btnnext.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnnext.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
index ++;
displaycontact();
}
});
panel.add(btnnext);
frame.setVisible(true);
panel.setVisible(true);
JMenuBar mb = new JMenuBar();
frame.setJMenuBar(mb);
JMenu insert = new JMenu("Import");
mb.add(insert);
JMenuItem imp = new JMenuItem("Add New Contacts");
insert.add(imp);
imp.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent event)
{
JFileChooser fileopen = new JFileChooser();
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION)
{
try {
BufferedReader fileStream = new BufferedReader(new FileReader("src/contacts.buab"));
while (true)
{
String fileInput = fileStream.readLine();
if(fileInput==null)
break;
Contact a = new Contact();
a.setname(fileInput);
a.setsurname(fileStream.readline());
a.setphone(fileStream.readLine());
a.setmobile(fileStream.readLine());
a.setaddress(fileStream.readLine());
a.setpostcode(fileStream.readline());
Contacts.add(a);
System.out.println(a.getname());
}
fileStream.close();
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
displaycontact();
}});
}
public void displaycontact()
{
txtname.setText(contacts.get(index).name);
txtsurname.SetText(contacts.get(index).surname);
txtphone.setText(contacts.get(index).phone);
txtmobile.setText(contacts.get(index).mobile);
txtAddress.setText(contacts.get(index).address);
}
}
}
please help i've been here for 3 hours!!
You are missing a curly brace here:
displaycontact();
}}}); // <- HERE
This is nearly impossible to see with your code because it is formatted very poorly. You should use a text editor which highlights matching braces. This lets you see quickly what that closing brace closes.
I advise you to reformat the code so that there is proper indentation. You have quite a lot of indentation so you may want to consider using two spaces or a tab size with the tab width set to two. Proper indentation lets you scan the code veritcally to see where the braces are closing things.
I reformatted your code in Eclipse and the ActionListener which is causing your problem now looks like this:
imp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFileChooser fileopen = new JFileChooser();
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
try {
BufferedReader fileStream = new BufferedReader(new FileReader("src/contacts.buab"));
while (true) {
String fileInput = fileStream.readLine();
if (fileInput == null)
break;
Contact a = new Contact();
a.setname(fileInput);
a.setsurname(fileStream.readline());
a.setphone(fileStream.readLine());
a.setmobile(fileStream.readLine());
a.setaddress(fileStream.readLine());
a.setpostcode(fileStream.readline());
Contacts.add(a);
System.out.println(a.getname());
}
fileStream.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ioe.getMessage());
}
displaycontact();
}
}
});
Notice that the last curly brace blob is now in three lines and that each line is less indented than the previous? This would make it immediately obvious where you were missing a curly brace.
new should be all lower-case
ioe should be ex
Remove the bottom-most curly-bracket
Add one more closing curly bracket after JOptionPane.showMessageDialog(null, ioe.getMessage()); displaycontact();
Use the prescribed coding conventions, especially the indentation ones
You appear to have a spurious open curly brace in front of public void actionPerformed.
But really, you need to be able to sort these out yourself. You can't post your code to SO every time it doesn't compile... Something that may help here is an editor that can do folding (just about every IDE would do this), or even the functionality that vi has when you press % on a brace/bracket/quote etc. (which jumps to the closing symbol letting you match up start and end).
Plus, whenever you ask a question, always provide the diagnostic information - which in this case would be the compiler output. It's basically rude to expect people to help you while withholding pertinent information.
You're short one closing curly brace after the last displaycontact();
You then need to remove the final curly brace.
addiosamigo, I would really recommend that you be able to deal with these kinds of errors youself, since it will help you much more in the future.
To help in that, here are the steps that I would take to solve this kind of thing:
Delete all the code from the file, except the minimum necessary to compile. See if this compiles (if not, you have a serious problem that's not part of the code. Perhaps a problem with a project definition or something).
Start adding code back in very small chunks.
Each time you add code back, make sure it compiles.
Eventually, you'll add something that doesn't compile, and you'll know the bad code is there.
Please note that doing this is not always so simple, since sometimes you need to add code in a certain order for it to compile.
For example, adding the code for function Foo, which calls function Bar, without adding the code for Bar will obviously cause a compile error. In this kind of case, you'll have to do smart tricks (like adding Bar back in, without any actual implementation, etc).
All in all, the strategy is the same as for every bug: find the smallest case that reproduces it, and work from there.
Hope this helps
The if statement
if (ret == JFileChooser.APPROVE_OPTION)
is missing it's closing brace, you must add it just after
displaycontact();
at the end of the source is an extra brace.
A few hints to help yourself in the future:
make sure your code indenting is correct, fixing your whitespacing and indenting would have lead you to the culprit
anonymous classes can make code unreadable if they consist of more than a few lines, your action listener is a fine example of this. code becomes much more readable if you create a separate nested class for it instead of inserting large anonymous classes.
Edit: to get started have a look at Sun's Java code conventions like and its indenting chapter. IDE's like eclipse supoort formatting and indenting of your code too.

Categories