How to transfer data between 2 frames in netbeans? - java

I'm using Netbeans 6.5.1 to create an application that involves transferring data between 2 frames, I mean the user will enter the data in the first frame and the data entered must be transferred to the second frame, without making the second frame visible. The second frame will not be visible initially and even after getting the data from the first frame it must not become visible till a certain button(from a different frame of the same project) is pressed. I tried overloading the constructor, but when I'm calling the method in frame-1 I'm unable to just store the data (and display it in a jLabel). I can only do this by using the setVisible() method as ( new Frame2(data_to_be_transferred).setVisible(true); ). This method does the job but it makes the second frame visible with the data. So how do I transfer the data between 2 frames without making the second frame visible?

You could either create your frame with the data Frame2 f2 = new Frame2(data_to_be_transferred); and then make it visible only when needed via f2.setVisible(true);
OR
keep your data to be transferred and only create the frame2 later on when really needed and make it immediately visible as you're already doing new Frame2(data_to_be_transferred).setVisible(true);
Cheers!

Example :
public class SomeClass extends JFrame {
JPanel panel;
JTextField textField;
JButton button;
JLabel label;
String data;
SomeClass() {
panel = new JPanel();
textField = new JTextField(16);
button = new JButton("Magic");
label = new JLabel();
panel.add(button);
panel.add(textField);
setContentPane(panel);
setSize(400,100);
setVisible(true);
}
public static void main(String[] args) {
new SomeClass();
}
button.addActionListener(e ->{
data = textField.getText();
if((data == null) || (data.equals(""))){
return;
}else {
this.remove(panel)
JPanel panel2 = new JPanel();
label = new JLabel();
panel.add(label);
this.setContentPane(panel2);
label.setText(data);
}
});
}
Sorry, I confused.. you can create new JFrame instance in actionPerformed or as I did in e-> which is lambda expression.
public class AnotherClass extends JFrame {
JPanel panel;
JLabel label;
AnotherClass() {
panel = new JPanel();
label = new JLabel();
panel.add(label);
setContentPane(panel);
setSize(400,100);
setVisible(true);
}
}
And then thought reference of AnotherClass ( frame 2 ) set value for label.
button.addActionListener(e ->{
data = textField.getText();
if((data == null) || (data.equals(""))){
return;
}else {
AnotherClass anotherClass = new AnotherClass();
anotherClass.label.setText(data);
}
});

Related

JLabel on JPanel not working [duplicate]

As an improvement to my encryption project I decided to make a little GUI. However, when I run the program, only the top element shows up on the screen and it appears to obscure the others, though I have no way of checking. Does anyone know why?
Below is my code in its entirety besides e() and d() because those simply encrypt a string and have nothing to do with a GUI. I would also like a way to speed it up as much as possible without editing the encryption, just to make it as great as possbile.
#SuppressWarnings("serial")
public class EncDecExample extends JFrame implements ActionListener {
final static JPanel top = new JPanel();
final static JPanel mid = new JPanel();
final static JPanel bot = new JPanel();
final static JTextField in = new JTextField(10);
final static JTextField out = new JTextField(10);
final static JButton enc = new JButton("Encrypt");
final static JButton dec = new JButton("Decrypt");
final static JFrame f = new JFrame("Encryption/decryption");
public static void main(String[] args) {
// EncDec.exampleImplement();
f.setSize(500, 500);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
out.setEditable(false);
out.setText("Hello");
in.setVisible(true);
out.setVisible(true);
enc.setVisible(true);
dec.setVisible(true);
top.add(in);
mid.add(enc);
mid.add(dec);
bot.add(out);
f.add(top);
f.add(mid);
f.add(bot);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == enc && !in.getText().equalsIgnoreCase("")) {
out.setText(EncDec.e(in.getText(), 5));
}
else if(e.getSource() == dec && !in.getText().equalsIgnoreCase("")) {
out.setText(EncDec.d(in.getText()));
}
}
}
The content pane of a JFrame has a BorderLayout. If you place a component in a BL with no constraints it ends up in the CENTER. The center can only display one component.
For an immediate effect, I suggest:
f.add(top, BorderLayout.PAGE_START);
f.add(mid);
f.add(bot, BorderLayout.PAGE_END);
Other points.
Take out f.setSize(500, 500); and call pack() immediately before setVisible(true)
For a better way to end the GUI, change f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
in.setVisible(true); Except for the frame itself, take these out. A component automatically becomes visible when it is added to a top level container and that container is itself made visible.
Change public class EncDecExample extends JFrame to public class EncDecExample This code keeps a reference to a frame, and that is the right way to go.

