gpt4 book ai didi

java - Swing 面板颜色变化

转载 作者:行者123 更新时间:2023-11-30 04:23:44 25 4
gpt4 key购买 nike

我正在尝试使用我创建的名为子面板的自定义面板启动多个JFrame。 [如果您对命名感到好奇,我有另一个名为 masterpanel 的类,其中包含一个按钮,用于启动包含 subpanel 新实例的新框架。

子面板的用途是当用户点击enter按钮时,颜色会发生变化。目前,我让每个 subpanel 包含一个名为 EnterAction 的内部类,它调用 setBackground 来更改颜色。

我想知道如何修改它,以便我可以同步所有子面板之间的颜色变化。

目前,我有一个变量green,我相信我可以在所有面板之间传递它。但是,我不确定如何让 EnterAction 更改所有当前 Activity 的面板?

我正在考虑创建一个 Activity 子面板列表?但是,如果用户关闭子面板,这是否会导致我需要维护列表的额外问题?

这是我的代码:

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.KeyStroke;

public class SubPanel extends javax.swing.JPanel
{
private Action enterAction;

public SubPanel()
{
initComponents();
enterAction = new EnterAction();

//KeyBindings on the enter button
this.getInputMap().put(KeyStroke.getKeyStroke( "ENTER" ), "doEnterAction");
this.getActionMap().put( "doEnterAction", enterAction );
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

setForeground(new java.awt.Color(1, 1, 1));
setToolTipText("");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration

private static int green = 240;

private class EnterAction extends AbstractAction
{
@Override
public void actionPerformed(ActionEvent ae)
{
//System.out.println("Enter button is pressed");
green -= 5;
if (green <= 0) green = 0;
setBackground(new java.awt.Color(255, green, 255));
}
}
}

编辑:最多有 5 个面板。这样就无需创建维护 Activity 面板的列表。

最佳答案

相反,创建一个保存当前颜色的PanelColorModel。让感兴趣的面板注册为该模型的监听器,使用 observer pattern 之一建议实现here 。那么你的Action可以更新模型,听众可以做出相应的 react 。

关于java - Swing 面板颜色变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16386355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com