我创建了用于最大化,最小化和退出的自定义按钮。一切工作正常,但有一个例外,程序在最小化之前不记得哪个窗口处于哪个状态。所以我的问题是,有没有一种程序可以在最小化之前记住窗口状态,并恢复该状态,而不是仅返回NORMAL状态?
我的解决方案:
最大化:
JButton btnO = new JButton("O");
btnO.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (frame.getExtendedState() == JFrame.MAXIMIZED_BOTH) {
frame.setExtendedState(JFrame.NORMAL);
} else {
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
}
});
并最小化:
JButton btnMinimize = new JButton("-");
btnMinimize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setExtendedState(JFrame.ICONIFIED);
}
});
答案 0 :(得分:1)
您可以采用ComponentListener
方法并在调整组件(在您的情况下为框架)的大小时恢复其状态。代码中有一些额外的注释。
看看这个例子:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class FrameState extends JFrame {
private static final long serialVersionUID = 1965751967944243251L;
private int state = -1; // Variable to keep the last state.
public FrameState() {
super("Nothing :)");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("-");
b.addActionListener(e -> {
state = getExtendedState(); //Store the state before "-" is pressed
setExtendedState(JFrame.ICONIFIED);
});
JButton o = new JButton("O");
o.addActionListener(e -> {
if (getExtendedState() == JFrame.MAXIMIZED_BOTH) {
setExtendedState(JFrame.NORMAL);
} else {
setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
getContentPane().setLayout(new FlowLayout());
getContentPane().add(o);
getContentPane().add(b);
setSize(new Dimension(300, 300));
setLocationRelativeTo(null);
addComponentListener(new ComponentListener() {
@Override
public void componentShown(ComponentEvent arg0) {
}
@Override
public void componentResized(ComponentEvent arg0) {
if (state != -1) {
setExtendedState(state); //Restore the state.
state = -1; //If it is not back to -1, window won't be resized properly by OS.
}
}
@Override
public void componentMoved(ComponentEvent arg0) {
}
@Override
public void componentHidden(ComponentEvent arg0) {
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
FrameState f = new FrameState();
f.setVisible(true);
});
}
}
答案 1 :(得分:1)
您可以在JButton中使用此代码来最大化和还原JFrame。 为了执行此功能,即使在Java类中扩展了JFrame,也要导入JFrame。
if(getExtendedState()==NORMAL)
{
setExtendedState(MAXIMIZED_BOTH);
}
else
{
setExtendedState(NORMAL);
}