dynamically new added fields are overlapping [duplicate]

As an improvement to my encryption project I decided to make a little GUI. However, when I run the program, only the top element shows up on the screen and it appears to obscure the others, though I have no way of checking. Does anyone know why?
Below is my code in its entirety besides e() and d() because those simply encrypt a string and have nothing to do with a GUI. I would also like a way to speed it up as much as possible without editing the encryption, just to make it as great as possbile.
#SuppressWarnings("serial")
public class EncDecExample extends JFrame implements ActionListener {
final static JPanel top = new JPanel();
final static JPanel mid = new JPanel();
final static JPanel bot = new JPanel();
final static JTextField in = new JTextField(10);
final static JTextField out = new JTextField(10);
final static JButton enc = new JButton("Encrypt");
final static JButton dec = new JButton("Decrypt");
final static JFrame f = new JFrame("Encryption/decryption");
public static void main(String[] args) {
// EncDec.exampleImplement();
f.setSize(500, 500);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
out.setEditable(false);
out.setText("Hello");
in.setVisible(true);
out.setVisible(true);
enc.setVisible(true);
dec.setVisible(true);
top.add(in);
mid.add(enc);
mid.add(dec);
bot.add(out);
f.add(top);
f.add(mid);
f.add(bot);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == enc && !in.getText().equalsIgnoreCase("")) {
out.setText(EncDec.e(in.getText(), 5));
}
else if(e.getSource() == dec && !in.getText().equalsIgnoreCase("")) {
out.setText(EncDec.d(in.getText()));
}
}
}
The content pane of a JFrame has a BorderLayout. If you place a component in a BL with no constraints it ends up in the CENTER. The center can only display one component.
For an immediate effect, I suggest:
f.add(top, BorderLayout.PAGE_START);
f.add(mid);
f.add(bot, BorderLayout.PAGE_END);
Other points.
Take out f.setSize(500, 500); and call pack() immediately before setVisible(true)
For a better way to end the GUI, change f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
in.setVisible(true); Except for the frame itself, take these out. A component automatically becomes visible when it is added to a top level container and that container is itself made visible.
Change public class EncDecExample extends JFrame to public class EncDecExample This code keeps a reference to a frame, and that is the right way to go.

Clear a JPanel from a JFrame

