Linking two frames in java - java

I am creating a java application which consists of two frames(JFrame1 and JFrame2)
JFrame1 has a grid 6x6 button; and JFrame2 has 6 radio buttons representing colours. How can I link the two frames so that when a button in JFrame1 is clicked, JFrame2 pops up and when a colour is chosen from that the JFrame2 closes and the clicked button gets the respective colour?

It is better to have one JFrame for every application. Use one for the 6x6 JButtons and create a modal JDialog for your color JRadioButtons.
The color selection JDialog should have a public getSelectedColor() method in order to return the selected color to the caller class.
Instantiate the ColorDialog in main and do not set it visible.
The ActionListener of each JButton should make the modal JDialog visible.
The RadioButton ActionPerformed should set the selected color and make the JDialog invisible.
Call getSelectedColor() and apply the returned color to your JButton.

In your frame1's button action listner, you can do something like this
public void actionPerformed(ActionEvent e) {
Frame2 frame = new Frame2(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
where "this" refers to the frame1 object. This is you can access its jTEXTFIELD and jBUTTONs from the second frame. So naturally you have store it in Frame1 object declared in your second class.
Suppose you have a clickable color field in frame2 object, once you click on it, you should trigger a function that get the input field from frame1 (using your locale object reference) and store it in it. something like this:
public void actionPerformed(ActionEvent e) {
frame1.getMyTextField().setText(WHAT_THE_CLICKED_ON);
this.close();
}
Sorry if I made any syntax errors, it's been a long time I didnt work with java :)

Just create another class, let us say FrameMananger, then use the singleton pattern to manage them.
Then in any class, you can use FrameManager.getFrame1() to get the frame1, same as the frame2. You can add logic judgement inside, like dynamically dispose some frame or only create them when needed.
This issue is fairly common concept when you create a game and try to navigate between your every view(like the show score panel from everywhere).
public class FrameManager
{
Frame1 frame1;
Frame1 frame2;
public static Frame1 getFrame1()
{
if(frame1 == null)
frame1 = new Frame1();
return frame1;
}
public static Frame1 getFrame2()
{
if(frame2 == null)
frame2 = new Frame1();
return frame2;
}
public class Frame1 extends JFrame
{
}
public class Frame2 extends JFrame
{
}
}

Related

How to call setVisible from another class?

What I have:
Two Classes that instantiate two JFrames.
What I am trying to achieve:
One with a button and the other that will become invisible when a action is fired on the button.
Problems:
I do not know how to pursue this. How should I go about coding this?
Class 1
public class test1{
public static void main(String[] args){
JFrame frame = new JFrame("Blinkly Frame");
frame.setSize(100, 100);
frame.setVisible(true);
}
}
Class 2
public class test2{
public static void main(String[] args){
JButton button = new JButton();
//when i will click this button i want to make invisible frame
}
}
Solution:
Create an instance of the class that has a Jframe or extends a JFrame.
First we need the JFrame that will be disappearing.
public class BClass extends JFrame{
// Disappearing frame
public BClass()
{
this.setSize(300,300);//sets frame properties
this.setLocationRelativeTo(null);
}
}
Next we need the Frame that will be holding the buttons. (Documentation added)
public class ACLass {
public static void main(String[] args) {
JFrame frame = new JFrame("Magician"); // instantiates
BClass b = new BClass(); // instantiates class that extends JFrame
b.setVisible(true);//
frame.setSize(300,300);//
frame.setVisible(true);//
frame.setLocationRelativeTo(null);//
JButton disappearButton = new JButton("Disappear"); //Adds button
disappearButton.addActionListener(new ActionListener() { // Adds action -When button is "clicked"
public void actionPerformed(ActionEvent e) { // method called when action fired
b.setVisible(false); //visibility changed
}
});
disappearButton.setBounds(0,0,300,150);
JButton appearButton = new JButton("appear"); //Adds button
appearButton.addActionListener(new ActionListener() { // Adds action -When button is "clicked"
public void actionPerformed(ActionEvent e) { // method called when action fired
b.setVisible(true); //visibility changed
}
});
disappearButton.setBounds(0,100,300,150);
frame.add(disappearButton, BorderLayout.PAGE_START); //adds button to frame
frame.add(appearButton, BorderLayout.PAGE_END); //adds button to frame
//I used border layout however use the a layout manager that works with your components/frame
}
}
Exotic Explanation
I'm going to explain this in terms of a magic show as it provides better understanding.
So first, we have one magician(JFrame) and his wand(JButton) and then we have the helper(the second JFrame) that will disappear and a stage that has been set(all properties defined etc.)
First the magician adds some magic power to his wand(actionListener that handles the button being pushed) that will react when the magician waves it(action fired a.k.a button being pushed).
Next we show the audience the helper(instantiating JFrame to disappear).
As we have shown the audience the helper, we can now show him/her disappearing (Now we can call setVisible through the instance variable of the class).
Finally, the magician waves his wand(firing an action), and the helper gets the signal(actionPerformed method) to disappear. The helper then can call the
b.setVisible(false); //making the frame invisible
General Explanation
https://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html
Basically, by instantiating an object in another class you can also call the objects methods in that class i.e. setVisible(boolean b).
Other less preferable solutions:
If your disappearing class has does not extend a JFrame but instantiates one..
You would need to create an instance variable
private JFrame j;
Then use getters/setters to access the object which will then allow you to call its methods.
secondClass.getFrame().setVisible(true);//getFrame returns the JFrame
Then add that to the actionPerformed method.
You can also use a static instance variable and statically reference it in the actionPerformed method... (not recommended)
secondClass.frame.setVisible(true);

Resize Jframe using external frame

What I have done is created a form that has a table displaying inventory. When an item is right clicked, a popup menu is shown where the user can click edit inventory edit (JFrame will resize to (988, 736)). A Panel will be loaded from an external class with buttons and labels. What I am trying to achieve here is when the user clicks save, a hidden "Close" button becomes visible. Once the close button is clicked then the panel will be set invisible and what I also need it to do is set the JFrame back to its original size (988, 430). How do I go about achieving this (Setting the JFrame back to (988, 430) from the External Class)?
Here is the code I have for it so far:
On this event button below i would like to insert the coding to resize the JFrame. This coding is in the class (SV2.java)
private void btn_closeActionPerformed(java.awt.event.ActionEvent evt)
{
SV1 objc = new SV1();
Panel.setVisible(false);
objc.getContentPane().setPreferredSize(new Dimension(988,430));
objc.getContentPane().setSize(new Dimension(988, 430));
// coding to resize JFrame in class SV1.java, from setting it within this class
}
In SV2.java:
//Add instance variable for parent
private JFrame parent;
//Add JFrame to the constructor
public SV2(SomeType someParameter, OtherType foo, JFrame parent) {
this.parent = parent;
//rest of constructor code...
}
//Use JFrame to resize
private void btn_closeActionPerformed(ActionEvent evt) {
parent.setSize(988, 430);
//rest of code triggered by close button...
}
In the class that calls the panel:
//Pass the frame when instantiating the SV2 object
new SV2(yourParameter1, yourOtherParameter, frame);

how to access one JFrame to another class JFrame

I have a problem.
I am creating two JFrames in different classes in the same package in eclipse. In the first JFrame class I have different JButtons for different uses.
In the first JButton, the name is "View user profile" after clicking this button some event is performed. the event occurs when the button is pressed that is another JFrame visible and this JFrame shows all user information which user is login. but this JFrame not show all the user details present in the database.
Because this showing an error for accessing another class (JFrame) variable like JButton, JLabel, etc.
Please help me. How can I access different class variables in another class.
"please help me how can i accesss different class varible in another class."
First See The Use of Multiple JFrames, Good/Bad Practice?
I would instead use a modal JDialog. See How to make Dialogs.
To access the components in the GUI class, you can just pass it as reference to the JDialog class, with getters for the components you want to access.
Here's an example of what I mean. You can see the JLabel from the GUI class is accessed through the getJLabel method from the GUI class.
public class GUI {
private JLabel label;
private MyDialog dialog;
private JFrame frame;
public GUI() {
JButtton button = new JButton("Button");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
dialog = new JDialog(frame, true, GUI.this);
}
});
}
#Override
public JLabel getJLabel() {
return label;
}
}
public class MyDialog extends JDialog {
private GUI gui;
public MyDialog(final JFrame frame, boolean modal, GUI gui) {
super(frame, modal);
this.gui = gui;
JButton button = new JButton("Button");
button.addActionListener(MyListener());
}
private MyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JLabel label = gui.getJLabel();
label.setText("Hello");
}
}
}

Enable a jframe when a vin

I made a JFrame in Java (Netbeans) with a button. When pressing that button another JFrame opens and the first frame has setEnabled to false. When I close my second Frame, I want the first one to be enabled again.... how can I do that?
Assuming you have JFrame subclass objects, you can pass your first frame as an argument to your second frame, and enable the first frame again in the close event of your second frame.
MyJFrame class:
private MyJFrame alphaFrame;
public MyJFrame(MyJFrame alpha) {
alphaFrame = alpha;
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
alphaFrame.setEnabled(true);
}
});
}
You can then instantiate your second frame (from the first, I assume) with something like this:
MyJFrame secondFrame = new MyJFrame(this);

Performing action when closing JFrame

In my program I have a main JFrame that holds a button. When this button is clicked a new JFrame appears in which I can change some information. Whenever I finish editing I press a save button on the new JFrame which saves the changes and disposes the JFrame. Now when this is done, I'd like to perform an action in the main JFrame as well, but only if something changed. If I open the new JFrame and just close it again without using the save button, I don't want to do anything in the main frame.
I've tried searching the web for a solution, but just don't seem to be anything useful out there..
An example of the code I've got so far:
Main Frame...
public class MainFrame extends JFrame
{
public MainFrame()
{
super("Main Frame");
JButton details = new JButton("Add Detail");
add(details);
details.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
new DetailFrame().setVisible(true);
}
});
}
}
Detail Frame...
public class DetailFrame extends JFrame
{
public DetailFrame()
{
super("Detail Frame");
JButton save = new JButton("Save");
add(save);
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
// Save whatever content
dispose();
}
});
}
}
So when I click the "Save" button on the Detail Frame, I want to do something in the Main Frame, whereas when the "x" is clicked on the Detail Frame, I don't want to do anything..
Hope someone is able to help me, and sorry for my english..
You can pass a MainFrame handle to the DetailFrame constructor. Then, on clicking the Save button, the DetailFrame would call a function in MainFrame and pass the changes to it.
Another way is to create a public boolean variable in DetailFrame and set it to true when the Save button is clicked. This way MainFrame will know whether the DetailFrame was closed or Save'd.
EDIT: Some more ideas:
Use JDialog instead of JFrame. JDialog.setVisible is modal, i.e. it will block the calling function until the dialog is closed; this way you can process the results of the dialog in the same "Details" button listener.
To access the dialog after it is called, store the dialog in a separate variable. First construct the dialog, then show it, and then process the result by analyzing its variables.
Store the results of editing in other public variables of DetailFrame (or let's call it DetailDialog). This should happen only when the "Save" button is clicked. This may even allow to go without the boolean variable (depends on the types of values you are editing).
DetailDialog dlg = new DetailDialog();
dlg.setVisible(true);
if(dlg.approvedResult != null) {
// process the result...
}
EDIT: Sorry, JDialog is not modal by default. Need to call a special super constructor to make it modal.
Also, here you will have to pass the reference to MainFrame to the dialog constructor, but you still can declare it as a simple JFrame and avoid unnecessary dependencies.
To get the reference to the enclosing MainFrame from within the anonymous ActionListener, use MainFrame.this.
To be able to change the button text after it was created, you will have to store the button in a member variable.
Main Frame...
public class MainFrame extends JFrame
{
private JButton details = new JButton("Add Detail");
public MainFrame()
{
super("Main Frame");
getContentPane().add(details);
details.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
DetailDialog dlg = new DetailDialog(MainFrame.this);
dlg.setVisible(true);
if(dlg.approved){
details.setText("Edit Detail");
}
}
});
}
}
Detail Dialog... (not Frame)
public class DetailDialog extends JDialog
{
public boolean approved = false;
public DetailDialog(JFrame parent)
{
super(parent,"Detail Dialog",true); // modal dialog parented to the calling frame
JButton save = new JButton("Save");
getContentPane().add(save);
save.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
// Save whatever content
approved = true;
dispose();
}
});
}
}
Create the detail frame in the main frame, and add a windowlistener to it, using the windowadapter class. Implement the windowclosing event by checking for changes, handle those, and then dispose the detail frame. This is all done in the mainframe.
The detail frame should have do nothing on close set to prevent the detail frame being disposed before you recorded the changes.
You may wish to implement checking for changes in the detailframe as a method returning a class holding the interesting data. That way your windowlistener can be small an to the point.
Forget the 2nd JFrame. use a modal dialog instead. It will block input until dismissed. Once dismissed, the only thing to do is decide whether to update the original data. JOptionPane has some inbuilt functionality that makes that easy. If the user presses Cancel or the esc key, the showInputDialog() method will return null as the result.
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
class EditInfo {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JFrame f = new JFrame("Uneditable");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new BorderLayout(10,10));
final JTextField tf = new JTextField("Hello World!", 20);
tf.setEnabled(false);
p.add(tf, BorderLayout.CENTER);
JButton edit = new JButton("Edit");
edit.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
String result = JOptionPane.showInputDialog(
f,
"Edit text",
tf.getText());
if (result!=null) {
tf.setText(result);
}
}
} );
p.add(edit, BorderLayout.EAST);
p.setBorder(new EmptyBorder(10,10,10,10));
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
If it is necessary to edit a number of fields all at once in the JOptionPane, use a JPanel to contain them all, and put them in a showMessageDialog() call. Check the integer based return result to determine if the user OK'd the changes.

Categories

Resources