I've read the similar questions regarding this problem, tried few methods but none is working.
I have 2 JFrame forms. I want to input information in the first form and submit it to the database. When I click a button, the second form will open and load the information
When I re-input new information in the first form and click the the button again, I want the second form to reload the new information inputted from the database.
This is my code so far.
time t = new time();
private void OrderButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(t.isVisible()){
t.dispose();
t.revalidate();
t.repaint();
t.setVisible(true);
t.setLocationRelativeTo(null);
}
else{
t.setVisible(true);
t.setLocationRelativeTo(null);
}
You don't need to play with JFrames for that. See below example :
JLabel toe = new JLabel("I'm primary text");
JFrame cow = new JFrame("Primary Window");
JPanel cowpanel = new JPanel();
cowpanel.add(toe);
cow.setContentPane(cowpanel);
cow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
cow.pack();
cow.setVisible(true);
JButton tow = new JButton("Change");
tow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
toe.setText("Hi!, I'm secondary text!");
}
});
JFrame dog = new JFrame("Secondary Window");
JPanel dogPanel = new JPanel();
dog.setContentPane(dogPanel);
dogPanel.add(tow);
dog.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
dog.pack();
dog.setVisible(true);
Clicking the 'Change' button from Frame 2 will change the JLabel's text in Frame 1.
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.
I am trying to make a text-based RPG and have a question about how to proceed the story dialogue (I'm still quite new to Java).
I want to change the content of text area by pressing a button so the dialog continues everytime you press the button.
For example, if there's a dialog like this,
Hello. I have never seen your face before.
You look like an adventurer.
So you also came to kill that wizard?
I want to display these texts one by one, not at once.
Here's my code:
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import java.awt.Container;
import javax.swing.*;
public class Dialogue extends JFrame implements ActionListener
{
//Window
JFrame window;
Container con;
//Font
Font basicfont;
Font bigfont;
Font timesnewroman;
//Main game screen
JPanel storyP;
JPanel inputP;
JPanel enterP;
//Main game screen Panel 3
JTextArea storyT;
//Main game screen Panel 5
JLabel inputA;
JTextField input;
JButton enterB;
public static void main(String[]args)
{
Dialogue game = new Dialogue();
game.setup();
}
public void setup()
{
window = new JFrame();
window.setBounds(0,0,1200,950);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.black);
window.setLayout(null); //Disabling the default layout.
window.setVisible(true);
basicfont = new Font("MS Gothic", Font.PLAIN, 24);
bigfont = new Font("MS Gothic", Font.BOLD, 28);
con = window.getContentPane();
// Panel Setup
storyP = new JPanel(); //This is where story text is displayed.
storyP.setBounds(50, 500, 800, 320);
storyP.setBackground(Color.white);
storyP.setLayout(new GridLayout());
inputP = new JPanel();
inputP.setBounds(50, 830, 500, 50);
inputP.setBackground(Color.black);
inputP.setLayout(new BorderLayout());
//p5.setLayout(new GridLayout());
enterP = new JPanel();
enterP.setBounds(600, 830, 120, 50);
enterP.setBackground(Color.black);
//STORY TEXT SETUP
storyT = new JTextArea();
storyT.setFont(basicfont);
storyT.setBackground(Color.black);
storyT.setForeground(Color.white);
storyT.setEditable(false);
//INPUT BOX SETUP
inputA = new JLabel(">");
inputA.setBackground(Color.black);
inputA.setForeground(Color.white);
inputA.setFont(bigfont);
input = new JTextField(15);
input.setBackground(Color.black);
input.setForeground(Color.white);
input.setBorder(null);
input.setFont(bigfont);
input.addActionListener(this);
enterB = new JButton("ENTER");
enterB.setFont(timesnewroman);
enterB.addActionListener(this);
//ADDING
storyP.add(storyT);
inputP.add("West",inputA);
inputP.add(input);
enterP.add(enterB);
//VISIBILITY
con.add(storyP);
con.add(inputP);
con.add(enterP);
Opening();
}
public void Opening()
{
storyT.setText("Hello. I have never seen your face before.");
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==enterB)
{
storyT.setText("You look like an adventurer.");
}
}
}
I could change the text from "Hello. I have never seen your face before" to "You look like an adventurer" by pressing ENTER button that I created.
But I don't know how to go further(to display "So you also came to kill that wizard?") from this point since my ENTER button's action is assigned to display a specific text ("You look like an adventurer").
I don't even know where to write the 3rd line so it is not written in this code yet.
There could be a counter and a loooong switch:
counter++;
switch(counter){
case 0: storyT.setText("You look like an adventurer.");
case 1: storyT.setText("So you also came to kill that wizard?");
case 2: ....
}
But it will be quite bad if you will have hunderds of texts.
For this i would use array of Strings or an ArrayList. then you can use counter to get to index of text to print
It will be much better if you will have these texts in a file. Than you can read it line by line with Scanner class.
Scanner sc = new Scanner(new File("texts.txt"));
ArrayList<String> texts = new ArrayList<String>();
while(sc.hasNextLine())
text.add(sc.nextLine());
sc.close();
it throws FileNotFoundException I think
Than your linstener content could be:
storyT.setText(texts.get(counter++));
The variable texts should be declared as an instance variable, not in method body:
private ArrayList<String> texts;
....
....
....
texts=new ArrayList<String>();
In your case, I'd do this...
declare a Stack.
Stack<String> texts = new Stack<String>();
A stack is like a physical stack. It has two main methods. Push(String a) and pop(). Push will put a String on top of the stack and pop() will return the String that is on the bottom.
In your main method, you simply fill this stack with the texts you want.
e.g.
texts.push("you look like an adventurer");
texts.push("etc..");
texts.push("etc..");
then, in you actionlistener, you just do this instead of what you had:
storyT.setText(texts.pop());
if you want some safety measures, you can do this:
if (texts.hasnext())
storyT.setText(texts.pop());
This checks if the stack still has texts stored up in it. If not, the stack won't be popped, in which case you'll get null, which isn't good.
After the password is entered i want the window to disappear and pop a new window.
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
if(passwordField.equals("test"))
{
frame.setVisible(false);
}
else if(!passwordField.equals("test"))
{
JOptionPane.showMessageDialog(null,"Access Denied!!");
}
}
});
btnEnter.setBounds(149, 184, 117, 29);
frame.getContentPane().add(btnEnter);
I'm assuming passwordField is a JTextField, if so, you need to get the text from it, just .getText() I think and store that in a string. Then test the string. At the moment you are testing if your JTextField equals the string.
Create 2 JFrames and make a reference for each one:
JFrame oldFrame = new JFrame();
// ...
JFrame newFrame = new JFrame();
// ...
// ...
if(passwordField.equals("test"))
{
oldFrame.setVisible(false);
newFrame.setVisible(true);
}
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.