I'm working on an assignment for class where we need to create a JComboBox and each option opens a new window where you can do whatever you want on those new windows. Please keep in mind I'm very new to GUI and new to Java in general, in case my questions are dumb.
I have a question and an issue...
My question:
When the user selects "The Matrix" option a new window pops up with a quote and two buttons. Right now I have two JPanels (panel and panel2) panel adds the quote to the NORTH position and then panel2 adds the two buttons to the CENTER position both using BorderLayout. My question is am I doing this correctly...Could I use just panel to add the quote and the buttons or is it necessary to create separate panels for separate items being added to the JFrame? When I had them both added to the same panel the quote was not on the window when I ran the program.
panel.add(matrixQuote);
newFrame.add(panel, BorderLayout.NORTH);
That's how I had it when it wasn't showing up ^^^
I GOT THE ISSUE WITH CLEARING THE JFRAME FIXED
I am trying to add an ActionListener to the bluePill button and instead of opening another new window I thought I could clear everything from the existing window when the button is pressed and then display something new on said window. The only info I could find on this is how I have it in the actionPerformed method below. I'll post a snippet of what I'm talking about directly below and then all my code below that just in case.
All my code...
public class MultiForm extends JFrame{
private JComboBox menu;
private JButton bluePill;
private JButton redPill;
private JLabel matrixQuote;
private int matrixSelection;
private JFrame newFrame;
private JPanel panel;
private JPanel panel2;
private static String[] fileName = {"", "The Matrix", "Another Option"};
public MultiForm() {
super("Multi Form Program");
setLayout(new FlowLayout());
menu = new JComboBox(fileName);
add(menu);
TheHandler handler = new TheHandler();
menu.addItemListener(handler);
}
public void matrixPanel() {
TheHandler handler = new TheHandler();
//Create a new window when "The Matrix" is clicked in the JCB
newFrame = new JFrame();
panel = new JPanel();
panel2 = new JPanel();
newFrame.setLayout(new FlowLayout());
newFrame.setSize(500, 300);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
matrixQuote = new JLabel("<html>After this, there is no turning back. "
+ "<br>You take the blue pill—the story ends, you wake up "
+ "<br>in your bed and believe whatever you want to believe."
+ "<br>You take the red pill—you stay in Wonderland, and I show"
+ "<br>you how deep the rabbit hole goes. Remember: all I'm "
+ "<br>offering is the truth. Nothing more.</html>");
panel2.add(matrixQuote);
newFrame.add(panel2, BorderLayout.NORTH);
//Blue pill button and picture.
Icon bp = new ImageIcon(getClass().getResource("Blue Pill.png"));
bluePill = new JButton("Blue Pill", bp);
panel2.add(bluePill);
bluePill.addActionListener(handler);
//Red pill button and picture
Icon rp = new ImageIcon(getClass().getResource("Red Pill.png"));
redPill = new JButton("Red Pill", rp);
panel2.add(redPill);
newFrame.add(panel2, BorderLayout.CENTER);
newFrame.setVisible(true);
}
private class TheHandler implements ItemListener, ActionListener{
public void itemStateChanged(ItemEvent IE) {
//listen for an item to be selected.
if(IE.getStateChange() == ItemEvent.SELECTED) {
Object selection = menu.getSelectedItem();
if("The Matrix".equals(selection)) {
matrixPanel();
}
else if("Another Option".equals(selection)) {
}
}
}
public void actionPerformed(ActionEvent AE) {
if(AE.getSource() == bluePill) {
newFrame.remove(panel);
newFrame.remove(panel2);
newFrame.repaint();
}
}
}
//MAIN
public static void main(String[] args) {
MultiForm go = new MultiForm();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(400, 200);
go.setVisible(true);
}
}
Use a Card Layout. You can swap panels as required.
The tutorial has a working example.
You can use:
jpanel.removeAll();
Either to delete a certain JComponent by using the JComponent itself like:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
frame.remove(panel);
panel.getGraphics().clearRect(0, 0, panel.getWidth(), panel.getHeight());

Using .setVisible() outside the constructor breaks my GUI

