我正在寻找创建一个将保持最大化的窗口,但可以将其拖动到其他屏幕(它将再次最大化)。我目前的实施失败了。
期望的行为:
ACTUAL BEHAVIOR:
有人有什么想法吗?
SSCCE:
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ComponentMovedTest extends JPanel
{
private ComponentMovedTest()
{
final JFrame frame = new JFrame("ComponentMovedTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// FIXME: Naive attempt at ensuring the window becomes maximized
// on the screen it moves to after moving finishes.
frame.addComponentListener( new ComponentAdapter()
{
@Override
public void componentMoved( ComponentEvent e )
{
frame.setExtendedState( JFrame.MAXIMIZED_BOTH );
}
});
frame.setExtendedState( JFrame.MAXIMIZED_BOTH );
frame.setResizable( false );
frame.setVisible(true);
}
public static void main(String[] args)
{
new ComponentMovedTest();
}
}
答案 0 :(得分:0)
所以我最终选择了一个黑客解决方案。我无法使自动最大化以可接受的方式工作。我做了它,以便如果窗口没有最大化,它强制执行严格的大小,但仍然允许您手动最大化窗口。黑客解决方案如下。如果没有人能够接近原问题的意图,我会在几天内将其标记为已接受的答案。
Hack示例修复:
import java.awt.Dimension;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ComponentMovedTest extends JPanel
{
Dimension size = new Dimension( 0, 0 );
private ComponentMovedTest()
{
final JFrame frame = new JFrame( "ComponentMovedTest" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// NOTE: With a proper layout manager, this ComponentListener may
// not be necessary, as the layout manager would likely enforce
// minimum/maximum window sizing. This means fix #2 could
// also be removed in favor of setting min/max/pref size,
// based on the layout manager.
frame.addComponentListener( new ComponentAdapter()
{
@Override
public void componentResized( ComponentEvent e )
{
if (frame.getExtendedState() != JFrame.MAXIMIZED_BOTH)
{
// FIX #3: resize the window to the default size
// whenever resized.
frame.setSize(size);
}
}
});
// FIX #1: Extend after setting visible.
frame.setVisible( true );
frame.setExtendedState( JFrame.MAXIMIZED_BOTH );
// FIX #2: Set a default window size.
size = frame.getSize();
}
public static void main( String[] args )
{
new ComponentMovedTest();
}
}