Java如何以编程方式更改JFrame状态?
在以下代码片段中,您将学习如何JFrame在Swing应用程序中以编程方式更改组件的框架状态。该JFrame状态表示为逐位掩码。您可以JFrame使用该JFrame.setExtendedState()方法最小化,最大化或使状态恢复正常。
您可以将以下值作为参数传递给方法:
Frame.NORMAL
Frame.ICONIFIED
Frame.MAXIMIZED_HORIZ
Frame.MAXIMIZED_VERT
Frame.MAXIMIZED_BOTH
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class SwingFrameState extends JFrame { public SwingFrameState() throws HeadlessException { initUI(); } private void initUI() { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLayout(new FlowLayout()); final JButton minimize = new JButton("Minimize"); final JButton maximize = new JButton("Maximize"); final JButton normal = new JButton("Normal"); add(normal); add(minimize); add(maximize); pack(); setSize(500, 200); ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == normal) { setExtendedState(Frame.NORMAL); } else if (e.getSource() == minimize) { setExtendedState(Frame.ICONIFIED); } else if (e.getSource() == maximize) { setExtendedState(Frame.MAXIMIZED_BOTH); } } }; minimize.addActionListener(listener); maximize.addActionListener(listener); normal.addActionListener(listener); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new SwingFrameState().setVisible(true); } }); } }
上面的代码片段的输出屏幕截图为: