我正在处理的应用程序包含一个主JFrame,用户最终可以从中打开另一个补充框架。我试图实现app的这种行为,一旦主框架最小化,辅助框架就被最小化(图标化)。
我正在考虑覆盖主框架的setExtendedState方法以捕获它被最小化的时刻,然后从那里触发属性更改事件,以便补充框架可以对其进行操作。
然而,我发现,遗憾的是,被覆盖的setExtendedState永远不会被调用。我非常感谢任何实现理想行为的想法。以下是我用于测试的代码......
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
public class IconifySupplementaryFrameTest {
public static void main(String[] args) {
(new MainFrame()).setVisible(true);
}
}
class MainFrame extends JFrame {
public static final String EXTENDED_STATE_KEY = "extendedState";
MainFrame() {
super("Iconify test - main window");
setLayout(new FlowLayout(FlowLayout.LEADING));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 400);
setLocationByPlatform(true);
add(new JButton(new AbstractAction("Show supplementary frame") {
@Override
public void actionPerformed(ActionEvent e) {
SupplementaryFrame.doShow(MainFrame.this);
}
}));
}
@Override
public synchronized void setExtendedState(int state) {
// This overridden method is never called ???
int oldState = getExtendedState();
super.setExtendedState(state);
firePropertyChange(EXTENDED_STATE_KEY, oldState, state);
}
}
class SupplementaryFrame extends JFrame implements PropertyChangeListener {
private static SupplementaryFrame instance;
private SupplementaryFrame(final JFrame parentFrame) {
super("Iconify test - supplementary window");
setSize(300, 300);
setLocationRelativeTo(parentFrame);
parentFrame.addPropertyChangeListener(
MainFrame.EXTENDED_STATE_KEY, this);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
instance = null;
parentFrame.removePropertyChangeListener(
MainFrame.EXTENDED_STATE_KEY,
SupplementaryFrame.this);
SupplementaryFrame.this.dispose();
}
});
}
static void doShow(JFrame parentFrame) {
if(instance == null) {
instance = new SupplementaryFrame(parentFrame);
instance.setVisible(true);
}
else {
// omitted _ugly_ code to bring this window (instance) to front
}
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
int state = this.getExtendedState();
int parentState = ((Integer)evt.getNewValue()).intValue();
if((parentState & ICONIFIED) == ICONIFIED)
this.setExtendedState(state | ICONIFIED);
}
}
答案 0 :(得分:1)
我正在处理的应用程序 包含一个主JFrame,从中 用户可能最终打开另一个 补充框架
应用程序通常设计为使用单个JFrame。使用JDialog创建补充窗口。创建对话框时,请确保将框架指定为对话框的所有者。现在,当您对图标进行图标化/取消图标化时,对话框会自动同步图标化。
答案 1 :(得分:1)
只需将WindowStateListener添加到MainFrame即可使代码与属性更改侦听器一起使用:
addWindowStateListener(new WindowStateListener() {
@Override
public void windowStateChanged(WindowEvent e) {
firePropertyChange(EXTENDED_STATE_KEY, e.getOldState(), e.getNewState());
}
});