Java/Swing JFC/Frame
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 A demonstration of the WindowListener approach to closing JFrames
- 2 Center a JFrame
- 3 Close a JFrame under condition
- 4 Create a frame
- 5 Create a JFrame class in a thread-safe way
- 6 Create undecorated frame
- 7 Creating a Borderless Window
- 8 Creating a Titleless and Borderless JFrame
- 9 Creating Frames with a background image
- 10 Default button for frame: press Enter to activate
- 11 Define the default close operation of a JFrame to EXIT_ON_CLOSE, application will exit by calling System.exit()
- 12 Deiconifies a frame; the maximized bits are not affected.
- 13 Demo to show a way of having More Choices or Less Choices
- 14 Determining When a Component Has Been Made Visible, Moved, or Resized
- 15 Determining When a Frame or Window Is Iconized or Maximized
- 16 Determining When a Frame or Window Is Opened or Closed
- 17 Disable JFrame close button
- 18 Disabling the Close Button on a JFrame
- 19 Drag and move a frame from its content area
- 20 Draw on frame with keyboard
- 21 Exiting an Application When a Frame Is Closed
- 22 Exiting an Application When a JFrame Is Closed
- 23 FrameDemo2.java shows off the window decoration features added in 1.4
- 24 FrameDemo:invoked from the event-dispatching thread
- 25 Frame dialog data exchange
- 26 Frame Icon drawn by yourself
- 27 Frame Icon from gif
- 28 Frame with components
- 29 Get the JFrame of a component
- 30 Getting All Created Frames in an Application
- 31 Handle JFrame window events
- 32 Hiding a Frame When Its Close Button Is Clicked
- 33 How to center a frame or dialog
- 34 Iconifies a frame; the maximized bits are not affected.
- 35 JFrame that closes when someone presses the ESC key
- 36 Make a JFrame always visible
- 37 Making a Frame Non-Resizable: use setResizable(false) to freeze a frame"s size.
- 38 Maximize a JFrame
- 39 Maximizes a frame; the iconified bit is not affected
- 40 Preventing a Window from Gaining the Focus
- 41 React to frame close action
- 42 Removing the Title Bar of a Frame
- 43 Screen edge snapping
- 44 Setting the Bounds for a Maximized Frame
- 45 Setting the Icon for a Frame
- 46 Show the given frame as modal to the specified owner
- 47 The Swing Version of the Hello, World! Program
- 48 Use Component listener to ensure frame visibilities
- 49 Using anonymous inner classes
A demonstration of the WindowListener approach to closing JFrames
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class FrameClose2 {
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
// Exit app when frame is closed.
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
System.exit(0);
}
});
mainFrame.setSize(320, 240);
mainFrame.setVisible(true);
}
}
Center a JFrame
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Main extends JFrame {
public static void main(String[] args) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Main mainForm = new Main();
mainForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainForm.setSize(250, 250);
mainForm.setLocation((screenSize.width - mainForm.getWidth()) / 2,
(screenSize.height - mainForm.getHeight()) / 2);
mainForm.pack();
mainForm.setVisible(true);
}
}
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();
}
}
Create a frame
import javax.swing.JFrame;
public class FirstFrame extends JFrame {
public FirstFrame() {
setTitle("FirstFrame");
setSize(300, 200);
}
public static void main(String[] args) {
JFrame frame = new FirstFrame();
frame.show();
}
}
Create a JFrame class in a thread-safe way
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.awt.EventQueue;
import javax.swing.JFrame;
/** Create a JFrame class in a thread-safe way.
* <br/>
* See http://java.sun.ru/developer/JDCTechTips/2003/tt1208.html.
*/
public class JFrameDemoSafe {
// We need a main program to instantiate and show.
public static void main(String[] args) {
// Create the GUI (variable is final because used by inner class).
final JFrame demo = new JFrameDemo();
// Create a Runnable to set the main visible, and get Swing to invoke.
EventQueue.invokeLater(new Runnable() {
public void run() {
demo.setVisible(true);
}
});
}
}
Create undecorated frame
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
private static Point point = new Point();
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setUndecorated(true);
JButton button = new JButton("Close Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
frame.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
point.x = e.getX();
point.y = e.getY();
}
});
frame.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
Point p = frame.getLocation();
frame.setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
}
});
frame.setSize(300, 300);
frame.setLocation(200, 200);
frame.setLayout(new BorderLayout());
frame.getContentPane().add(button, BorderLayout.NORTH);
frame.getContentPane().add(new JLabel("Drag Me", JLabel.CENTER), BorderLayout.CENTER);
frame.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 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);
}
}
Default button for frame: press Enter to activate
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
public class DefaultButton extends JPanel {
public DefaultButton() {
}
public static void main(String[] a) {
JDialog f = new JDialog();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JButton btOK = new JButton("Press Enter to click me, I am the default.");
btOK.setToolTipText("Save and exit");
f.getRootPane().setDefaultButton(btOK);
JPanel p = new JPanel();
p.add(btOK);
p.add(new JButton("I am NOT the default."));
f.getContentPane().add(p);
f.pack();
f.setSize(new Dimension(300, 200));
f.show();
}
}
Define the default close operation of a JFrame to EXIT_ON_CLOSE, application will exit by calling System.exit()
import javax.swing.JFrame;
public class Main extends JFrame {
public static void main(String[] args) {
Main frame = new Main();
frame.setSize(100, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Deiconifies a frame; the maximized bits are not affected.
import java.awt.Frame;
public class Main {
public static void main(String[] argv) throws Exception {
Frame frame = new Frame();
frame.setSize(300, 300);
frame.setVisible(true);
deiconify(frame);
}
public static void deiconify(Frame frame) {
int state = frame.getExtendedState();
// Clear the iconified bit
state &= ~Frame.ICONIFIED;
// Deiconify the frame
frame.setExtendedState(state);
}
}
Demo to show a way of having More Choices or Less Choices
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Demo to show a way of having "More Choices/Less Choices" in a pop-up window.
* The secret is to call pack() again each time you add/subtract the bottom
* panel.
*
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: MoreChoices.java,v 1.3 2004/02/09 03:33:50 ian Exp $
*/
public class MoreChoices extends JFrame {
Container cp;
boolean unsavedChanges = false;
JButton moreOrLessButton;
JPanel moreOrLessPanel;
ActionListener more;
ActionListener less;
/** "main program" method - construct and show */
public static void main(String[] av) {
// create a MoreChoices object, tell it to show up
JFrame jf = new MoreChoices();
jf.setLocation(100, 100); // get away from screen corner,
// since on some OSes a main window at 0,0 may be
// partly obscured (e.g. notebook with PowerPanel
jf.setVisible(true);
}
/** Construct the object including its GUI */
public MoreChoices() {
super("More Choices");
// cp = getContentPane();
cp = this;
cp.setLayout(new BorderLayout());
ButtonsPanel bp = new ButtonsPanel();
cp.add(BorderLayout.NORTH, bp);
// Construct the more/less switcher
less = new ActionListener() {
public void actionPerformed(ActionEvent e) {
cp.remove(moreOrLessPanel);
pack();
moreOrLessButton.setText("More Choices");
moreOrLessButton.removeActionListener(less);
moreOrLessButton.addActionListener(more);
}
};
more = new ActionListener() {
public void actionPerformed(ActionEvent e) {
cp.add(BorderLayout.SOUTH, moreOrLessPanel);
pack();
moreOrLessButton.setText("Fewer Choices");
moreOrLessButton.removeActionListener(more);
moreOrLessButton.addActionListener(less);
}
};
bp.add(moreOrLessButton = new JButton("More Choices"));
// Initial state is to add more choices
moreOrLessButton.addActionListener(more);
moreOrLessPanel = new ChoicesPanel();
// Finally a frame closer
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
dispose();
System.exit(0);
}
});
pack();
}
/**
* The panel that appears when you press More Choices. This is a toy; in a
* real application, this would likely be a separate full "public class".
*/
class ChoicesPanel extends JPanel {
ChoicesPanel() {
setBorder(BorderFactory.createEtchedBorder());
add(new JCheckBox("Happiness"));
add(new JCheckBox("Satisfaction"));
add(new JCheckBox("Contentment"));
}
}
/**
* The Panel that contains the More/Less button. It is just here to override
* getPreferredSize so that we can avoid "jitter" (i.e., the width
* changing); i.e., we must ensure that the main panel and the ChoicePanel
* have the same width
*/
class ButtonsPanel extends JPanel {
public Dimension getPreferredSize() {
// System.out.println("In ButtonsPanel.getPreferredSize()");
// For height, use our normal height
int dHeight = moreOrLessButton.getPreferredSize().height + 5 + 5;
// For witdh, use the included Panel"s width
int dWidth = moreOrLessPanel.getPreferredSize().width;
// Combine them; that"s the result we need.
return new Dimension(dWidth, dHeight);
}
}
}
Determining When a Component Has Been Made Visible, Moved, or Resized
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ruponentAdapter;
import java.awt.event.ruponentEvent;
import java.awt.event.ruponentListener;
import javax.swing.JFrame;
public class Main {
public static void main() {
ComponentListener listener = new ComponentAdapter() {
public void componentShown(ComponentEvent evt) {
Component c = (Component) evt.getSource();
System.out.println("Component is now visible");
}
public void componentHidden(ComponentEvent evt) {
Component c = (Component) evt.getSource();
System.out.println("Component is now hidden");
}
public void componentMoved(ComponentEvent evt) {
Component c = (Component) evt.getSource();
Point newLoc = c.getLocation();
System.out.println("Get new location");
}
public void componentResized(ComponentEvent evt) {
Component c = (Component) evt.getSource();
Dimension newSize = c.getSize();
System.out.println("Get new size");
}
};
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.addComponentListener(listener);
frame.setVisible(true);
}
}
Determining When a Frame or Window Is Iconized or Maximized
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
public class Main {
public static void main() {
Frame frame = new Frame();
WindowStateListener listener = new WindowAdapter() {
public void windowStateChanged(WindowEvent evt) {
int oldState = evt.getOldState();
int newState = evt.getNewState();
if ((oldState & Frame.ICONIFIED) == 0 && (newState & Frame.ICONIFIED) != 0) {
System.out.println("Frame was iconized");
} else if ((oldState & Frame.ICONIFIED) != 0 && (newState & Frame.ICONIFIED) == 0) {
System.out.println("Frame was deiconized");
}
if ((oldState & Frame.MAXIMIZED_BOTH) == 0 && (newState & Frame.MAXIMIZED_BOTH) != 0) {
System.out.println("Frame was maximized");
} else if ((oldState & Frame.MAXIMIZED_BOTH) != 0 && (newState & Frame.MAXIMIZED_BOTH) == 0) {
System.out.println("Frame was minimized");
}
}
};
frame.addWindowStateListener(listener);
frame.setVisible(true);
}
}
Determining When a Frame or Window Is Opened or Closed
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class Main {
public static void main() {
Frame frame = new Frame();
WindowListener listener = new WindowAdapter() {
public void windowOpened(WindowEvent evt) {
Frame frame = (Frame) evt.getSource();
System.out.println(frame.getTitle());
}
public void windowClosing(WindowEvent evt) {
Frame frame = (Frame) evt.getSource();
System.out.println(frame.getTitle());
}
public void windowClosed(WindowEvent evt) {
Frame frame = (Frame) evt.getSource();
System.out.println(frame.getTitle());
}
};
frame.addWindowListener(listener);
frame.setVisible(true);
}
}
Disable JFrame close button
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame {
public Main() throws HeadlessException {
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
JButton button = new JButton("Close");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setSize(new Dimension(100, 100));
this.getContentPane().add(button);
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
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);
}
}
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) {
}
}
Draw on frame with keyboard
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SketchPanel extends JPanel implements KeyListener {
private Point startPoint = new Point(0, 0);
private Point endPoint = new Point(0, 0);
public SketchPanel() {
addKeyListener(this);
}
public void keyPressed(KeyEvent evt) {
int keyCode = evt.getKeyCode();
int d;
if (evt.isShiftDown())
d = 5;
else
d = 1;
if (keyCode == KeyEvent.VK_LEFT)
add(-d, 0);
else if (keyCode == KeyEvent.VK_RIGHT)
add(d, 0);
else if (keyCode == KeyEvent.VK_UP)
add(0, -d);
else if (keyCode == KeyEvent.VK_DOWN)
add(0, d);
}
public void keyReleased(KeyEvent evt) {
}
public void keyTyped(KeyEvent evt) {
}
public boolean isFocusTraversable() {
return true;
}
public void add(int dx, int dy) {
endPoint.x += dx;
endPoint.y += dy;
Graphics g = getGraphics();
g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
g.dispose();
startPoint.x = endPoint.x;
startPoint.y = endPoint.y;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Sketch");
frame.setSize(300, 200);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new SketchPanel());
frame.show();
}
}
Exiting an Application When a Frame Is Closed
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Main {
public static void main() {
Frame frame = new Frame();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
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);
}
}
FrameDemo2.java shows off the window decoration features added in 1.4
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
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;
/*
* FrameDemo2.java shows off the window decoration features added in 1.4, plus
* some window positioning code and (optionally) setIconImage. It uses the file
* images/FD.jpg.
*/
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();
}
}
}
FrameDemo:invoked from the event-dispatching thread
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* 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 MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS 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 THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
/* FrameDemo.java requires no other files. */
public class FrameDemo {
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Suggest that the L&F (rather than the system)
//decorate all windows. This must be invoked before
//creating the JFrame. Native look and feels will
//ignore this hint.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
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();
}
});
}
}
Frame dialog data exchange
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class DataExchangeTest extends JFrame implements ActionListener {
private ConnectDialog dialog = null;
private JMenuItem connectItem = new JMenuItem("Connect");
public DataExchangeTest() {
setTitle("Data Exchange");
setSize(300, 300);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu);
connectItem.addActionListener(this);
fileMenu.add(connectItem);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source == connectItem) {
UserInfo transfer = new UserInfo("yourname", "pw");
dialog = new ConnectDialog(this);
if (dialog.showDialog(transfer)) {
String name = transfer.username;
String pwd = transfer.password;
Container contentPane = getContentPane();
contentPane.removeAll();
contentPane.add(new JLabel("username=" + name + ", password=" + pwd), "Center");
validate();
}
}
}
public static void main(String[] args) {
JFrame f = new DataExchangeTest();
f.show();
}
}
class UserInfo {
public String username;
public String password;
public UserInfo(String u, String p) {
username = u;
password = p;
}
}
class ConnectDialog extends JDialog implements ActionListener {
private JTextField username = new JTextField("");
private JPasswordField password= new JPasswordField("");
private boolean okPressed;
private JButton okButton;
private JButton cancelButton;
public ConnectDialog(JFrame parent) {
super(parent, "Connect", true);
Container contentPane = getContentPane();
JPanel p1 = new JPanel(new GridLayout(2, 2,3,3));
p1.add(new JLabel("User name:"));
p1.add(username);
p1.add(new JLabel("Password:"));
p1.add(password );
contentPane.add("Center", p1);
Panel p2 = new Panel();
okButton = addButton(p2, "Ok");
cancelButton = addButton(p2, "Cancel");
contentPane.add("South", p2);
setSize(240, 120);
}
private JButton addButton(Container c, String name) {
JButton button = new JButton(name);
button.addActionListener(this);
c.add(button);
return button;
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source == okButton) {
okPressed = true;
setVisible(false);
} else if (source == cancelButton)
setVisible(false);
}
public boolean showDialog(UserInfo transfer) {
username.setText(transfer.username);
password.setText(transfer.password);
okPressed = false;
show();
if (okPressed) {
transfer.username = username.getText();
transfer.password = new String(password.getPassword());
}
return okPressed;
}
}
Frame Icon drawn by yourself
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
///
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.MemoryImageSource;
/** MemImage is an in-memory icon showing a Color gradient. */
public class MemImage extends Component {
/**
* Demo main program, showing two ways to use it. Create a small MemImage
* and set it as this Frame"s iconImage. Also display a larger version of
* the same image in the Frame.
*/
public static void main(String[] av) {
Frame f = new Frame("MemImage.java");
f.add(new MemImage());
f.setIconImage(new MemImage(16, 16).getImage());
f.pack();
f.setVisible(true);
}
/** The image */
private Image img;
/** The image width */
private int w;
/** The image height */
private int h;
/** Construct a MemImage with a default size */
public MemImage() {
this(100, 100);
}
/** Construct a MemImage with a specified width and height */
public MemImage(int w, int h) {
this.w = w;
this.h = h;
int pix[] = new int[w * h];
int index = 0;
for (int y = 0; y < h; y++) {
int red = (y * 255) / (h - 1);
for (int x = 0; x < w; x++) {
int blue = (x * 255) / (w - 1);
pix[index++] = (255 << 24) | (red << 16) | blue;
}
}
img = createImage(new MemoryImageSource(w, h, pix, 0, w));
setSize(getPreferredSize());
}
/** Getter for the Image */
public Image getImage() {
return img;
}
public Dimension getPreferredSize() {
return new Dimension(w, h);
}
public void paint(Graphics g) {
g.drawImage(img, 0, 0, getSize().width, getSize().height, this);
}
}
Frame Icon from gif
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.awt.Frame;
import java.awt.Image;
import java.awt.Toolkit;
public class FrameIcon {
/** Demo main program, showing two ways to use it.
* Create a small MemImage and set it as this Frame"s iconImage.
* Also display a larger version of the same image in the Frame.
*/
public static void main(String[] av) {
Frame f = new Frame("FrameIcon");
Image im =
Toolkit.getDefaultToolkit().getImage("jexp.gif");
f.setIconImage(im);
f.setSize(100, 100);
f.setLocation(200, 200);
f.setVisible(true);
}
}
Frame with components
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class FramewithComponents extends JFrame {
public FramewithComponents() {
super("JLayeredPane Demo");
setSize(256, 256);
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.setOpaque(false);
JLabel label1 = new JLabel("Username:");
label1.setForeground(Color.white);
content.add(label1);
JTextField field = new JTextField(15);
content.add(field);
JLabel label2 = new JLabel("Password:");
label2.setForeground(Color.white);
content.add(label2);
JPasswordField fieldPass = new JPasswordField(15);
content.add(fieldPass);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(content);
((JPanel) getContentPane()).setOpaque(false);
ImageIcon earth = new ImageIcon("largejexpLogo.png");
JLabel backlabel = new JLabel(earth);
getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
backlabel.setBounds(0, 0, earth.getIconWidth(), earth.getIconHeight());
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(l);
setVisible(true);
}
public static void main(String[] args) {
new FramewithComponents();
}
}
Get the JFrame of a component
import java.awt.Color;
import java.awt.ruponent;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
public Main() {
this.setSize(400, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton button = new JButton("Change Frame Color");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
JFrame frame = (JFrame) SwingUtilities.getRoot(component);
frame.getContentPane().setBackground(Color.RED);
}
});
this.getContentPane().add(button);
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
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);
}
}
}
Handle JFrame window events
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Main extends JFrame {
public Main() {
setSize(300, 300);
setTitle("Window Listener");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
System.out.println("Window Opened Event");
}
public void windowClosing(WindowEvent e) {
System.out.println("Window Closing Event");
}
public void windowClosed(WindowEvent e) {
System.out.println("Window Close Event");
}
public void windowIconified(WindowEvent e) {
System.out.println("Window Iconified Event");
}
public void windowDeiconified(WindowEvent e) {
System.out.println("Window Deiconified Event");
}
public void windowActivated(WindowEvent e) {
System.out.println("Window Activated Event");
}
public void windowDeactivated(WindowEvent e) {
System.out.println("Window Deactivated Event");
}
public void windowStateChanged(WindowEvent e) {
System.out.println("Window State Changed Event");
}
public void windowGainedFocus(WindowEvent e) {
System.out.println("Window Gained Focus Event");
}
public void windowLostFocus(WindowEvent e) {
System.out.println("Window Lost Focus Event");
}
});
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
Hiding a Frame When Its Close Button Is Clicked
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Main {
public static void main() {
Frame frame = new Frame();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
Frame frame = (Frame) evt.getSource();
frame.setVisible(false);
// frame.dispose();
}
});
}
}
How to center a frame or dialog
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class CenteredFrame extends JFrame {
public CenteredFrame() {
setTitle("CenteredFrame");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
}
public static void main(String[] args) {
JFrame frame = new CenteredFrame();
frame.show();
}
}
Iconifies a frame; the maximized bits are not affected.
import java.awt.Frame;
public class Main {
public static void main() {
Frame frame = new Frame();
frame.setSize(300, 300);
frame.setVisible(true);
iconify(frame);
}
public static void iconify(Frame frame) {
int state = frame.getExtendedState();
// Set the iconified bit
state |= Frame.ICONIFIED;
// Iconify the frame
frame.setExtendedState(state);
}
}
JFrame that closes when someone presses the ESC key
/*
* jMemorize - Learning made easy (and fun) - A Leitner flashcards tool
* Copyright(C) 2004-2008 Riad Djemili and contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;
/**
* A advanced JFrame that closes when someone presses the ESC key.
*
* @author djemili
*/
public abstract class EscapableFrame extends JFrame
{
public EscapableFrame()
{
// on ESC key close frame
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "Cancel"); //$NON-NLS-1$
getRootPane().getActionMap().put("Cancel", new AbstractAction(){ //$NON-NLS-1$
public void actionPerformed(ActionEvent e)
{
close();
}
});
// on close window the close method is called
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt)
{
close();
}
});
}
/**
* Is called when the frame is closed by pressing ESC or closing it by
* clicking on the close icon.
*
* @return True if the frame got closed; false otherwise.
*/
abstract public boolean close();
}
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);
}
}
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);
}
}
Maximizes a frame; the iconified bit is not affected
import java.awt.Frame;
public class Main {
public static void main(String[] argv) throws Exception {
Frame frame = new Frame();
frame.setSize(300, 300);
frame.setVisible(true);
maximize(frame);
}
public static void maximize(Frame frame) {
int state = frame.getExtendedState();
// Set the maximized bits
state |= Frame.MAXIMIZED_BOTH;
// Maximize the frame
frame.setExtendedState(state);
}
}
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);
}
}
React to frame close action
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class CloseFrameAction extends JFrame {
public CloseFrameAction() {
setTitle("CloseableFrame");
setSize(300, 200);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
JFrame frame = new CloseFrameAction();
frame.show();
}
}
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();
}
}
Screen edge snapping
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ruponentAdapter;
import java.awt.event.ruponentEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class WindowSnapper extends ComponentAdapter {
private boolean locked = false;
private int sd = 50;
public void componentMoved(ComponentEvent evt) {
if (locked)
return;
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
int nx = evt.getComponent().getX();
int ny = evt.getComponent().getY();
// top
if (ny < 0 + sd) {
ny = 0;
}
// left
if (nx < 0 + sd) {
nx = 0;
}
// right
if (nx > size.getWidth() - evt.getComponent().getWidth() - sd) {
nx = (int) size.getWidth() - evt.getComponent().getWidth();
}
// bottom
if (ny > size.getHeight() - evt.getComponent().getHeight() - sd) {
ny = (int) size.getHeight() - evt.getComponent().getHeight();
}
// make sure we don"t get into a recursive loop when the
// set location generates more events
locked = true;
evt.getComponent().setLocation(nx, ny);
locked = false;
}
public static void main(String[] args) {
JFrame frame = new JFrame("");
JLabel label = new JLabel("Move this window"s title bar to demonstrate screen edge snapping.");
frame.getContentPane().add(label);
frame.pack();
frame.addComponentListener(new WindowSnapper());
frame.setVisible(true);
}
}
Setting the Bounds for a Maximized Frame
import java.awt.Frame;
import java.awt.Rectangle;
public class Main {
public static void main() {
Frame frame = new Frame();
Rectangle bounds = new Rectangle(20, 20, 200, 200);
frame.setMaximizedBounds(bounds);
frame.setVisible(true);
}
}
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);
}
}
Show the given frame as modal to the specified owner
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import javax.swing.JFrame;
// @author Santhosh Kumar T - santhosh@in.fiorano.ru
public class ModalFrameUtil {
static class EventPump implements InvocationHandler {
Frame frame;
public EventPump(Frame frame) {
this.frame = frame;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return frame.isShowing();
}
// when the reflection calls in this method has to be
// replaced once Sun provides a public API to pump events.
public void start() throws Exception {
Class<?> clazz = Class.forName("java.awt.Conditional");
Object conditional = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz },
this);
Method pumpMethod = Class.forName("java.awt.EventDispatchThread").getDeclaredMethod(
"pumpEvents", new Class[] { clazz });
pumpMethod.setAccessible(true);
pumpMethod.invoke(Thread.currentThread(), new Object[] { conditional });
}
}
// show the given frame as modal to the specified owner.
// NOTE: this method returns only after the modal frame is closed.
public static void showAsModal(final Frame frame, final Frame owner) {
frame.addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
owner.setEnabled(false);
}
public void windowClosing(WindowEvent e) {
owner.setEnabled(true);
frame.removeWindowListener(this);
}
public void windowClosed(WindowEvent e) {
owner.setEnabled(true);
frame.removeWindowListener(this);
}
});
owner.addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent e) {
if (frame.isShowing()) {
frame.setExtendedState(JFrame.NORMAL);
frame.toFront();
} else {
owner.removeWindowListener(this);
}
}
});
frame.setVisible(true);
try {
new EventPump(frame).start();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
}
The Swing Version of the Hello, World! Program
import javax.swing.JFrame;
public class HelloFrame extends JFrame {
public static void main(String[] args) {
new HelloFrame();
}
public HelloFrame() {
this.setSize(200, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Hello World!");
this.setVisible(true);
}
}
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);
}
}
Using anonymous inner classes
// : c14:Button2b.java
// Using anonymous inner classes.
// <applet code=Button2b width=200 height=75></applet>
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Button2b extends JApplet {
private JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2");
private JTextField txt = new JTextField(10);
private ActionListener bl = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = ((JButton) e.getSource()).getText();
txt.setText(name);
}
};
public void init() {
b1.addActionListener(bl);
b2.addActionListener(bl);
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1);
cp.add(b2);
cp.add(txt);
}
public static void main(String[] args) {
run(new Button2b(), 200, 75);
}
public static void run(JApplet applet, int width, int height) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(width, height);
applet.init();
applet.start();
frame.setVisible(true);
}
} ///:~