0

I want to make a simple addition program. In it I want to pass variables from Main_Window to Second_Window for addition and I want to get result on Second_Window multiple times. Means If I pass variables multiple times from Main_Window for addition then result should be on Second_Window not third and fourth Window.

Here I want All changes should be show on Second_Window not another on open.

Here I want All changes should be show on <code>Second_Window</code> not another on open.

These lines are written for passing variables from Main_Window.

Second_Window s = new Second_Window(a,b);
s.setVisible(true);
Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • 1
    For better help sooner post a proper [mcve], I think you need to create a method and pass the new numbers to it, then that method adds them and displays them on your screen...BTW see: [The use of multiple JFrames, Good/Bad practice?](https://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-or-bad-practice) – Frakcool Feb 15 '18 at 13:37
  • Do you mean if button click on main window the first time, it creates the second window, and when click from the second time onwards, it update the already showing second window instead of creating a new window? – Antony Ng Feb 15 '18 at 15:22
  • Don't keep creating a second window. Instead you need to create one SecondWindow class. Then you need to add a method to this class like `addMoreData(...)` which accepts the data you want to display on the window. – camickr Feb 15 '18 at 15:30
  • Yes, Antony Ng . You are Right... Please tell me how can I do this. ? – Ashu Ansari Feb 15 '18 at 16:42

2 Answers2

1

I'm going to take my code from my previous answer to one of your questions as my base code and add some functionality to it:

First of all, you need to create one and only one instance of your second window and have a method that can update the angles sent to it.

How do you do that you might be asking yourself, well it's easy, in your action listener you create the instance if the second frame was not created yet and updated it otherwise.

private ActionListener listener = e -> {
    if (e.getSource().equals(submitButton)) {
        if (!frame.isVisible()) {
            circle = new MyCircle((Integer) box1.getSelectedItem(), (Integer) box2.getSelectedItem());
            frame.add(circle);
            frame.pack();
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        } else {
            circle.updateAngles((Integer) box1.getSelectedItem(), (Integer) box2.getSelectedItem());
        }
    }
};

Note:

If you close the second window all previous data will be lost, if you want to save that state, then play with the frame visibility and initialize the MyCircle instance in the createAndShowGui() method in the code below.


Next thing is you need to keep track of all the angles you've added, for that you might need a List and iterate over it, or paint that to a BufferedImage and then paint that image on the JPanel. For this example we'll be using the List option.

However, for this example, if the data is too much, it might not display, to correct that, use a JScrollPane as well, however I'm leaving that up to you.

This example as well, makes the whole program to terminate only when you close the main window, but not if you close the second window.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class RadiusDrawer {
    private JFrame frame;
    private JFrame mainFrame;
    private int centerX = 50;
    private int centerY = 50;
    private int x1 = 0;
    private int y1 = 0;
    private int x2 = 0;
    private int y2 = 0;
    private int r = 100;

    private JComboBox<Integer> box1;
    private JComboBox<Integer> box2;
    private JLabel label1;
    private JLabel label2;
    private JButton submitButton;

    MyCircle circle;

    private static final Integer[] ANGLES = new Integer[]{15, 30, 45, 60, 75, 90};

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new RadiusDrawer()::createAndShowGui);
    }

    private void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());
        mainFrame = new JFrame("Main Frame");

        mainFrame.add(createMainWindow());
        mainFrame.pack();
        mainFrame.setVisible(true);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private ActionListener listener = e -> {
        if (e.getSource().equals(submitButton)) {
            if (!frame.isVisible()) {
                circle = new MyCircle((Integer) box1.getSelectedItem(), (Integer) box2.getSelectedItem());
                frame.add(circle);
                frame.pack();
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            } else {
                circle.updateAngles((Integer) box1.getSelectedItem(), (Integer) box2.getSelectedItem());
            }
        }
    };

    private JPanel createMainWindow() {
        JPanel pane = new JPanel();

        box1 = new JComboBox<>(ANGLES);
        box2 = new JComboBox<>(ANGLES);

        label1 = new JLabel("Angle 1");
        label2 = new JLabel("Angle 2");

        submitButton = new JButton("Submit");

        submitButton.addActionListener(listener);

        pane.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(20, 30, 20, 30);
        pane.add(box1, gbc);

        gbc.gridx = 1;
        pane.add(box2, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        pane.add(label1, gbc);

        gbc.gridx = 1;
        pane.add(label2, gbc);

        gbc.gridy = 2;
        pane.add(submitButton, gbc);

        return pane;
    }

    @SuppressWarnings("serial")
    class MyCircle extends JPanel {
        int cx = 0;
        int cy = 0;
        double lineX = 0;
        double lineY = 0;
        double roundedX = 0;
        double roundedY = 0;
        int angle1 = 0;
        int angle2 = 0;

        int angle1HistoryX = 15;
        int angle2HistoryX = 150;
        int angleHistoryY = 300;
        int angleHistoryYGap = 20;

        Color angle1Color = Color.BLUE;
        Color angle2Color = Color.RED;

        List <Integer> angle1History;
        List <Integer> angle2History;

        public MyCircle(int angle1, int angle2) {
            this.angle1 = angle1;
            this.angle2 = angle2;

            angle1History = new ArrayList<>();
            angle2History = new ArrayList<>();

            angle1History.add(angle1);
            angle2History.add(angle2);

            calculateCoords();
            calculateCenter();
        }

        private void updateAngles(int angle1, int angle2) {
            this.angle1 = angle1;
            this.angle2 = angle2;

            angle1History.add(angle1);
            angle2History.add(angle2);
            calculateCoords();

            this.revalidate();
            this.repaint();
        }

        private void calculateCoords() {
            x1 = (int) (r * Math.cos(Math.toRadians(angle1)));
            y1 = (int) (r * Math.sin(Math.toRadians(angle1))) * -1;

            x2 = (int) (r * Math.cos(Math.toRadians(angle2)));
            y2 = (int) (r * Math.sin(Math.toRadians(angle2))) * -1;
        }

        private void calculateCenter() {
            cx = centerX + r;
            cy = centerY + r;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;

            drawCircle(g2d, centerX, centerY, r);
            drawRadius(g2d);
            drawHistory(g2d);
        }

        private void drawCircle(Graphics2D g2d, int x, int y, int r) {
            g2d.setColor(Color.BLACK);
            g2d.draw(new Ellipse2D.Double(x, y, r * 2, r * 2));
        }

        private void drawRadius(Graphics2D g2d) {
            g2d.setColor(angle1Color);
            g2d.draw(new Line2D.Double(cx, cy, cx + x1, cy + y1));

            g2d.setColor(angle2Color);
            g2d.draw(new Line2D.Double(cx, cy, cx + x2, cy + y2));
        }

        private void drawHistory(Graphics2D g2d) {
            g2d.setColor(angle1Color);
            g2d.drawString("Angle1", angle1HistoryX, angleHistoryY);
            for (int i = 0; i < angle1History.size(); i++) {
                g2d.drawString(angle1History.get(i).toString(), angle1HistoryX, angleHistoryY + (angleHistoryYGap * (i + 1)));
            }

            g2d.setColor(angle2Color);
            g2d.drawString("Angle2", angle2HistoryX, angleHistoryY);
            for (int i = 0; i < angle2History.size(); i++) {
                g2d.drawString(angle2History.get(i).toString(), angle2HistoryX, angleHistoryY + (angleHistoryYGap * (i + 1)));
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 600);
        }
    }
}

