How to Transfer Data From JFrame to another JFrame with this situation? - java

How can I transfer data into my other frame cause I'm doing If else statements in one Jbutton and so that the confirm button will also check the text fields that are empty and I also want it to act as a button to open my next frame then send that data to the next frame. My code doesn't seem to work other functions work and it also opens the other frame but doesn't display the data I need like: Name and will display the name in the other frame, need some help :(
JButton confirm = new JButton("Sign Up");
confirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
UserInfo a = new UserInfo();
if(!firstname.getText().trim().isEmpty() && !lastname.getText().trim().isEmpty() && password.getPassword().length != 0 && pass2.getPassword().length != 0
&& !address.getText().trim().isEmpty() ) {
String inputText = firstname.getText();
a.D1.setText(inputText);
a.frame2.setVisible(true);
frame.dispose(); }
else
if(firstname.getText().trim().isEmpty()) {
missingfirst.setText("Please Add Your First Name.");
}
if(lastname.getText().trim().isEmpty()) {
missinglast.setText("Please Add Your Last Name.");
}
if(address.getText().trim().isEmpty()) {
missingadd.setText("Please Enter An Address.");
}
if(password.getPassword().length == 0) {
missingpass.setText("Please Add A Password.");
}
if(pass2.getPassword().length == 0) {
missingrepass.setText("Please Re-Type Your Password.");
}
else if (!(password.getPassword().equals(pass2.getPassword()))) {
missingrepass.setText("Password Doesn't Match.");
}
}
This is my 2nd Frame

Related

Java - JLabel wont add when in a while loop

I am making a GUI Console with Java and Swing. It calls on the scanner to input text, then puts that text into a variable to give to the JFrame. The bolded code is the code in question.
The code works, but when you type in "change text", after putting in the required input, it does not add the JLabel to the JFrame.
Please Help! Thanks!
//prepare all imports
Random rand = new Random();
Scanner input = new Scanner(System.in);
JFrame myframe = new JFrame();
myframe.setSize(300, 300);
myframe.setTitle("Blank Window");
myframe.setResizable(false);
myframe.setLocation(300,300);
//*******************************************
boolean done = false;
boolean winopen = false;
System.out.println("Type commands here. Type 'help' for list of commands.");
while (done == false) {
System.out.print("Console > > > ");
String coninput = input.nextLine();
if (coninput.equals("window open")) {
System.out.println("Opening Window...");
System.out.println("Done!");
winopen = true;
myframe.setVisible(true);
}
if (coninput.equals("window close")) {
System.out.println("Closing Window...");
winopen = false;
myframe.setVisible(false);
System.out.println("Done!");
}
if (coninput.equals("exit")) {
System.out.println("Exiting...");
myframe.dispose();
done = true;
System.out.println("Done!");
}
if (coninput.equals("help")) {
System.out.println("Commands: ");
System.out.println("window open: opens a window");
System.out.println("window close: closes the open window");
System.out.println("exit: shuts down the program");
System.out.println("help: lists commands");
//System.out.println("");
//System.out.println("");
//System.out.println("");
}
**if (coninput.equals("change text") && winopen == true) {
System.out.print("What do you want the text to say > > > ");
JLabel text1 = new JLabel(input.nextLine());
System.out.println("Adding...");
myframe.add(text1);
}**
if (coninput.equals("change text") && winopen == false) {
System.out.print("You have to have a window open.");
}
}
}
}
First of, you need to structure your code in a better way. Secondly, it is better to use a swing container where the text (JLabel) will be added. Below Box is used, which is a container that uses BoxLayout as its layout manager, allowing multiple components (JLabels in your case) to be laid out either vertically (Y_AXIS) or horizontally (X_AXIS). You can then use JScrollPane to provide a scrollable view of the Box component, and add that JScrollPane instance to your frame. Every time you add a new text, you add it to the Box instance, and then you call repaint(); and revalidate(); on your frame for the text to be shown. If you need only the last text to be shown on the window (and not every text you have added), then uncomment box.removeAll(); as a quick fix. Otherwise, do not use the Box with the JScrollPane, but simply add the label to your frame e.g., myframe.getContentPane().add(lbl, BorderLayout.CENTER);. Again, remember to call myframe.getContentPane().removeAll(); before adding a new JLabel, as well as repaint(); and revalidate(); afterwards. Working example below:
import java.awt.*;
import javax.swing.*;
import java.util.Scanner;
public class App {
Scanner input;
JFrame myframe;
Box box;
JScrollPane scrollPane;
public App() {
input = new Scanner(System.in);
box = new Box(BoxLayout.Y_AXIS);
scrollPane = new JScrollPane(box);
myframe = new JFrame();
myframe.getContentPane().add(scrollPane, BorderLayout.CENTER);
myframe.setSize(300, 300);
myframe.setTitle("Blank Window");
myframe.setResizable(false);
myframe.setLocation(300, 300);
}
public void go() {
boolean done = false;
boolean winopen = false;
System.out.println("Type commands here. Type 'help' for list of commands.");
while (done == false) {
System.out.print("Console > > > ");
String coninput = input.nextLine();
if (coninput.equals("window open")) {
System.out.println("Opening Window...");
System.out.println("Done!");
winopen = true;
myframe.setVisible(true);
}
if (coninput.equals("window close")) {
System.out.println("Closing Window...");
winopen = false;
myframe.setVisible(false);
System.out.println("Done!");
}
if (coninput.equals("exit")) {
System.out.println("Exiting...");
myframe.dispose();
done = true;
System.out.println("Done!");
}
if (coninput.equals("help")) {
System.out.println("Commands: ");
System.out.println("window open: opens a window");
System.out.println("window close: closes the open window");
System.out.println("exit: shuts down the program");
System.out.println("help: lists commands");
}
if (coninput.equals("change text") && winopen == true) {
System.out.print("What do you want the text to say > > > ");
JLabel lbl = new JLabel(input.nextLine());
System.out.println("Adding...");
// box.removeAll();
box.add(lbl);
myframe.repaint();
myframe.revalidate();
Rectangle bounds = lbl.getBounds();
scrollPane.getViewport().scrollRectToVisible(bounds);// scroll to the new text
}
if (coninput.equals("change text") && winopen == false) {
System.out.print("You have to have a window open.");
}
}
}
public static void main(String[] args) {
new App().go();
}
}