I am just now learning the basics of java GUI. I have this weird situation that I can't really explain.
I have a GUI class, where I build a simple JFrame. If I use .setVisible(true) within the constructor everything works fine, if I use it outside, nothing loads (the window is visible, but the buttons and what not aren't).
Why is this happening ?
public class GUI extends JFrame {
private JTextField humanYears_TextField = new JTextField(3);
private JTextField dogYears_TextField = new JTextField(3);
private JButton convert_Button = new JButton("Convert");
private JLabel greeting = new JLabel ("Dog years to Human years!");
public GUI () {
JFrame window = new JFrame();
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(this.greeting);
content.add(new JLabel("Dog Years: "));
content.add(this.dogYears_TextField);
content.add(this.convert_Button);
content.add(new JLabel("Human Years: "));
content.add(this.humanYears_TextField);
window.setContentPane(content);
pack(); // aplica contentPane-ul
window.setLocationRelativeTo(null);
window.setTitle("Dog Year Converter");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true); // IF IT'S HERE IT WORKS
}
}
public static void main(String[] args) {
GUI dogYears = new GUI();
//dogYears.setVisible(true); // IF IT'S HERE
//NOTHING EXCEPT THE WINDOW LOADS
}
Why is this happening ?
In this example it doesn't matter, but what if I want to make a window visible only if I click a button or something ?
1) You create 2 instances of JFrame the first from extending JFrame on the class and the second from JFrame window=... You than go on to call setVisible(..) on the window and in your main you attempt to call setVisible(...) on your dogYears.
Solution
You should only create one JFrame per Swing GUI. Get rid of the extends JFrame (and the code that goes with it), as its not good practice to extend JFrame in Swing. Thus of course you wont be able to call setVisible(true) in your constructor which is fine either call it after creating the GUI in the constructor or make a method like setVisible in GUI class which will be a wrapper for your JFrames setVisble(boolean b) method.
Other suggestions
Always create your Swing components on the Event Dispatch Thread which you should do in via SwingUtilitites.invokeLater(Runnable r) block. Have a read on Concurrency in Swing.
Remember to call pack before setting JFrame visible and after adding components.
setLocationRelativeTo(..) should come after pack().
Better to use JFrame.DISPOSE_ON_CLOSE unless using Timers.
Also no need for setContentPane simply call add(..) on JFrame instance.
Here is your code with above mentioned fixes:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class GUI {
private JTextField humanYears_TextField = new JTextField(3);
private JTextField dogYears_TextField = new JTextField(3);
private JButton convert_Button = new JButton("Convert");
private JLabel greeting = new JLabel("Dog years to Human years!");
private JFrame window = new JFrame();
private JPanel content = new JPanel();
public GUI() {
content.setLayout(new FlowLayout());
content.add(this.greeting);
content.add(new JLabel("Dog Years: "));
content.add(this.dogYears_TextField);
content.add(this.convert_Button);
content.add(new JLabel("Human Years: "));
content.add(this.humanYears_TextField);
window.add(content);
window.setTitle("Dog Year Converter");
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
window.pack();
window.setLocationRelativeTo(null);
//window.setVisible(true); //works here now
}
//our wrapper method so we can change visibility of our frame from outside the class
void setVisible(boolean visible) {
window.setVisible(visible);
}
public static void main(String[] args) {
//Create Swing components on EDT
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI dogYears = new GUI();
dogYears.setVisible(true);//works here too
}
});
}
}
You've got two JFrames, the GUI class itself and the internal variable "window". Use only one.
Make sure that GUI does not extend JFrame (there's no need for this), and give the class a public void setVisible(boolean) method that sets the window to visible.
public class GUI {
private JTextField humanYears_TextField = new JTextField(3);
private JTextField dogYears_TextField = new JTextField(3);
private JButton convert_Button = new JButton("Convert");
private JLabel greeting = new JLabel ("Dog years to Human years!");
private JFrame window = new JFrame();
public GUI () {
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(this.greeting);
content.add(new JLabel("Dog Years: "));
content.add(this.dogYears_TextField);
content.add(this.convert_Button);
content.add(new JLabel("Human Years: "));
content.add(this.humanYears_TextField);
window.setContentPane(content);
pack(); // aplica contentPane-ul
window.setLocationRelativeTo(null);
window.setTitle("Dog Year Converter");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// window.setVisible(true); // IF IT'S HERE IT WORKS
}
public void setVisible(boolean visible) {
window.setVisible(visible);
}
}
You have two different instances :-)
in your constructor:
JFrame window = new JFrame();
window.setVisible(true); // IF IT'S HERE IT WORKS
in your main:
GUI dogYears = new GUI();
dogYears.setVisible(true);
// dogYears != local var window in constructor
Which might get me starting on not extending classes, but using them.
Your class GUI extends from a JFrame, but in the constructor, you are initializing another JFrame, which results in having two different JFrames.
Try this:
public class GUI {
private JTextField humanYears_TextField = new JTextField(3);
private JTextField dogYears_TextField = new JTextField(3);
private JButton convert_Button = new JButton("Convert");
private JLabel greeting = new JLabel ("Dog years to Human years!");
public GUI () {
JFrame window = new JFrame();
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(this.greeting);
content.add(new JLabel("Dog Years: "));
content.add(this.dogYears_TextField);
content.add(this.convert_Button);
content.add(new JLabel("Human Years: "));
content.add(this.humanYears_TextField);
window.setContentPane(content);
pack(); // aplica contentPane-ul
window.setLocationRelativeTo(null);
window.setTitle("Dog Year Converter");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
// main
}
you are creating an instance of JFrame in constructor of GUI which also extends JFRame.
Now you are creating different components and added them on 'window' object.
As you know a frame is set as visible= false and undecorated=false.
So to set a particular JFrame instance you need to call setVisible() method on that instance.
Here you are just creating an instance of GUI and didn't added any component on it.
write a statement in constructor as following rather than "window.setContentPane(content);":
setContentPane(content);
and then call setVisible() method on your instance of GUI class i.e d*ogYears.setVisible(true);*!!

Java Swing: How can I implement a login screen before showing a JFrame?

I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?
A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!
Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.
Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).

Categories

Resources