That's it!

enter image description here enter image description here

Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • 1
    If this answer was helpful for you and answered your question be sure to [accept it](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Frakcool Feb 15 '18 at 17:25
0

So basically you want to keep the second window to maximum one instance (or zero if the button in main window is never clicked), to do this you need to keep a static reference to the second window, if this reference already exists, you don't create a new one, but ask the existing one to display the calculation result.

A possible approach:

For the submit button in main window, you gather the values of the required parameters, and call the static method of the second window class. A static method is a method that belongs to a class, not an object.

    btnSubmit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent aE) {
            int azimuth = ...;
            int elevation = ...;

            SecondWindow.showResult(azimuth, elevation);
        }
    });

In the second window class, it keeps a static instance of this class, it is null initially. When showResult() is called, it checks if the instance isn't yet exists, then create a new second window and assign to the static reference. And it asks the instance to calculate and display the result in UI.

public class SecondWindow extends JFrame {
    private static SecondWindow instance = null;

    public static void showResult(int azimuth, int elevation) {
        if (instance == null) {
            instance = new SecondWindow();
        }

        instance.performShowResult(azimuth, elevation);
    }

    private void performShowResult(int azimuth, int elevation) {
        // Display the result in UI.
    }
}

The last thing to consider is whether you want to set the instance to null when it has been closed? If yes, add this code to the second window constructor:

public SecondWindow() {
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent aE) {
            instance = null;
        }
    });
}

So when showResult() is called again, a new second window will be created.

If you think the creation of second window is somewhat "heavy", then you can just keep the second window closed (thus not set the instance to null), but ensure it is shown when showResult() is called. Like this:

public static void showResult(int azimuth, int elevation) {
    if (instance == null) {
        instance = new SecondWindow();
    } else if (instance.isShowing() == false) {
        instance.setVisible(true);
    }

    instance.performShowResult(azimuth, elevation);
}
Antony Ng
  • 767
  • 8
  • 16