Make code continue from same place in action performed

//boutton
ent.setBounds(490,400,100,50);
ent.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String text;
text=chatbox.getText().toLowerCase();
chatarea.append("\t\t\t\t"+text+" <- YOU \n");
chatbox.setText("");
if(text.contains("hii") || text.contains("hey") || text.contains("hi"))
{
bot("hey there");
bot("how can i help you?");
}
else if(text.contains("info") || text.contains("help") || text.contains("i need information") || text.contains("help me"))
{
bot("sure i am here to help you");
bot("what you want to know about?");
bot("1 info about anything?");
bot("2 info about place?");
bot("enter your choice : ");
if(text.contains("1")|| text.contains("info about anything") || text.contains("number 1") || text.contains("first one") || text.contains("first"))
{
bot("sure which blood group info you are looking for?");
}else if(text.contains("2") || text.contains("info about place") || text.contains("number 2") || text.contains("second one") || text.contains("second"))
else
{
bot("I Don't Understand you");
}
}
}
});
}
private void bot(String string)
{
chatarea.append("BOT -> "+string+"\n");
}
public static void main(String[] args)
{
new bot();
}
}
I am making a chat bot in which when I click on the JButton it takes the value from JTextField and posts it on a JTextArea. But the problem is I want my code to be continue not stop but every time click on button it start the code from starting.
How to make code continue from same place in action performed when I second time click on the button?
Add a boolean member to your botclass to keep track of the state (first time / not first time) and initialise it to true
boolean isFirstTimeButtonWasPressed = true
public void actionPerformed(ActionEvent e) {
if (isFirstTimeButtonWasPressed) {
//do stuff that should only happens the firs time
//...
isFirstTimeButtonWasPressed = false;
}
//do stuff that should be done every time the button is pressed
});

How do I call on information entered into a dialogue box as part of action listener?

I have an action listener attached to a JButton in my program.
When the button is clicked, a dialogue box opens that requests the user to enter a number, then click ok.
This part works fine, what I am having trouble doing is calling upon that number that the user has entered to use as part of an if statement.
Could someone please tell me how I call upon this number that the user has enterd, here is my code so far.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == t1) {
String Message = "Enter an Amount ";
String number = JOptionPane.showInputDialog(null, Message,
JOptionPane.QUESTION_MESSAGE);
}
if () { // ideally here i would want to say if the user number is bigger
// than 0 then do this...
}
}
after the changes my code now looks like this
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == t1)
{
String Message = "Enter an Amount ";
String number =
JOptionPane.showInputDialog(null,
Message,
JOptionPane.QUESTION_MESSAGE);
if(Integer.valueOf(number) > 0)
{
String s = a.gettext();
getContentPane().removeAll();
repaint();
new TaxiFrame(Integer.parseInt(s));
}
else{}
}
else{}
}
}
try {
//.Convert string to Integer
if (Integer.valueOf(number) > 0) {
//. Do that
} else {
//. Otherwise
}
} catch (NumberFormatException err) {
err.printStackTrace();
//.Conversion failed. The user entered a non numeric string
}

Return null when closing JDialog

