首页 > 解决方案 > 链接两个类

问题描述

我正在尝试结合两个课程。我想用 DON 类中的图像和一些按钮JFrame创建一个。JLabel当我按下其中一个按钮时,程序会调用另一个名为的类,该类inizio将 my 的可见性设置jLabelfalse

当我使用添加的按钮调用类inizio时,程序还会创建一个新的Jframe,给我留下 2 个或更多(基于我按下按钮的次数)。

这是因为我在 DON 类中放入了创建 JFrame 的指令。我怎样才能解决这个问题?

这是我的程序:

唐级

import javax.swing.*;

public class DON  {
  public JFrame finestra;
  public JPanel imagePanel;
  public JLabel imageLabel;

  public  void rbeg() {

    }

   public DON() {
        //Impostazioni finestra
        finestra = new JFrame("JFRAME EXAMPLE");
        Container con = finestra.getContentPane();
        finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GridBagLayout layout = new GridBagLayout();
        finestra.setResizable(false);
        finestra.setSize(1280, 720);

        ImageIcon ICONA = new ImageIcon(getClass().getClassLoader().getResource("logo.png"));
        finestra.setIconImage(ICONA.getImage());
        con.setBackground(Color.black);






        //Jpanel for images
        GridBagConstraints c = new GridBagConstraints();
        imagePanel = new JPanel();
        imagePanel.setLayout(layout);

        //Impostazioni label e ImageIcon


        ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("menu.png")); 



         imageLabel= new JLabel(icon);
        c.gridx = 0;
        c.gridy = 0;
        c.weightx = 1;
        c.weighty = 1;
        layout.setConstraints(imageLabel, c);
        imageLabel.setOpaque(true);

        imagePanel.add(imageLabel);
        //JBUTTONS 
        Insets paddingBottone = new Insets(10,25,10,25);
        //Button Jpanel
        JPanel pannelloBottoni = new JPanel();
        pannelloBottoni.setLayout(layout);

        c.gridx = 1;
        c.gridy = 0;
        c.insets = new Insets(3,3,60,3);

        layout.setConstraints(pannelloBottoni, c);
       //BUTTON 1 ( Start )
        JButton start = new JButton("Start!");
        c.gridx = 0;
        c.gridy = 0;
        layout.setConstraints(start, c);
        start.setMargin(paddingBottone);
        pannelloBottoni.add(start);
        start.addActionListener(e -> new inizio());
        imagePanel.add(pannelloBottoni);
        con.add(imagePanel);
        finestra.setVisible(true);
        }

   public static void main(String args[]) {
      new DON();
   }
}

inizio 类

public class inizio {
    public inizio() {
        DON a = new DON();
        a.rbeg();
        a.imageLabel.setVisible(false);

        }
}

标签: javauser-interface

解决方案


不必每次单击按钮时都创建一个新的 DON 对象,只需将inizio句柄传递给已经存在的 JFrame。可能是这样的:

public class inizio {
    public inizio(JFrame frame) {
        frame.imageLabel.setVisible(false);
        }
}

并更改此行:

start.addActionListener(e -> new inizio(imagePanel));

推荐阅读