java - 链接两个类
问题描述
我正在尝试结合两个课程。我想用 DON 类中的图像和一些按钮JFrame
创建一个。JLabel
当我按下其中一个按钮时,程序会调用另一个名为的类,该类inizio
将 my 的可见性设置jLabel
为false
。
当我使用添加的按钮调用类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);
}
}
解决方案
不必每次单击按钮时都创建一个新的 DON 对象,只需将inizio
句柄传递给已经存在的 JFrame。可能是这样的:
public class inizio {
public inizio(JFrame frame) {
frame.imageLabel.setVisible(false);
}
}
并更改此行:
start.addActionListener(e -> new inizio(imagePanel));
推荐阅读
- java - 任务:app:kaptDebugKotlin FAILED(错误:找不到符号) - Kotlin
- mysql - 将 Codeigniter 项目上传到 Cpanel subdmoin 会导致 DNS_Probe_Error
- laravel - 如何在laravel中使用代码索引特定数据库的表列
- javascript - 功能顺序是否有保证?
- ssl - 如何完全删除使用 openssl 创建的自签名证书
- apache-nifi - Nifi 无法建立与服务器的连接
- npm - 私人 npm 注册表的 npm 安装失败
- php - PHP循环数组和make
- 问题
- kubernetes - 我的 kubernetes pod 因临时存储问题而被驱逐
- flutter - 使用 Image Picker Flutter 从图库中获取视频的大小