-2

i want to pass a JFrame as parameter in a method, is it possible to do that ?

here is what i want :

private void mouseClickedButtonsActions(JLabel l, Class c){
    l.addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            c ma = new c();
            ma.setVisible(true);
            setVisible(false);
        }
    });
}
mohamed.bc
  • 47
  • 4
  • 10

2 Answers2

0

You shouldn't be sending Class in this situation, if you want to learn more about sending class as parameter check this out Passing class as parameter.

Now since you want to pass JFrame as parameter you can simply write methodName(JFrame frame), otherwise if you just want to make new JFrame you don't need to pass it but just create new one inside method:

myMethod(){
   JFrame frame = new JFrame();
   // Do something with it
}

So as you can see there is no need to pass an Class in other to make object of that class.

Here you can see example of how to pass JFrame as parameter and make new JFrame:

public void jframe() {

    JFrame frame = new JFrame("Frame 1");
    JButton btn = new JButton("Click Me");
    ActionListener al = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            jframeAsParam(new JLabel("You added label to old JFrame"), frame);
            //makeNewJFrame(new JLabel("You opened new JFrame"));
        }
    };
    btn.addActionListener(al);
    JPanel panel = new JPanel(new GridLayout(2, 1));

    panel.add(btn);
    frame.setContentPane(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 250);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

public void jframeAsParam(JLabel lbl, JFrame frame) {
    frame.getContentPane().add(lbl);
    frame.setVisible(true);
}

public void makeNewJFrame(JLabel lbl) {
    JFrame frame = new JFrame("Frame 2");
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(lbl, BorderLayout.CENTER);
    frame.setContentPane(panel);    
    frame.setSize(300, 250);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

Uncomment makeNewJFrame(new JLabel("You opened new JFrame")); to see how opening new JFrame works.

Community
  • 1
  • 1
FilipRistic
  • 2,661
  • 4
  • 22
  • 31
0
c ma = new c();

First of all class names should:

  1. Start with an upper case character
  2. Be descriptive

i want to pass a JFrame as parameter in a method, is it possible to do that ?

There is no need to pass the frame as a parameter you can access the current frame by using code like:

Component component = (Component)evt.getSource();
Window window = SwingUtilities.windowForComponent( component );
window.setVisible( false );
camickr
  • 321,443
  • 19
  • 166
  • 288