Java Tutorial/Swing/JFrame Window
Содержание
- 1 Centering a Window
- 2 Close a JFrame under condition
- 3 Constants for JFrame window close action
- 4 Creating a Borderless Window
- 5 Creating a Titleless and Borderless JFrame
- 6 Creating a Window
- 7 Creating Frames with a background image
- 8 Disabling the Close Button on a JFrame
- 9 Display a JFrame instance
- 10 Drag and move a frame from its content area
- 11 Exiting an Application When a JFrame Is Closed
- 12 Extending JFrame: Closing Frames by Default
- 13 Getting All Created Frames in an Application
- 14 Getting the Child Components of a Container
- 15 Get Top Frame
- 16 Handling JFrame Events
- 17 JFrame with Label and Window Listener to Handle Closing the Frame
- 18 Make a JFrame always visible
- 19 Make a JInternalFrame a tool window
- 20 Making a Frame Non-Resizable: use setResizable(false) to freeze a frame"s size.
- 21 Maximize a JFrame
- 22 Move JInternalFrame To Front
- 23 Preventing a Window from Gaining the Focus
- 24 Removing the Title Bar of a Frame
- 25 Resizing and positioning a JFrame
- 26 Set Default window close operation
- 27 SetIconImages for JFrame
- 28 Setting the Icon for a Frame
- 29 Sizing Windows with Toolkit
- 30 Specifying Window Decorations
- 31 Use Component listener to ensure frame visibilities
Centering a Window
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import javax.swing.JFrame;
public class CenteringaWindow {
public static void main(String[] args) {
JFrame aWindow = new JFrame("This is the Window Title");
Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
int windowWidth = 400;
int windowHeight = 150;
// set position and size
aWindow.setBounds(center.x - windowWidth / 2, center.y - windowHeight / 2, windowWidth,
windowHeight);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aWindow.setVisible(true); // Display the window
}
}
Close a JFrame under condition
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Main extends JFrame {
public Main() {
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
if (JOptionPane.showConfirmDialog(null, "Are you sure ?") == JOptionPane.YES_OPTION) {
setVisible(false);
dispose();
}
}
});
pack();
setVisible(true);
}
public static void main(String args[]) {
new Main();
}
}
Constants for JFrame window close action
- JFrame has the setDefaultCloseOperation method to control what the JFrame"s close button does.
- The setDefaultCloseOperation method can take one of these static finals defined in the JFrame class:
- WindowConstants.DO_NOTHING_ON_CLOSE. Don"t do anything.
- WindowConstants.HIDE_ON_CLOSE (the default). Hides the frame after invoking any registered WindowListener objects.
- WindowConstants.DISPOSE_ON_CLOSE. Hides and disposes the frame after invoking any registered WindowListener objects.
- JFrame.EXIT_ON_CLOSE. Exits the application using the System.exit method.
import javax.swing.JFrame;
import javax.swing.UIManager;
public class SimplestFrame {
public static void main(String[] args) {
JFrame aWindow = new JFrame("This is the Window Title");
aWindow.setBounds(50, 100, 300, 300);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aWindow.setVisible(true);
}
}
Creating a Borderless Window
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JWindow;
public class Main {
public static void main(String[] argv) throws Exception {
JWindow window = new JWindow();
JButton component = new JButton("asdf");
// Add component to the window
window.getContentPane().add(component, BorderLayout.CENTER);
// Set initial size
window.setSize(300, 300);
// Show the window
window.setVisible(true);
}
}
Creating a Titleless and Borderless JFrame
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("TitleLessJFrame");
frame.getContentPane().add(new JLabel(" HEY!!!"));
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setVisible(true);
}
}
Creating a Window
import javax.swing.JFrame;
public class CreatingAWindow {
public static void main(String[] args) {
JFrame aWindow = new JFrame("This is the Window Title");
int windowWidth = 400; // Window width in pixels
int windowHeight = 150; // Window height in pixels
aWindow.setBounds(50, 100, // Set position
windowWidth, windowHeight); // and size
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aWindow.setVisible(true); // Display the window
}
}
Creating Frames with a background image
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
Main() {
add(new ContentPanel());
setSize(500, 300);
}
public static void main(String[] args) {
Main jrframe = new Main();
jrframe.setVisible(true);
}
}
class ContentPanel extends JPanel {
Image bgimage = null;
ContentPanel() {
MediaTracker mt = new MediaTracker(this);
bgimage = Toolkit.getDefaultToolkit().getImage("a.jpg");
mt.addImage(bgimage, 0);
try {
mt.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int imwidth = bgimage.getWidth(null);
int imheight = bgimage.getHeight(null);
g.drawImage(bgimage, 1, 1, null);
}
}
Disabling the Close Button on a JFrame
import javax.swing.JFrame;
public class Main {
public static void main(String[] argv) throws Exception {
// Create a frame
JFrame frame = new JFrame();
// Get default close operation
int op = frame.getDefaultCloseOperation(); // HIDE_ON_CLOSE
// Set to ignore the button
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
}
Display a JFrame instance
The JFrame class has two methods that you call to display a JFrame instance, pack and setVisible.
public void pack ()
public void setVisible (boolean visible)
Drag and move a frame from its content area
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, getWidth(), getHeight());
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(300, 280));
Main ch = new Main();
frame.getContentPane().add(ch);
frame.setUndecorated(true);
MoveMouseListener mml = new MoveMouseListener(ch);
ch.addMouseListener(mml);
ch.addMouseMotionListener(mml);
frame.pack();
frame.setVisible(true);
}
}
class MoveMouseListener implements MouseListener, MouseMotionListener {
JComponent target;
Point start_drag;
Point start_loc;
public MoveMouseListener(JComponent target) {
this.target = target;
}
public static JFrame getFrame(Container target) {
if (target instanceof JFrame) {
return (JFrame) target;
}
return getFrame(target.getParent());
}
Point getScreenLocation(MouseEvent e) {
Point cursor = e.getPoint();
Point target_location = this.target.getLocationOnScreen();
return new Point((int) (target_location.getX() + cursor.getX()),
(int) (target_location.getY() + cursor.getY()));
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
this.start_drag = this.getScreenLocation(e);
this.start_loc = this.getFrame(this.target).getLocation();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Point current = this.getScreenLocation(e);
Point offset = new Point((int) current.getX() - (int) start_drag.getX(),
(int) current.getY() - (int) start_drag.getY());
JFrame frame = this.getFrame(target);
Point new_location = new Point(
(int) (this.start_loc.getX() + offset.getX()), (int) (this.start_loc
.getY() + offset.getY()));
frame.setLocation(new_location);
}
public void mouseMoved(MouseEvent e) {
}
}
Exiting an Application When a JFrame Is Closed
import javax.swing.JFrame;
public class Main {
public static void main(String[] argv) throws Exception {
// Create a frame
JFrame frame = new JFrame();
// Get default close operation
int op = frame.getDefaultCloseOperation(); // HIDE_ON_CLOSE
// Set to exit on close
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Extending JFrame: Closing Frames by Default
When extending JFrame, this class has two important protected methods:
protected void frameInit()
protected JRootPane createRootPane()
If you do override the frameInit() method of JFrame, remember to call super.frameInit() first, to initialize the default behaviors.
Getting All Created Frames in an Application
import java.awt.Frame;
public class Main {
public static void main() {
Frame[] frames = Frame.getFrames();
for (int i = 0; i < frames.length; i++) {
String title = frames[i].getTitle();
System.out.println(title);
boolean isVisible = frames[i].isVisible();
System.out.println(isVisible);
}
}
}
Getting the Child Components of a Container
import java.awt.ruponent;
import java.awt.Rectangle;
import javax.swing.JFrame;
public class Main {
public static void main() {
JFrame container = new JFrame();
Component[] components = container.getComponents();
for (int i = 0; i < components.length; i++) {
Rectangle bounds = components[i].getBounds();
}
}
}
Get Top Frame
/*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
import java.awt.*;
public class GUITasks {
public static Frame getTopFrame() {
Frame[] frames = Frame.getFrames();
for(int i = 0; i < frames.length; i++) {
if(frames[i].getFocusOwner() != null) {
return frames[i];
}
}
if(frames.length > 0) {
return frames[0];
}
return null;
}
public static void drawDashed(Graphics g, int x1, int y1, int x2, int y2, int dashSize, int gapSize) {
if(x2 < x1) {
int temp = x1;
x1 = x2;
x2 = temp;
}
if(y2 < y1) {
int temp = y1;
y1 = y2;
y2 = temp;
}
int totalDash = dashSize + gapSize;
if(y1 == y2) {
int virtualStartX = (x1 / totalDash) * totalDash;
for(int x = virtualStartX; x < x2; x += totalDash) {
int topX = x + dashSize;
if(topX > x2) {
topX = x2;
}
int firstX = x;
if(firstX < x1) {
firstX = x1;
}
if(firstX < topX) {
g.drawLine(firstX, y1, topX, y1);
}
}
}
else if(x1 == x2) {
int virtualStartY = (y1 / totalDash) * totalDash;
for(int y = virtualStartY; y < y2; y += totalDash) {
int topY = y + dashSize;
if(topY > y2) {
topY = y2;
}
int firstY = y;
if(firstY < y1) {
firstY = y1;
}
if(firstY < topY) {
g.drawLine(x1, firstY, x1, topY);
}
}
}
else {
// Not supported
g.drawLine(x1, y1, x2, y2);
}
}
}
Handling JFrame Events
The JFrame class supports the registration of eleven different listeners:
- ComponentListener: To find out when the frame moves or is resized.
- ContainerListener: Normally not added to a JFrame because you add components to the content pane of its JRootPane.
- FocusListener: To find out when the frame gets or loses input focus.
- HierarchyBoundsListener: To find out when the frame moves or is resized.
- HierarchyListener: To find out when the frame is shown or hidden.
- InputMethodListener: To work with input methods for internationalization.
- MouseListener and MouseMotionListener: To listen for mouse and mouse motion events.
- PropertyChangeListener: To listen for changes to bound properties.
- WindowListener: To find out when a window is iconified, deiconified, closing, closed and so on.
- KeyListener: Normally not added to a JFrame. Instead, you register a keyboard action for its content pane, like this:
JPanel content = (JPanel)frame.getContentPane();
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
content.registerKeyboardAction(actionListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
JFrame with Label and Window Listener to Handle Closing the Frame
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
}
public class TJFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Frame");
JLabel label = new JLabel("This is a Swing frame", JLabel.CENTER);
frame.add(label);
frame.addWindowListener(new WindowEventHandler());
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setSize(350, 200); // width=350, height=200
frame.setVisible(true); // Display the frame
}
}
Make a JFrame always visible
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main{
public static void main(String[] args) {
JFrame frame = new JFrame("Hello!!");
frame.setAlwaysOnTop(true);
frame.setLocationByPlatform(true);
frame.add(new JLabel(" Always visible"));
frame.pack();
frame.setVisible(true);
}
}
Make a JInternalFrame a tool window
/*
* Copyright (C) 2001-2004 Colin Bell
* colbell@users.sourceforge.net
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.SwingUtilities;
/**
* Common GUI utilities accessed via static methods.
*
* @author
*/
public class GUIUtils {
/**
* Return <TT>true</TT> if <TT>frame</TT> is a tool window. I.E. is the
* <TT>JInternalFrame.isPalette</TT> set to <TT>Boolean.TRUE</TT>?
*
* @param frame
* The <TT>JInternalFrame</TT> to be checked.
*
* @throws IllegalArgumentException
* If <TT>frame</TT> is <TT>null</TT>.
*/
public static boolean isToolWindow(JInternalFrame frame) {
if (frame == null) {
throw new IllegalArgumentException("null JInternalFrame passed");
}
final Object obj = frame.getClientProperty("JInternalFrame.isPalette");
return obj != null && obj == Boolean.TRUE;
}
/**
* Make the passed internal frame a Tool Window.
*/
public static void makeToolWindow(JInternalFrame frame, boolean isToolWindow) {
if (frame == null) {
throw new IllegalArgumentException("null JInternalFrame passed");
}
frame
.putClientProperty("JInternalFrame.isPalette", isToolWindow ? Boolean.TRUE : Boolean.FALSE);
}
}
Making a Frame Non-Resizable: use setResizable(false) to freeze a frame"s size.
import java.awt.Frame;
public class Main {
public static void main() {
Frame frame = new Frame();
frame.setResizable(false);
boolean resizable = frame.isResizable();
}
}
Maximize a JFrame
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
public class Main extends JFrame {
public Main() {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
this.setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
Main t = new Main();
t.setVisible(true);
}
}
Move JInternalFrame To Front
/*
* Copyright (C) 2001-2004 Colin Bell
* colbell@users.sourceforge.net
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.SwingUtilities;
/**
* Common GUI utilities accessed via static methods.
*
* @author
*/
public class GUIUtils {
public static void moveToFront(final JInternalFrame fr) {
if (fr != null) {
processOnSwingEventThread(new Runnable() {
public void run() {
fr.moveToFront();
fr.setVisible(true);
try {
fr.setSelected(true);
if (fr.isIcon()) {
fr.setIcon(false);
}
fr.setSelected(true);
} catch (PropertyVetoException ex) {
}
fr.requestFocus();
}
});
}
}
public static void processOnSwingEventThread(Runnable todo) {
processOnSwingEventThread(todo, false);
}
public static void processOnSwingEventThread(Runnable todo, boolean wait) {
if (todo == null) {
throw new IllegalArgumentException("Runnable == null");
}
if (wait) {
if (SwingUtilities.isEventDispatchThread()) {
todo.run();
} else {
try {
SwingUtilities.invokeAndWait(todo);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
} else {
if (SwingUtilities.isEventDispatchThread()) {
todo.run();
} else {
SwingUtilities.invokeLater(todo);
}
}
}
}
Preventing a Window from Gaining the Focus
import javax.swing.JFrame;
public class Main {
public static void main(String[] argv) throws Exception {
JFrame frame = new JFrame();
frame.setFocusableWindowState(false);
}
}
Removing the Title Bar of a Frame
import java.awt.Frame;
public class Main {
public static void main() {
Frame frame = new Frame();
frame.setUndecorated(true);
// Get the current decorated state
boolean undecorated = frame.isUndecorated();
}
}
Resizing and positioning a JFrame
The pack method resizes a JFrame to a default width and height. To resize a JFrame, call the setSize method
public void setSize (int width, int height)
public void setSize (java.awt.Dimension d)
Set Default window close operation
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainClass extends JFrame {
private JButton buttonOK = new JButton("OK");
private JTextField textName = new JTextField(15);
public static void main(String[] args) {
new MainClass();
}
public MainClass() {
this.setSize(325, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonListener bl = new ButtonListener();
JPanel panel1 = new JPanel();
panel1.add(new JLabel("Enter your name: "));
panel1.add(textName);
buttonOK.addActionListener(bl);
panel1.add(buttonOK);
this.add(panel1);
this.setVisible(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonOK) {
String name = textName.getText();
if (name.length() == 0) {
JOptionPane.showMessageDialog(MainClass.this, "=0", "", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(MainClass.this, "Good morning " + name, "Salutations",
JOptionPane.INFORMATION_MESSAGE);
}
textName.requestFocus();
}
}
}
}
SetIconImages for JFrame
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class WindowIcons extends JFrame {
final static int BIG_ICON_RENDER_WIDTH = 20;
final static int SMALL_ICON_WIDTH = 16;
final static int SMALL_ICON_HEIGHT = 16;
final static int SMALL_ICON_RENDER_WIDTH = 10;
public WindowIcons() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
BufferedImage bi = new BufferedImage(SMALL_ICON_WIDTH, SMALL_ICON_HEIGHT,
BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.getGraphics();
g.setColor(Color.black);
g.fillRect(0, 0, SMALL_ICON_RENDER_WIDTH, SMALL_ICON_HEIGHT);
g.dispose();
images.add(bi);
setIconImages(images);
setSize(250, 100);
setVisible(true);
new JDialog(this, "Arbitrary Dialog") {
{
setSize(200, 100);
setVisible(true);
}
};
}
public static void main(String[] args) {
new WindowIcons();
}
}
Setting the Icon for a Frame
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Main {
public static void main() {
JFrame frame = new JFrame();
Image icon = Toolkit.getDefaultToolkit().getImage("icon.gif");
frame.setIconImage(icon);
}
}
Sizing Windows with Toolkit
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class SizingWindowswithToolkit {
public static void main(String[] args) {
JFrame aWindow = new JFrame("This is the Window Title");
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize = theKit.getScreenSize();
aWindow.setBounds(wndSize.width / 4, wndSize.height / 4, // Position
wndSize.width / 2, wndSize.height / 2); // Size
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aWindow.setVisible(true);
}
}
Specifying Window Decorations
/*
*
* Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.image.BufferedImage;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
public class FrameDemo2 extends WindowAdapter implements ActionListener {
private Point lastLocation = null;
private int maxX = 500;
private int maxY = 500;
// the main frame"s default button
private static JButton defaultButton = null;
// constants for action commands
protected final static String NO_DECORATIONS = "no_dec";
protected final static String LF_DECORATIONS = "laf_dec";
protected final static String WS_DECORATIONS = "ws_dec";
protected final static String CREATE_WINDOW = "new_win";
protected final static String DEFAULT_ICON = "def_icon";
protected final static String FILE_ICON = "file_icon";
protected final static String PAINT_ICON = "paint_icon";
// true if the next frame created should have no window decorations
protected boolean noDecorations = false;
// true if the next frame created should have setIconImage called
protected boolean specifyIcon = false;
// true if the next frame created should have a custom painted icon
protected boolean createIcon = false;
// Perform some initialization.
public FrameDemo2() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
maxX = screenSize.width - 50;
maxY = screenSize.height - 50;
}
// Create a new MyFrame object and show it.
public void showNewWindow() {
JFrame frame = new MyFrame();
// Take care of the no window decorations case.
// NOTE: Unless you really need the functionality
// provided by JFrame, you would usually use a
// Window or JWindow instead of an undecorated JFrame.
if (noDecorations) {
frame.setUndecorated(true);
}
// Set window location.
if (lastLocation != null) {
// Move the window over and down 40 pixels.
lastLocation.translate(40, 40);
if ((lastLocation.x > maxX) || (lastLocation.y > maxY)) {
lastLocation.setLocation(0, 0);
}
frame.setLocation(lastLocation);
} else {
lastLocation = frame.getLocation();
}
// Calling setIconImage sets the icon displayed when the window
// is minimized. Most window systems (or look and feels, if
// decorations are provided by the look and feel) also use this
// icon in the window decorations.
if (specifyIcon) {
if (createIcon) {
frame.setIconImage(createFDImage()); // create an icon from scratch
} else {
frame.setIconImage(getFDImage()); // get the icon from a file
}
}
// Show window.
frame.setSize(new Dimension(170, 100));
frame.setVisible(true);
}
// Create the window-creation controls that go in the main window.
protected JComponent createOptionControls() {
JLabel label1 = new JLabel("Decoration options for subsequently created frames:");
ButtonGroup bg1 = new ButtonGroup();
JLabel label2 = new JLabel("Icon options:");
ButtonGroup bg2 = new ButtonGroup();
// Create the buttons
JRadioButton rb1 = new JRadioButton();
rb1.setText("Look and feel decorated");
rb1.setActionCommand(LF_DECORATIONS);
rb1.addActionListener(this);
rb1.setSelected(true);
bg1.add(rb1);
//
JRadioButton rb2 = new JRadioButton();
rb2.setText("Window system decorated");
rb2.setActionCommand(WS_DECORATIONS);
rb2.addActionListener(this);
bg1.add(rb2);
//
JRadioButton rb3 = new JRadioButton();
rb3.setText("No decorations");
rb3.setActionCommand(NO_DECORATIONS);
rb3.addActionListener(this);
bg1.add(rb3);
//
//
JRadioButton rb4 = new JRadioButton();
rb4.setText("Default icon");
rb4.setActionCommand(DEFAULT_ICON);
rb4.addActionListener(this);
rb4.setSelected(true);
bg2.add(rb4);
//
JRadioButton rb5 = new JRadioButton();
rb5.setText("Icon from a JPEG file");
rb5.setActionCommand(FILE_ICON);
rb5.addActionListener(this);
bg2.add(rb5);
//
JRadioButton rb6 = new JRadioButton();
rb6.setText("Painted icon");
rb6.setActionCommand(PAINT_ICON);
rb6.addActionListener(this);
bg2.add(rb6);
// Add everything to a container.
Box box = Box.createVerticalBox();
box.add(label1);
box.add(Box.createVerticalStrut(5)); // spacer
box.add(rb1);
box.add(rb2);
box.add(rb3);
//
box.add(Box.createVerticalStrut(15)); // spacer
box.add(label2);
box.add(Box.createVerticalStrut(5)); // spacer
box.add(rb4);
box.add(rb5);
box.add(rb6);
// Add some breathing room.
box.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
return box;
}
// Create the button that goes in the main window.
protected JComponent createButtonPane() {
JButton button = new JButton("New window");
button.setActionCommand(CREATE_WINDOW);
button.addActionListener(this);
defaultButton = button; // Used later to make this the frame"s default
// button.
// Center the button in a panel with some space around it.
JPanel pane = new JPanel(); // use default FlowLayout
pane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
pane.add(button);
return pane;
}
// Handle action events from all the buttons.
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
// Handle the New window button.
if (CREATE_WINDOW.equals(command)) {
showNewWindow();
// Handle the first group of radio buttons.
} else if (NO_DECORATIONS.equals(command)) {
noDecorations = true;
JFrame.setDefaultLookAndFeelDecorated(false);
} else if (WS_DECORATIONS.equals(command)) {
noDecorations = false;
JFrame.setDefaultLookAndFeelDecorated(false);
} else if (LF_DECORATIONS.equals(command)) {
noDecorations = false;
JFrame.setDefaultLookAndFeelDecorated(true);
// Handle the second group of radio buttons.
} else if (DEFAULT_ICON.equals(command)) {
specifyIcon = false;
} else if (FILE_ICON.equals(command)) {
specifyIcon = true;
createIcon = false;
} else if (PAINT_ICON.equals(command)) {
specifyIcon = true;
createIcon = true;
}
}
// Creates an icon-worthy Image from scratch.
protected static Image createFDImage() {
// Create a 16x16 pixel image.
BufferedImage bi = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
// Draw into it.
Graphics g = bi.getGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, 15, 15);
g.setColor(Color.RED);
g.fillOval(5, 3, 6, 6);
// Clean up.
g.dispose();
// Return it.
return bi;
}
// Returns an Image or null.
protected static Image getFDImage() {
java.net.URL imgURL = FrameDemo2.class.getResource("images/FD.jpg");
if (imgURL != null) {
return new ImageIcon(imgURL).getImage();
} else {
return null;
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Use the Java look and feel.
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
}
// Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
// Instantiate the controlling class.
JFrame frame = new JFrame("FrameDemo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
FrameDemo2 demo = new FrameDemo2();
// Add components to it.
Container contentPane = frame.getContentPane();
contentPane.add(demo.createOptionControls(), BorderLayout.CENTER);
contentPane.add(demo.createButtonPane(), BorderLayout.PAGE_END);
frame.getRootPane().setDefaultButton(defaultButton);
// Display the window.
frame.pack();
frame.setLocationRelativeTo(null); // center it
frame.setVisible(true);
}
// Start the demo.
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application"s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
class MyFrame extends JFrame implements ActionListener {
// Create a frame with a button.
public MyFrame() {
super("A window");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// This button lets you close even an undecorated window.
JButton button = new JButton("Close window");
button.addActionListener(this);
// Place the button near the bottom of the window.
Container contentPane = getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
contentPane.add(Box.createVerticalGlue()); // takes all extra space
contentPane.add(button);
button.setAlignmentX(Component.CENTER_ALIGNMENT); // horizontally centered
contentPane.add(Box.createVerticalStrut(5)); // spacer
}
// Make the button do the same thing as the default close operation
// (DISPOSE_ON_CLOSE).
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
}
}
Use Component listener to ensure frame visibilities
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ruponentAdapter;
import java.awt.event.ruponentEvent;
import javax.swing.JFrame;
public class Main extends ComponentAdapter {
public void componentMoved(ComponentEvent evt) {
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
int x = evt.getComponent().getX();
int y = evt.getComponent().getY();
if (y < 0 ) {
y = 0;
}
if (x < 0 ) {
x = 0;
}
if (x > size.getWidth() - evt.getComponent().getWidth() ) {
x = (int) size.getWidth() - evt.getComponent().getWidth();
}
if (y > size.getHeight() - evt.getComponent().getHeight() ) {
y = (int) size.getHeight() - evt.getComponent().getHeight();
}
evt.getComponent().setLocation(x, y);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Window cannot be moved to hide part of it");
frame.setSize(300,300);
frame.addComponentListener(new Main());
frame.setVisible(true);
}
}