【问题标题】:passing frame as parameter in method在方法中将帧作为参数传递
【发布时间】:2017-05-07 10:50:16
【问题描述】:

我想在方法中传递一个 JFrame 作为参数, 有可能吗?

这就是我想要的:

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);
        }
    });
}

【问题讨论】:

  • 你想在哪一行传递JFrame?
  • 你要传递一个对象还是一个类?
  • 您的问题并不清楚,正如上面@granmirupa 所指出的那样,所以如果您告诉并显示更多细节,这将对所有人都有帮助。附带说明一下,您似乎正在使用 MouseListener,而应该使用 ActionListener。
  • 在第 1 行 @Itamar_Green
  • @HovercraftFullOfEels "看起来你正在使用 MouseListener,而应该使用 ActionListener。" 没错,但动作监听器需要与 JButton 一起使用,而 OP 似乎正在将鼠标侦听器添加到 JLabel。 OP:使用JButton 作为组件并使用ActionListener 来检测该按钮的鼠标键盘输入。

标签: java swing


【解决方案1】:

在这种情况下您不应该发送 Class,如果您想了解更多关于发送 class 作为参数的信息,请查看Passing class as parameter

既然你想传递 JFrame 作为参数,你可以简单地写methodName(JFrame frame),否则如果你只想制作新的 JFrame,你不需要传递它,只需在方法中创建一个新的:

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

所以你可以看到没有必要在 other 中传递一个 Class 来创建该类的对象。

这里您可以看到如何将 JFrame 作为参数传递并创建新 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);
}

取消注释 makeNewJFrame(new JLabel("You opened new JFrame")); 以查看打开新 JFrame 的工作原理。

【讨论】:

    【解决方案2】:
    c ma = new c();
    

    首先类名应该:

    1. 以大写字符开头
    2. 具有描述性

    我想在方法中传递一个 JFrame 作为参数,可以这样做吗?

    无需将帧作为参数传递,您可以使用以下代码访问当前帧:

    Component component = (Component)evt.getSource();
    Window window = SwingUtilities.windowForComponent( component );
    window.setVisible( false );
    

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 2010-11-16
      • 2013-02-20
      • 2010-10-06
      • 2014-10-25
      • 2017-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多