I have a table that has a JDialog for add new record, When i click to add Button and want to add a new record and JDialog opened, I close JDialog window and it returns null for my all columns of my table rows.
This is my JDialog constructor:
public class AddBookDialog extends JDialog implements ActionListener {
public AddBookDialog(JFrame owner) {
super(owner, "Add New Book", true);
initComponents();
saveBtn.addActionListener(this);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == cancelBtn) dispose();
else if (e.getSource() == saveBtn) saveAction();
}
}
public void saveAction() {
if (nameTf.getText().trim().length() != 0) {
if (!haveDigit(nameTf.getText().trim())) setBookName(nameTf.getText().trim());
else {
JOptionPane.showMessageDialog(null, "Book Name have digit");
return;
}
} else {
JOptionPane.showMessageDialog(null, "Enter Book Name");
return;
}
if (isbnTf.getText().trim().length() != 0) {
if (haveSpace(isbnTf.getText().trim()) || haveLetter(isbnTf.getText().trim())) {
JOptionPane.showMessageDialog(null, "Enter Correct ISBN");
return;
}
setIsbn(isbnTf.getText().trim());
} else {
JOptionPane.showMessageDialog(null, "Enter Book ISBN");
return;
}
setBorrowStatus("No");
setDate(dateGenerate());
dispose();
}
I try to control this problem in my table GUI class:
public class BookPage_Admin extends JFrame implements ActionListener {
...
public void addAction() {
AddBookDialog dialog = new AddBookDialog(this);
if (dialog.getBookName() != null && dialog.getIsbn() != null && dialog.getBorrowStatus() != null &&
dialog.getDate() != null) {
Object[] added = new Object[]{dialog.getBookID(), dialog.getBookName(), dialog.getIsbn(), dialog.getBorrowStatus(), dialog.getDate()};
model.addRow(added);
}
}
}
But still when i close it, it returns null for my row.
How to prevent returning null when close it?
Just in case if no one will answer you:
When you initiate Dialog, aka AddBookDialog dialog = new AddBookDialog(this); you can override ActionListener on the Frame side like:
AddBookDialog dialog = new AddBookDialog(this);
dialog.setModal(true);
dialog.getSaveBtn().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] added = new Object[]{dialog.getBookID(), dialog.getBookName(), dialog.getIsbn(), dialog.getBorrowStatus(), dialog.getDate()};
model.addRow(added);
}
});
// importent set visible after ActionListener!!
dialog.setVisible(true);
Hope it will help,

Exiting system upon selecting the x button in the top right corner of a showMessageDialog box in Java?

I want to know how to cause a program to exit upon selecting the X button of a showMessageDialog dialog box.
Currently whenever I do this, it simply continues running the code or, in the case of confirm or option dialog boxes, selects the 'Yes' option. Is it possible to include this kind of command in the code for the dialog box? For example:
JOptionPane.showMessageDialog(null, "Your message here");
How would I edit the output so that the X button closes the program?
Will I have to change the showMessageDialog to another type of dialog box?
I dont know if is this what you want but i put a confirm box in a program:
(...)
import org.eclipse.swt.widgets.MessageBox;
(...)
createButton(buttons, "&Exit", "Exit", new MySelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent evt) {
MessageBox messageBox = new MessageBox(getShell(), SWT.YES | SWT.NO | SWT.ICON_QUESTION);
messageBox.setMessage("Are you sure?");
messageBox.setText("Exit");
if (messageBox.open() == SWT.YES) {
getParent().dispose();
}
}
});
And looking at online javadoc (java 6) or (java 1.4), you have another option:
Direct Use:
To create and use an JOptionPane directly, the standard pattern is roughly as follows:
JOptionPane pane = new JOptionPane(arguments);
pane.set.Xxxx(...); // Configure
JDialog dialog = pane.createDialog(parentComponent, title);
dialog.show();
Object selectedValue = pane.getValue();
if(selectedValue == null)
return CLOSED_OPTION;
//If there is not an array of option buttons:
if(options == null) {
if(selectedValue instanceof Integer)
return ((Integer)selectedValue).intValue();
return CLOSED_OPTION;
}
//If there is an array of option buttons:
for(int counter = 0, maxCounter = options.length;
counter < maxCounter; counter++) {
if(options[counter].equals(selectedValue))
return counter;
}
return CLOSED_OPTION;
showMessageDialog() doesn't have a return value. Here is an example with showOptionsDialog().
public class Test
{
public static void main(String[] args){
final JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Test");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int result = JOptionPane.showOptionDialog(null,
"Your message here", "", JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE, null, new String[] {"OK"}, "OK");
if (result == JOptionPane.CLOSED_OPTION) {
frame.dispose();
}
}
});
panel.add(button);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
}

Categories