Java/Swing JFC/InternalFrame
Содержание
- 1 A few interesting things using JInternalFrames, JDesktopPane, and DesktopManager
- 2 A quick demonstration of setting up an internal frame in an application
- 3 A quick setting up an Internal Frame in an application
- 4 A simple extension of the JInternalFrame class that contains a list
- 5 Desktop Manager Demo
- 6 Implements InternalFrameListener
- 7 Interesting things using JInternalFrames, JDesktopPane, and DesktopManager 2
- 8 InternalFrame demo
- 9 InternalFrameEvent Demo
- 10 Internal Frame Listener Demo
- 11 Internal Frames Demo
- 12 Java X Windows
- 13 JDesktopPane Cascade Demo
- 14 JDesktopPane demo
- 15 Make a JInternalFrame a tool window
- 16 Move JInternalFrame To Front
- 17 Working with Internal Frames within a Desktop
A few interesting things using JInternalFrames, JDesktopPane, and DesktopManager
//An example that shows how to do a few interesting things using
//JInternalFrames, JDesktopPane, and DesktopManager.
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
public class Figure3 extends JFrame {
private JDesktopPane desk;
public Figure3(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
desk = new JDesktopPane();
setContentPane(desk);
}
private void addFrame(int number) {
JInternalFrame f = new JInternalFrame("Frame " + number, true, true,true, true);
f.setBounds(number * 10 - 5, number * 10 - 5, 250, 150);
desk.add(f, 1);
f.setVisible(true);
}
public static void main(String[] args) {
Figure3 td = new Figure3("");
td.setSize(300, 220);
td.setVisible(true);
for (int i = 1; i <= 4; i++) {
td.addFrame(i);
}
}
}
A quick demonstration of setting up an internal frame in an application
import java.awt.BorderLayout;
import java.awt.Frame;
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.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JLayeredPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SimpleInternalFrameDemo extends Frame {
JButton openButton, macButton, javaButton, motifButton, winButton;
JLayeredPane desktop;
JInternalFrame internalFrame;
public SimpleInternalFrameDemo() {
super("Internal Frame Demo");
setSize(500, 400);
openButton = new JButton("Open");
macButton = new JButton("Mac");
javaButton = new JButton("Metal");
motifButton = new JButton("Motif");
winButton = new JButton("Windows");
Panel p = new Panel();
p.add(openButton);
p.add(macButton);
p.add(javaButton);
p.add(motifButton);
p.add(winButton);
add(p, BorderLayout.SOUTH);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
openButton.addActionListener(new OpenListener());
LnFListener lnf = new LnFListener(this);
macButton.addActionListener(lnf);
javaButton.addActionListener(lnf);
motifButton.addActionListener(lnf);
winButton.addActionListener(lnf);
// Set up the layered pane
desktop = new JDesktopPane();
desktop.setOpaque(true);
add(desktop, BorderLayout.CENTER);
}
// An inner class to handle presses of the Open button
class OpenListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if ((internalFrame == null) || (internalFrame.isClosed())) {
internalFrame = new JInternalFrame("Internal Frame", true, true, true, true);
internalFrame.setBounds(50, 50, 200, 100);
desktop.add(internalFrame, new Integer(1));
internalFrame.setVisible(true);
}
}
}
public static void main(String args[]) {
SimpleInternalFrameDemo sif = new SimpleInternalFrameDemo();
sif.setVisible(true);
}
}
class LnFListener implements ActionListener {
Frame frame;
public LnFListener(Frame f) {
frame = f;
}
public void actionPerformed(ActionEvent e) {
String lnfName = null;
if (e.getActionCommand().equals("Mac")) {
lnfName = "com.apple.mrj.swing.MacLookAndFeel";
} else if (e.getActionCommand().equals("Metal")) {
lnfName = "javax.swing.plaf.metal.MetalLookAndFeel";
} else if (e.getActionCommand().equals("Motif")) {
lnfName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
} else if (e.getActionCommand().equals("Windows")) {
lnfName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
} else {
System.err.println("Unrecognized L&F request action: " + e.getActionCommand());
return;
}
try {
UIManager.setLookAndFeel(lnfName);
SwingUtilities.updateComponentTreeUI(frame);
} catch (UnsupportedLookAndFeelException ex1) {
System.err.println("Unsupported LookAndFeel: " + lnfName);
} catch (ClassNotFoundException ex2) {
System.err.println("LookAndFeel class not found: " + lnfName);
} catch (InstantiationException ex3) {
System.err.println("Could not load LookAndFeel: " + lnfName);
} catch (IllegalAccessException ex4) {
System.err.println("Cannot use LookAndFeel: " + lnfName);
}
}
}
A quick setting up an Internal Frame in an application
//A quick demonstration of setting up an Internal Frame in an application.
import java.awt.BorderLayout;
import java.awt.Frame;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class SimpleInternalFrame extends Frame {
JLayeredPane desktop;
JInternalFrame internalFrame;
public SimpleInternalFrame() {
super("");
setSize(500, 400);
desktop = new JDesktopPane();
desktop.setOpaque(true);
add(desktop, BorderLayout.CENTER);
internalFrame = new JInternalFrame("Meow", true, true, true, true);
internalFrame.setBounds(50, 50, 200, 100);
internalFrame.getContentPane().add(new JLabel(new ImageIcon("1.jpg")));
internalFrame.setVisible(true);
desktop.add(internalFrame, new Integer(1));
}
public static void main(String args[]) {
SimpleInternalFrame sif = new SimpleInternalFrame();
sif.setVisible(true);
}
}
A simple extension of the JInternalFrame class that contains a list
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// SiteFrame.java
//A simple extension of the JInternalFrame class that contains a list
//object. Elements of the list represent HTML pages for a web site.
//
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLayeredPane;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class SiteFrame extends JInternalFrame {
JList nameList;
SiteManager parent;
// Hardcode the pages of our "site" to keep things simple
String[] pages = { "index.html", "page1.html", "page2.html" };
public SiteFrame(String name, SiteManager sm) {
super("Site: " + name, true, true, true);
parent = sm;
setBounds(50, 50, 250, 100);
nameList = new JList(pages);
nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
nameList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent lse) {
// We know this is the list, so pop up the page.
if (!lse.getValueIsAdjusting()) {
parent.addPageFrame((String) nameList.getSelectedValue());
}
}
});
Container contentPane = getContentPane();
contentPane.add(nameList, BorderLayout.CENTER);
}
}
//A sample Swing application that manages several internal frames. This
//is the main class for working with the SiteFrame and PageFrame classes.
//
class SiteManager extends JFrame {
JLayeredPane desktop;
Vector popups = new Vector();
public SiteManager() {
super("Web Site Manager");
setSize(450, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
JToolBar jtb = new JToolBar();
jtb.add(new CutAction(this));
jtb.add(new CopyAction(this));
jtb.add(new PasteAction(this));
contentPane.add(jtb, BorderLayout.NORTH);
// Add our LayeredPane object for the internal frames.
desktop = new JDesktopPane();
contentPane.add(desktop, BorderLayout.CENTER);
addSiteFrame("Sample");
}
public static void main(String args[]) {
SiteManager mgr = new SiteManager();
mgr.setVisible(true);
}
// Methods to create our internal frames
public void addSiteFrame(String name) {
SiteFrame sf = new SiteFrame(name, this);
popups.addElement(sf);
desktop.add(sf, new Integer(2)); // Keep sites on top for now
sf.setVisible(true);
}
public void addPageFrame(String name) {
PageFrame pf = new PageFrame(name, this);
desktop.add(pf, new Integer(1));
pf.setVisible(true);
pf.setIconifiable(true);
popups.addElement(pf);
}
public JInternalFrame getCurrentFrame() {
for (int i = 0; i < popups.size(); i++) {
JInternalFrame currentFrame = (JInternalFrame) popups.elementAt(i);
if (currentFrame.isSelected()) {
return currentFrame;
}
}
return null;
}
}
class PasteAction extends AbstractAction {
SiteManager manager;
public PasteAction(SiteManager sm) {
super("", new ImageIcon("paste.gif"));
manager = sm;
}
public void actionPerformed(ActionEvent ae) {
JInternalFrame currentFrame = manager.getCurrentFrame();
if (currentFrame == null) {
return;
}
// cannot cut or paste sites
if (currentFrame instanceof SiteFrame) {
return;
}
((PageFrame) currentFrame).pasteText();
}
}
class PageFrame extends JInternalFrame implements ActionListener {
SiteManager parent;
String filename;
JTextArea ta;
public PageFrame(String name, SiteManager sm) {
super("Page: " + name, true, true, true, true);
parent = sm;
setBounds(50, 50, 300, 150);
Container contentPane = getContentPane();
// Create a text area to display the contents of our file in
// and stick it in a scrollable pane so we can see everything
ta = new JTextArea();
JScrollPane jsp = new JScrollPane(ta);
contentPane.add(jsp, BorderLayout.CENTER);
JMenuBar jmb = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem saveItem = new JMenuItem("Save");
saveItem.addActionListener(this);
fileMenu.add(saveItem);
jmb.add(fileMenu);
setJMenuBar(jmb);
filename = name;
loadContent();
}
public void actionPerformed(ActionEvent ae) {
// Can only be the save menu
saveContent();
}
public void loadContent() {
try {
FileReader fr = new FileReader(filename);
ta.read(fr, null);
fr.close();
} catch (Exception e) {
System.err.println("Could not load page: " + filename);
}
}
public void saveContent() {
try {
FileWriter fw = new FileWriter(filename);
ta.write(fw);
fw.close();
} catch (Exception e) {
System.err.println("Could not save page: " + filename);
}
}
public void cutText() {
ta.cut();
}
public void copyText() {
ta.copy();
}
public void pasteText() {
ta.paste();
}
}
class CutAction extends AbstractAction {
SiteManager manager;
public CutAction(SiteManager sm) {
super("", new ImageIcon("cut.gif"));
manager = sm;
}
public void actionPerformed(ActionEvent ae) {
JInternalFrame currentFrame = manager.getCurrentFrame();
if (currentFrame == null) {
return;
}
// cannot cut or paste sites
if (currentFrame instanceof SiteFrame) {
return;
}
((PageFrame) currentFrame).cutText();
}
}
class CopyAction extends AbstractAction {
SiteManager manager;
public CopyAction(SiteManager sm) {
super("", new ImageIcon("copy.gif"));
manager = sm;
}
public void actionPerformed(ActionEvent ae) {
JInternalFrame currentFrame = manager.getCurrentFrame();
if (currentFrame == null) {
return;
}
// can"t cut or paste sites
if (currentFrame instanceof SiteFrame) {
return;
}
((PageFrame) currentFrame).copyText();
}
}
Desktop Manager Demo
import java.beans.PropertyVetoException;
import javax.swing.border.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class DesktopManagerDemo extends JFrame implements ActionListener{
protected int m_count;
protected int m_tencount;
protected JButton m_newFrame;
protected JDesktopPane m_desktop;
protected JComboBox m_UIBox;
protected UIManager.LookAndFeelInfo[] m_infos;
protected JLabel m_lActivates, m_lBegindrags, m_lBeginresizes, m_lCloses,
m_lDeactivates, m_lDeiconifies, m_lDrags, m_lEnddrags, m_lEndresizes,
m_lIconifies, m_lMaximizes, m_lMinimizes, m_lOpens, m_lResizes, m_lSetbounds;
protected MyDesktopManager m_myDesktopManager;
protected DMEventCanvas m_dmEventCanvas;
protected Timer m_eventTimer;
public DesktopManagerDemo() {
setTitle("Animated DesktopManager");
m_count = m_tencount = 0;
JPanel innerListenerPanel = new JPanel(new GridLayout(15,1));
JPanel listenerPanel = new JPanel(new BorderLayout());
m_dmEventCanvas = new DMEventCanvas();
m_lActivates = new JLabel("activateFrame");
m_lBegindrags = new JLabel("beginDraggingFrame");
m_lBeginresizes = new JLabel("beginResizingFrame");
m_lCloses = new JLabel("closeFrame");
m_lDeactivates = new JLabel("deactivateFrame");
m_lDeiconifies = new JLabel("deiconifyFrame");
m_lDrags = new JLabel("dragFrame");
m_lEnddrags = new JLabel("endDraggingFrame");
m_lEndresizes = new JLabel("endResizingFrame");
m_lIconifies = new JLabel("iconifyFrame");
m_lMaximizes = new JLabel("maximizeFrame");
m_lMinimizes = new JLabel("minimizeFrame");
m_lOpens = new JLabel("openFrame");
m_lResizes = new JLabel("resizeFrame");
m_lSetbounds = new JLabel("setBoundsForFrame");
innerListenerPanel.add(m_lActivates);
innerListenerPanel.add(m_lBegindrags);
innerListenerPanel.add(m_lBeginresizes);
innerListenerPanel.add(m_lCloses);
innerListenerPanel.add(m_lDeactivates);
innerListenerPanel.add(m_lDeiconifies);
innerListenerPanel.add(m_lDrags);
innerListenerPanel.add(m_lEnddrags);
innerListenerPanel.add(m_lEndresizes);
innerListenerPanel.add(m_lIconifies);
innerListenerPanel.add(m_lMaximizes);
innerListenerPanel.add(m_lMinimizes);
innerListenerPanel.add(m_lOpens);
innerListenerPanel.add(m_lResizes);
innerListenerPanel.add(m_lSetbounds);
listenerPanel.add("Center", m_dmEventCanvas);
listenerPanel.add("West", innerListenerPanel);
listenerPanel.setOpaque(true);
listenerPanel.setBackground(Color.white);
m_myDesktopManager = new MyDesktopManager();
m_desktop = new JDesktopPane();
m_desktop.setDesktopManager(m_myDesktopManager);
m_desktop.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
m_newFrame = new JButton("New Frame");
m_newFrame.addActionListener(this);
m_infos = UIManager.getInstalledLookAndFeels();
String[] LAFNames = new String[m_infos.length];
for(int i=0; i<m_infos.length; i++) {
LAFNames[i] = m_infos[i].getName();
}
m_UIBox = new JComboBox(LAFNames);
m_UIBox.addActionListener(this);
JPanel topPanel = new JPanel(true);
topPanel.setLayout(new FlowLayout());
topPanel.setBorder(new CompoundBorder(
new SoftBevelBorder(BevelBorder.LOWERED),
new CompoundBorder(new EmptyBorder(2,2,2,2),
new SoftBevelBorder(BevelBorder.RAISED))));
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", topPanel);
getContentPane().add("Center", m_desktop);
getContentPane().add("South", listenerPanel);
((JPanel) getContentPane()).setBorder(new CompoundBorder(
new SoftBevelBorder(BevelBorder.LOWERED),
new CompoundBorder(new EmptyBorder(1,1,1,1),
new SoftBevelBorder(BevelBorder.RAISED))));
topPanel.add(m_newFrame);
topPanel.add(new JLabel("Look & Feel:",SwingConstants.RIGHT));
topPanel.add(m_UIBox);
setSize(645,600);
Dimension dim = getToolkit().getScreenSize();
setLocation(dim.width/2-getWidth()/2,
dim.height/2-getHeight()/2);
setVisible(true);
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(l);
m_eventTimer = new Timer(1000, this);
m_eventTimer.setRepeats(true);
m_eventTimer.start();
}
public void newFrame() {
JInternalFrame jif = new JInternalFrame("Frame " + m_count,
true, true, true, true);
jif.setBounds(20*(m_count%10) + m_tencount*80,
20*(m_count%10), 200, 200);
JLabel label = new JLabel();
label.setBackground(Color.white);
label.setOpaque(true);
jif.getContentPane().add(label);
m_desktop.add(jif);
try {
jif.setSelected(true);
}
catch (PropertyVetoException pve) {
System.out.println("Could not select " + jif.getTitle());
}
m_count++;
if (m_count%10 == 0) {
if (m_tencount < 3)
m_tencount++;
else
m_tencount = 0;
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == m_newFrame)
newFrame();
else if (e.getSource() == m_eventTimer) {
m_dmEventCanvas.render(m_myDesktopManager.getCounts());
m_myDesktopManager.clearCounts();
}
else if (e.getSource() == m_UIBox) {
try {
m_UIBox.hidePopup(); //BUG WORKAROUND
UIManager.setLookAndFeel(m_infos[m_UIBox.getSelectedIndex()].getClassName());
SwingUtilities.updateComponentTreeUI(this);
}
catch(Exception ex) {
System.out.println("Could not load " +
m_infos[m_UIBox.getSelectedIndex()].getClassName());
}
}
}
public static void main(String[] args) {
new DesktopManagerDemo();
}
}
class MyDesktopManager
extends DefaultDesktopManager
{
protected int[] m_counts = new int[15];
public void clearCounts() {
for (int i=0; i<15; i++) {
m_counts[i] = 0;
}
}
public int[] getCounts() { return m_counts; }
public void activateFrame(JInternalFrame f) {
super.activateFrame(f);
m_counts[0]++;
}
public void beginDraggingFrame(JComponent f) {
m_counts[1]++;
}
public void beginResizingFrame(JComponent f, int direction) {
m_counts[2]++;
}
public void closeFrame(JInternalFrame f) {
super.closeFrame(f);
m_counts[3]++;
}
public void deactivateFrame(JInternalFrame f) {
super.deactivateFrame(f);
m_counts[4]++;
}
public void deiconifyFrame(JInternalFrame f) {
super.deiconifyFrame(f);
m_counts[5]++;
}
public void dragFrame(JComponent f, int newX, int newY) {
f.setLocation(newX, newY);
m_counts[6]++;
}
public void endDraggingFrame(JComponent f) {
m_counts[7]++;
}
public void endResizingFrame(JComponent f) {
m_counts[8]++;
}
public void iconifyFrame(JInternalFrame f) {
super.iconifyFrame(f);
m_counts[9]++;
}
public void maximizeFrame(JInternalFrame f) {
super.maximizeFrame(f);
m_counts[10]++;
}
public void minimizeFrame(JInternalFrame f) {
super.minimizeFrame(f);
m_counts[11]++;
}
public void openFrame(JInternalFrame f) {
m_counts[12]++;
}
public void resizeFrame(JComponent f,
int newX, int newY, int newWidth, int newHeight) {
f.setBounds(newX, newY, newWidth, newHeight);
m_counts[13]++;
}
public void setBoundsForFrame(JComponent f,
int newX, int newY, int newWidth, int newHeight) {
f.setBounds(newX, newY, newWidth, newHeight);
m_counts[14]++;
}
}
class DMEventCanvas
extends JComponent
{
protected Color[] m_colors = new Color[15];
protected int[][] m_arrays = new int[15][12];
public DMEventCanvas() {
setPreferredSize(new Dimension(505,255));
for (int i=0; i<15; i++) {
m_arrays[i] = new int[12];
m_colors[i] = new Color(37+i*4, 37+i*4, 37+i*4);
}
}
public void paintEventSquare(Graphics g, int value, int currwidth,
int currheight, int cellwidth, int cellheight, Color color) {
if(value != 0) {
g.setColor(color);
g.fillRect(currwidth, currheight, cellwidth, cellheight);
g.setColor(Color.green);
g.drawString("" + value, currwidth + 5, currheight + 14);
}
g.setColor(Color.black);
g.drawRect(currwidth, currheight, cellwidth, cellheight);
}
public void paintComponent(Graphics g) {
int cellheight = 17;
int cellwidth = 42;
int currwidth = 0;
int currheight = 0;
for (int i=0; i < 12; i++) {
for (int j=0; j < 15; j++) {
paintEventSquare(g, m_arrays[j][i], currwidth, currheight,
cellwidth, cellheight, m_colors[j]);
currheight += cellheight;
}
currheight = 0;
currwidth += cellwidth;
}
}
public void render(int[] counts) {
for (int i=0; i < 11; i++) {
for (int j=0; j < 15; j++) {
m_arrays[j][i] = m_arrays[j][i+1];
}
}
for (int k=0; k < 15; k++) {
m_arrays[k][11] = counts[k];
}
paintImmediately(new Rectangle(20,20,505,255));
}
}
Implements InternalFrameListener
/* 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.
*/
/*
* InternalFrameEventDemo.java is a 1.4 example that requires no other files.
*/
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
public class InternalFrameEventDemo extends JFrame implements
InternalFrameListener, ActionListener {
JTextArea display;
JDesktopPane desktop;
JInternalFrame displayWindow;
JInternalFrame listenedToWindow;
static final String SHOW = "show";
static final String CLEAR = "clear";
String newline = "\n";
static final int desktopWidth = 500;
static final int desktopHeight = 300;
public InternalFrameEventDemo(String title) {
super(title);
//Set up the GUI.
desktop = new JDesktopPane();
desktop.putClientProperty("JDesktopPane.dragMode", "outline");
//Because we use pack, it"s not enough to call setSize.
//We must set the desktop"s preferred size.
desktop.setPreferredSize(new Dimension(desktopWidth, desktopHeight));
setContentPane(desktop);
createDisplayWindow();
desktop.add(displayWindow); //DON"T FORGET THIS!!!
Dimension displaySize = displayWindow.getSize();
displayWindow.setSize(desktopWidth, displaySize.height);
}
//Create the window that displays event information.
protected void createDisplayWindow() {
JButton b1 = new JButton("Show internal frame");
b1.setActionCommand(SHOW);
b1.addActionListener(this);
JButton b2 = new JButton("Clear event info");
b2.setActionCommand(CLEAR);
b2.addActionListener(this);
display = new JTextArea(3, 30);
display.setEditable(false);
JScrollPane textScroller = new JScrollPane(display);
//Have to supply a preferred size, or else the scroll
//area will try to stay as large as the text area.
textScroller.setPreferredSize(new Dimension(200, 75));
textScroller.setMinimumSize(new Dimension(10, 10));
displayWindow = new JInternalFrame("Event Watcher", true, //resizable
false, //not closable
false, //not maximizable
true); //iconifiable
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
b1.setAlignmentX(CENTER_ALIGNMENT);
contentPane.add(b1);
contentPane.add(Box.createRigidArea(new Dimension(0, 5)));
contentPane.add(textScroller);
contentPane.add(Box.createRigidArea(new Dimension(0, 5)));
b2.setAlignmentX(CENTER_ALIGNMENT);
contentPane.add(b2);
displayWindow.setContentPane(contentPane);
displayWindow.pack();
displayWindow.setVisible(true);
}
public void internalFrameClosing(InternalFrameEvent e) {
displayMessage("Internal frame closing", e);
}
public void internalFrameClosed(InternalFrameEvent e) {
displayMessage("Internal frame closed", e);
}
public void internalFrameOpened(InternalFrameEvent e) {
displayMessage("Internal frame opened", e);
}
public void internalFrameIconified(InternalFrameEvent e) {
displayMessage("Internal frame iconified", e);
}
public void internalFrameDeiconified(InternalFrameEvent e) {
displayMessage("Internal frame deiconified", e);
}
public void internalFrameActivated(InternalFrameEvent e) {
displayMessage("Internal frame activated", e);
}
public void internalFrameDeactivated(InternalFrameEvent e) {
displayMessage("Internal frame deactivated", e);
}
//Add some text to the text area.
void displayMessage(String prefix, InternalFrameEvent e) {
String s = prefix + ": " + e.getSource();
display.append(s + newline);
display.setCaretPosition(display.getDocument().getLength());
}
//Handle events on the two buttons.
public void actionPerformed(ActionEvent e) {
if (SHOW.equals(e.getActionCommand())) {
//They clicked the Show button.
//Create the internal frame if necessary.
if (listenedToWindow == null) {
listenedToWindow = new JInternalFrame("Event Generator", true, //resizable
true, //closable
true, //maximizable
true); //iconifiable
//We want to reuse the internal frame, so we need to
//make it hide (instead of being disposed of, which is
//the default) when the user closes it.
listenedToWindow
.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
//Add an internal frame listener so we can see
//what internal frame events it generates.
listenedToWindow.addInternalFrameListener(this);
//And we mustn"t forget to add it to the desktop pane!
desktop.add(listenedToWindow);
//Set its size and location. We"d use pack() to set the size
//if the window contained anything.
listenedToWindow.setSize(300, 100);
listenedToWindow.setLocation(desktopWidth / 2
- listenedToWindow.getWidth() / 2, desktopHeight
- listenedToWindow.getHeight());
}
//Show the internal frame.
listenedToWindow.setVisible(true);
} else { //They clicked the Clear button.
display.setText("");
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new InternalFrameEventDemo("InternalFrameEventDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//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();
}
});
}
}
Interesting things using JInternalFrames, JDesktopPane, and DesktopManager 2
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O"Reilly
*/
// SampleDesktop.java
//Another example that shows how to do a few interesting things using
//JInternalFrames, JDesktopPane, and DesktopManager.
//
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import javax.swing.AbstractAction;
import javax.swing.DefaultDesktopManager;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class SampleDesktop extends JFrame {
private JDesktopPane desk;
private IconPolice iconPolice = new IconPolice();
public SampleDesktop(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create a desktop and set it as the content pane. Don"t set the
// layered
// pane, since it needs to hold the menu bar too.
desk = new JDesktopPane();
setContentPane(desk);
// Install our custom desktop manager.
desk.setDesktopManager(new SampleDesktopMgr());
createMenuBar();
loadBackgroundImage();
}
// Create a menu bar to show off a few things.
protected void createMenuBar() {
JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("Frames");
menu.add(new AddFrameAction(true)); // add "upper" frame
menu.add(new AddFrameAction(false)); // add "lower" frame
menu.add(new TileAction(desk)); // add tiling capability
setJMenuBar(mb);
mb.add(menu);
}
// Here we load a background image for our desktop.
protected void loadBackgroundImage() {
ImageIcon icon = new ImageIcon("images/matterhorn.gif");
JLabel l = new JLabel(icon);
l.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight());
// Place the image in the lowest possible layer so nothing
// can ever be painted under it.
desk.add(l, new Integer(Integer.MIN_VALUE));
}
// This class adds a new JInternalFrame when requested.
class AddFrameAction extends AbstractAction {
public AddFrameAction(boolean upper) {
super(upper ? "Add Upper Frame" : "Add Lower Frame");
if (upper) {
this.layer = new Integer(2);
this.name = "Up";
} else {
this.layer = new Integer(1);
this.name = "Lo";
}
}
public void actionPerformed(ActionEvent ev) {
JInternalFrame f = new JInternalFrame(name, true, true, true, true);
f.addVetoableChangeListener(iconPolice);
f.setBounds(0, 0, 120, 60);
desk.add(f, layer);
f.setVisible(true); // Needed since 1.3
}
private Integer layer;
private String name;
}
// A simple vetoable change listener that insists that there is always at
// least one noniconified frame (just as an example of the vetoable
// properties).
class IconPolice implements VetoableChangeListener {
public void vetoableChange(PropertyChangeEvent ev)
throws PropertyVetoException {
String name = ev.getPropertyName();
if (name.equals(JInternalFrame.IS_ICON_PROPERTY)
&& (ev.getNewValue() == Boolean.TRUE)) {
JInternalFrame[] frames = desk.getAllFrames();
int count = frames.length;
int nonicons = 0; // how many are not icons?
for (int i = 0; i < count; i++) {
if (!frames[i].isIcon()) {
nonicons++;
}
}
if (nonicons <= 1) {
throw new PropertyVetoException("Invalid Iconification!",
ev);
}
}
}
}
// A simple test program.
public static void main(String[] args) {
SampleDesktop td = new SampleDesktop("Sample Desktop");
td.setSize(300, 220);
td.setVisible(true);
}
}
//TileAction.java
//An action that tiles all internal frames when requested.
//
class TileAction extends AbstractAction {
private JDesktopPane desk; // the desktop to work with
public TileAction(JDesktopPane desk) {
super("Tile Frames");
this.desk = desk;
}
public void actionPerformed(ActionEvent ev) {
// How many frames do we have?
JInternalFrame[] allframes = desk.getAllFrames();
int count = allframes.length;
if (count == 0)
return;
// Determine the necessary grid size
int sqrt = (int) Math.sqrt(count);
int rows = sqrt;
int cols = sqrt;
if (rows * cols < count) {
cols++;
if (rows * cols < count) {
rows++;
}
}
// Define some initial values for size & location.
Dimension size = desk.getSize();
int w = size.width / cols;
int h = size.height / rows;
int x = 0;
int y = 0;
// Iterate over the frames, deiconifying any iconified frames and then
// relocating & resizing each.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols && ((i * cols) + j < count); j++) {
JInternalFrame f = allframes[(i * cols) + j];
if (!f.isClosed() && f.isIcon()) {
try {
f.setIcon(false);
} catch (PropertyVetoException ignored) {
}
}
desk.getDesktopManager().resizeFrame(f, x, y, w, h);
x += w;
}
y += h; // start the next row
x = 0;
}
}
}
//SampleDesktopMgr.java
//A DesktopManager that keeps its frames inside the desktop.
class SampleDesktopMgr extends DefaultDesktopManager {
// This is called anytime a frame is moved. This
// implementation keeps the frame from leaving the desktop.
public void dragFrame(JComponent f, int x, int y) {
if (f instanceof JInternalFrame) { // Deal only w/internal frames
JInternalFrame frame = (JInternalFrame) f;
JDesktopPane desk = frame.getDesktopPane();
Dimension d = desk.getSize();
// Nothing all that fancy below, just figuring out how to adjust
// to keep the frame on the desktop.
if (x < 0) { // too far left?
x = 0; // flush against the left side
} else {
if (x + frame.getWidth() > d.width) { // too far right?
x = d.width - frame.getWidth(); // flush against right side
}
}
if (y < 0) { // too high?
y = 0; // flush against the top
} else {
if (y + frame.getHeight() > d.height) { // too low?
y = d.height - frame.getHeight(); // flush against the
// bottom
}
}
}
// Pass along the (possibly cropped) values to the normal drag handler.
super.dragFrame(f, x, y);
}
}
InternalFrame demo
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
public class DesktopSample {
public static void main(String[] args) {
String title = "Desktop Sample";
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JDesktopPane desktop = new JDesktopPane();
JInternalFrame internalFrames[] = {
new JInternalFrame("Can Do All", true, true, true, true),
new JInternalFrame("Not Resizable", false, true, true, true),
new JInternalFrame("Not Closable", true, false, true, true),
new JInternalFrame("Not Maximizable", true, true, false, true),
new JInternalFrame("Not Iconifiable", true, true, true, false) };
InternalFrameListener internalFrameListener = new InternalFrameIconifyListener();
for (int i = 0, n = internalFrames.length; i < n; i++) {
desktop.add(internalFrames[i]);
internalFrames[i].setBounds(i * 25, i * 25, 200, 100);
internalFrames[i].addInternalFrameListener(internalFrameListener);
JLabel label = new JLabel(internalFrames[i].getTitle(), JLabel.CENTER);
Container content = internalFrames[i].getContentPane();
content.add(label, BorderLayout.CENTER);
internalFrames[i].setVisible(true);
}
JInternalFrame palette = new JInternalFrame("Palette", true, false, true, false);
palette.setBounds(350, 150, 100, 100);
palette.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE);
desktop.add(palette, JDesktopPane.PALETTE_LAYER);
palette.setVisible(true);
desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
Container content = frame.getContentPane();
content.add(desktop, BorderLayout.CENTER);
frame.setSize(500, 300);
frame.setVisible(true);
}
}
class InternalFrameIconifyListener extends InternalFrameAdapter {
public void internalFrameIconified(InternalFrameEvent internalFrameEvent) {
JInternalFrame source = (JInternalFrame) internalFrameEvent.getSource();
System.out.println("Iconified: " + source.getTitle());
}
public void internalFrameDeiconified(InternalFrameEvent internalFrameEvent) {
JInternalFrame source = (JInternalFrame) internalFrameEvent.getSource();
System.out.println("Deiconified: " + source.getTitle());
}
}
InternalFrameEvent Demo
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
public class InternalFrameEventTest {
public static void main(String[] a) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
JLayeredPane desktop = new JDesktopPane();
desktop.setOpaque(false);
contentPane.add(desktop, BorderLayout.CENTER);
desktop.add(createLayer("One"), JLayeredPane.POPUP_LAYER);
desktop.add(createLayer("Two"), JLayeredPane.DEFAULT_LAYER);
desktop.add(createLayer("Three"), JLayeredPane.PALETTE_LAYER);
frame.setSize(400, 200);
frame.setVisible(true);
}
public static JInternalFrame createLayer(String label) {
return new SelfInternalFrame(label);
}
}
class SelfInternalFrame extends JInternalFrame {
public SelfInternalFrame(String s) {
getContentPane().add(new JLabel(s), BorderLayout.CENTER);
addInternalFrameListener(new InternalFrameListener() {
public void internalFrameActivated(InternalFrameEvent e) {
System.out.println("Activated" + e.getSource());
}
public void internalFrameClosed(InternalFrameEvent e) {
System.out.println("Closed");
}
public void internalFrameClosing(InternalFrameEvent e) {
System.out.println("Closing");
}
public void internalFrameDeactivated(InternalFrameEvent e) {
System.out.println("Deactivated");
}
public void internalFrameDeiconified(InternalFrameEvent e) {
System.out.println("Deiconified");
}
public void internalFrameIconified(InternalFrameEvent e) {
System.out.println("Iconified");
}
public void internalFrameOpened(InternalFrameEvent e) {
System.out.println("Opened");
}
});
setBounds(50, 50, 100, 100);
setResizable(true);
setClosable(true);
setMaximizable(true);
setIconifiable(true);
setTitle(s);
}
}
Internal Frame Listener Demo
import java.beans.PropertyVetoException;
import javax.swing.plaf.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class InternalFrameListenerDemo
extends JFrame
implements ActionListener, InternalFrameListener
{
protected int m_count;
protected int m_tencount;
private int[] m_counts = new int[7];
private int m_open, m_closing, m_close, m_iconify,
m_deiconify, m_activate, m_deactivate;
protected JButton m_newFrame;
protected JDesktopPane m_desktop;
protected JComboBox m_UIBox;
protected UIManager.LookAndFeelInfo[] m_infos;
private JLabel m_lOpened, m_lClosing, m_lClosed,
m_lIconified, m_lDeiconified, m_lActivated,
m_lDeactivated;
protected IFEventCanvas m_ifEventCanvas;
protected Timer m_eventTimer;
public InternalFrameListenerDemo() {
setTitle("Animated InternalFrameListener");
m_count = m_tencount = 0;
JPanel innerListenerPanel = new JPanel(new GridLayout(7,1));
JPanel listenerPanel = new JPanel(new BorderLayout());
m_ifEventCanvas = new IFEventCanvas();
m_lOpened = new JLabel("internalFrameOpened");
m_lClosing = new JLabel("internalFrameClosing");
m_lClosed = new JLabel("internalFrameClosed");
m_lIconified = new JLabel("internalFrameIconified");
m_lDeiconified = new JLabel("internalFrameDeiconified");
m_lActivated = new JLabel("internalFrameActivated");
m_lDeactivated = new JLabel("internalFrameDeactivated");
innerListenerPanel.add(m_lOpened);
innerListenerPanel.add(m_lClosing);
innerListenerPanel.add(m_lClosed);
innerListenerPanel.add(m_lIconified);
innerListenerPanel.add(m_lDeiconified);
innerListenerPanel.add(m_lActivated);
innerListenerPanel.add(m_lDeactivated);
listenerPanel.add("Center", m_ifEventCanvas);
listenerPanel.add("West", innerListenerPanel);
listenerPanel.setOpaque(true);
listenerPanel.setBackground(Color.white);
m_desktop = new JDesktopPane();
m_desktop.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
m_newFrame = new JButton("New Frame");
m_newFrame.addActionListener(this);
m_infos = UIManager.getInstalledLookAndFeels();
String[] LAFNames = new String[m_infos.length];
for(int i=0; i<m_infos.length; i++) {
LAFNames[i] = m_infos[i].getName();
}
m_UIBox = new JComboBox(LAFNames);
m_UIBox.addActionListener(this);
JPanel topPanel = new JPanel(true);
topPanel.setLayout(new FlowLayout());
topPanel.setBorder(new CompoundBorder(
new SoftBevelBorder(BevelBorder.LOWERED),
new CompoundBorder(new EmptyBorder(2,2,2,2),
new SoftBevelBorder(BevelBorder.RAISED))));
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", topPanel);
getContentPane().add("Center", m_desktop);
getContentPane().add("South", listenerPanel);
((JPanel) getContentPane()).setBorder(new CompoundBorder(
new SoftBevelBorder(BevelBorder.LOWERED),
new CompoundBorder(new EmptyBorder(1,1,1,1),
new SoftBevelBorder(BevelBorder.RAISED))));
topPanel.add(m_newFrame);
topPanel.add(new JLabel("Look & Feel:",SwingConstants.RIGHT));
topPanel.add(m_UIBox);
setSize(645,500);
Dimension dim = getToolkit().getScreenSize();
setLocation(dim.width/2-getWidth()/2,
dim.height/2-getHeight()/2);
setVisible(true);
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(l);
m_eventTimer = new Timer(1000, this);
m_eventTimer.setRepeats(true);
m_eventTimer.start();
}
public void newFrame() {
JInternalFrame jif = new JInternalFrame("Frame " + m_count,
true, true, true, true);
jif.addInternalFrameListener(this);
jif.setBounds(20*(m_count%10) + m_tencount*80,
20*(m_count%10), 200, 200);
JLabel label = new JLabel();
label.setBackground(Color.white);
label.setOpaque(true);
jif.getContentPane().add(label);
m_desktop.add(jif);
try {
jif.setSelected(true);
}
catch (PropertyVetoException pve) {
System.out.println("Could not select " + jif.getTitle());
}
m_count++;
if (m_count%10 == 0) {
if (m_tencount < 3)
m_tencount++;
else
m_tencount = 0;
}
}
public void clearCounts() {
for (int i=0; i<7; i++) {
m_counts[i] = 0;
}
}
public int[] getCounts() {
return m_counts;
}
public void internalFrameOpened(InternalFrameEvent e) {
m_counts[0]++;
}
public void internalFrameClosing(InternalFrameEvent e) {
m_counts[1]++;
}
public void internalFrameClosed(InternalFrameEvent e) {
m_counts[2]++;
}
public void internalFrameIconified(InternalFrameEvent e) {
m_counts[3]++;
}
public void internalFrameDeiconified(InternalFrameEvent e) {
m_counts[4]++;
}
public void internalFrameActivated(InternalFrameEvent e) {
m_counts[5]++;
}
public void internalFrameDeactivated(InternalFrameEvent e) {
m_counts[6]++;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == m_newFrame)
newFrame();
else if (e.getSource() == m_eventTimer) {
m_ifEventCanvas.render(getCounts());
clearCounts();
}
else if (e.getSource() == m_UIBox) {
try {
m_UIBox.hidePopup(); //BUG WORKAROUND
UIManager.setLookAndFeel(m_infos[m_UIBox.getSelectedIndex()].getClassName());
SwingUtilities.updateComponentTreeUI(this);
}
catch(Exception ex) {
System.out.println("Could not load " +
m_infos[m_UIBox.getSelectedIndex()].getClassName());
}
}
}
public static void main(String[] args) {
new InternalFrameListenerDemo();
}
}
class IFEventCanvas
extends JComponent
{
private Color[] m_colors = new Color[8];
private int[][] m_arrays = new int[15][12];
public IFEventCanvas() {
setPreferredSize(new Dimension(505,130));
for (int i=0; i<7; i++) {
m_arrays[i] = new int[12];
m_colors[i] = new Color(37+i*14, 37+i*14, 37+i*14);
}
}
public void paintEventSquare(Graphics g, int value, int currwidth,
int currheight, int cellwidth, int cellheight, Color color) {
if(value != 0) {
g.setColor(color);
g.fillRect(currwidth, currheight, cellwidth, cellheight);
g.setColor(Color.green);
g.drawString("" + value, currwidth + 5, currheight + 14);
}
g.setColor(Color.black);
g.drawRect(currwidth, currheight, cellwidth, cellheight);
}
public void paintComponent(Graphics g) {
int cellheight = 19;
int cellwidth = 40;
int currwidth = 0;
int currheight = 0;
for (int i=0; i < 12; i++) {
for (int j=0; j < 7; j++) {
paintEventSquare(g, m_arrays[j][i], currwidth, currheight,
cellwidth, cellheight, m_colors[j]);
currheight += cellheight;
}
currheight = 0;
currwidth += cellwidth;
}
}
public void render(int[] counts) {
for (int i=0; i < 11; i++) {
for (int j=0; j < 7; j++) {
m_arrays[j][i] = m_arrays[j][i+1];
}
}
for (int k=0; k < 7; k++) {
m_arrays[k][11] = counts[k];
}
paintImmediately(new Rectangle(0,0,505,130));
}
}
Internal Frames Demo
/*
* 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.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
/**
* Internal Frames Demo
*
* @version $Id: JIFrameDemo.java,v 1.4 2003/07/15 01:46:47 ian Exp $
*/
public class JIFrameDemo {
/* Main View */
public static void main(String[] a) {
final JFrame jf = new JFrame("JIFrameDemo Main Window");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
screenSize.width -= 42;
screenSize.height -= 42;
jf.setSize(screenSize);
jf.setLocation(20, 20);
JMenuBar mb = new JMenuBar();
jf.setJMenuBar(mb);
JMenu fm = new JMenu("File");
mb.add(fm);
JMenuItem mi;
fm.add(mi = new JMenuItem("Exit"));
mi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JDesktopPane dtp = new JDesktopPane();
//dtp.setBackground(Color.GREEN);
jf.setContentPane(dtp);
JInternalFrame mboxFrame = new JInternalFrame("Mail Reader", true,
true, true, true);
JLabel reader = new JLabel("Mail Reader Would Be Here");
mboxFrame.setContentPane(reader);
mboxFrame.setSize(400, 300);
mboxFrame.setLocation(50, 50);
mboxFrame.setVisible(true);
dtp.add(mboxFrame);
JInternalFrame compFrame = new JInternalFrame("Compose Mail", true,
true, true, true);
JLabel composer = new JLabel("Mail Compose Would Be Here");
compFrame.setContentPane(composer);
compFrame.setSize(300, 200);
compFrame.setLocation(200, 200);
compFrame.setVisible(true);
dtp.add(compFrame);
JInternalFrame listFrame = new JInternalFrame("Users", true, true,
true, true);
JLabel list = new JLabel("List of Users Would Be Here");
listFrame.setContentPane(list);
listFrame.setLocation(400, 400);
listFrame.setSize(500, 200);
listFrame.setVisible(true);
dtp.add(listFrame);
jf.setVisible(true);
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
jf.setVisible(false);
jf.dispose();
System.exit(0);
}
});
}
}
Java X Windows
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ruponentAdapter;
import java.awt.event.ruponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.beans.PropertyVetoException;
import java.io.FileReader;
import javax.swing.DefaultDesktopManager;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.event.MouseInputAdapter;
public class JavaXWin extends JFrame
{
protected int m_count;
protected int m_tencount;
protected int m_wmX, m_wmY;
protected JButton m_newFrame;
protected JDesktopPane m_desktop;
protected WindowManager m_wm;
protected JViewport viewport;
public JavaXWin() {
setTitle("JavaXWin");
m_count = m_tencount = 0;
m_desktop = new JDesktopPane();
JScrollPane scroller = new JScrollPane();
m_wm = new WindowManager(m_desktop);
m_desktop.setDesktopManager(m_wm);
m_desktop.add(m_wm.getWindowWatcher(),
JLayeredPane.PALETTE_LAYER);
m_wm.getWindowWatcher().setBounds(555,5,200,150);
viewport = new JViewport() {
public void setViewPosition(Point p) {
super.setViewPosition(p);
m_wm.getWindowWatcher().setLocation(
m_wm.getWindowWatcher().getX() +
(getViewPosition().x-m_wmX),
m_wm.getWindowWatcher().getY() +
(getViewPosition().y-m_wmY));
m_wmX = getViewPosition().x;
m_wmY = getViewPosition().y;
}
};
viewport.setView(m_desktop);
scroller.setViewport(viewport);
ComponentAdapter ca = new ComponentAdapter() {
JViewport view = viewport;
public void componentResized(ComponentEvent e) {
m_wm.getWindowWatcher().setLocation(
view.getViewPosition().x + view.getWidth()-
m_wm.getWindowWatcher().getWidth()-15,
view.getViewPosition().y + 5);
}
};
viewport.addComponentListener(ca);
m_newFrame = new JButton("New Frame");
m_newFrame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newFrame();
}
});
JPanel topPanel = new JPanel(true);
topPanel.setLayout(new FlowLayout());
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", topPanel);
getContentPane().add("Center", scroller);
topPanel.add(m_newFrame);
Dimension dim = getToolkit().getScreenSize();
setSize(800,600);
setLocation(dim.width/2-getWidth()/2,
dim.height/2-getHeight()/2);
m_desktop.setPreferredSize(new Dimension(1600,1200));
setVisible(true);
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(l);
}
public void newFrame() {
JInternalFrame jif = new JInternalFrame("Frame " + m_count,
true, true, true, true);
jif.setBounds(20*(m_count%10) + m_tencount*80,
20*(m_count%10), 200, 200);
JTextArea text = new JTextArea();
JScrollPane scroller = new JScrollPane();
scroller.getViewport().add(text);
try {
FileReader fileStream = new FileReader("");
text.read(fileStream, "JavaLinux.txt");
}
catch (Exception e) {
text.setText("* Could not read JavaLinux.txt *");
}
jif.getContentPane().add(scroller);
m_desktop.add(jif);
try {
jif.setSelected(true);
}
catch (PropertyVetoException pve) {
System.out.println("Could not select " + jif.getTitle());
}
m_count++;
if (m_count%10 == 0) {
if (m_tencount < 3)
m_tencount++;
else
m_tencount = 0;
}
}
public static void main(String[] args) {
new JavaXWin();
}
}
class WindowManager
extends DefaultDesktopManager
{
protected WindowWatcher ww;
public WindowManager(JDesktopPane desktop) {
ww = new WindowWatcher(desktop);
}
public WindowWatcher getWindowWatcher() { return ww; }
public void activateFrame(JInternalFrame f) {
super.activateFrame(f);
ww.repaint();
}
public void beginDraggingFrame(JComponent f) {
super.beginDraggingFrame(f);
ww.repaint();
}
public void beginResizingFrame(JComponent f, int direction) {
super.beginResizingFrame(f,direction);
ww.repaint();
}
public void closeFrame(JInternalFrame f) {
super.closeFrame(f);
ww.repaint();
}
public void deactivateFrame(JInternalFrame f) {
super.deactivateFrame(f);
ww.repaint();
}
public void deiconifyFrame(JInternalFrame f) {
super.deiconifyFrame(f);
ww.repaint();
}
public void dragFrame(JComponent f, int newX, int newY) {
f.setLocation(newX, newY);
ww.repaint();
}
public void endDraggingFrame(JComponent f) {
super.endDraggingFrame(f);
ww.repaint();
}
public void endResizingFrame(JComponent f) {
super.endResizingFrame(f);
ww.repaint();
}
public void iconifyFrame(JInternalFrame f) {
super.iconifyFrame(f);
ww.repaint();
}
public void maximizeFrame(JInternalFrame f) {
super.maximizeFrame(f);
ww.repaint();
}
public void minimizeFrame(JInternalFrame f) {
super.minimizeFrame(f);
ww.repaint();
}
public void openFrame(JInternalFrame f) {
super.openFrame(f);
ww.repaint();
}
public void resizeFrame(JComponent f,
int newX, int newY, int newWidth, int newHeight) {
f.setBounds(newX, newY, newWidth, newHeight);
ww.repaint();
}
public void setBoundsForFrame(JComponent f,
int newX, int newY, int newWidth, int newHeight) {
f.setBounds(newX, newY, newWidth, newHeight);
ww.repaint();
}
}
class WindowWatcher extends JPanel
{
protected static final Color C_UNSELECTED =
new Color(123, 123, 123);
protected static final Color C_SELECTED =
new Color(243, 232, 165);
protected static final Color C_BACKGROUND =
new Color(5,165,165);
protected static final Color C_WWATCHER =
new Color(203,226,0);
protected float m_widthratio, m_heightratio;
protected int m_width, m_height, m_XDifference, m_YDifference;
protected JDesktopPane m_desktop;
protected NorthResizeEdge m_northResizer;
protected SouthResizeEdge m_southResizer;
protected EastResizeEdge m_eastResizer;
protected WestResizeEdge m_westResizer;
public WindowWatcher(JDesktopPane desktop) {
m_desktop = desktop;
setOpaque(true);
m_northResizer = new NorthResizeEdge(this);
m_southResizer = new SouthResizeEdge(this);
m_eastResizer = new EastResizeEdge(this);
m_westResizer = new WestResizeEdge(this);
setLayout(new BorderLayout());
add(m_northResizer, BorderLayout.NORTH);
add(m_southResizer, BorderLayout.SOUTH);
add(m_eastResizer, BorderLayout.EAST);
add(m_westResizer, BorderLayout.WEST);
MouseInputAdapter ma = new MouseInputAdapter() {
public void mousePressed(MouseEvent e) {
m_XDifference = e.getX();
m_YDifference = e.getY();
}
public void mouseDragged(MouseEvent e) {
int vx = 0;
int vy = 0;
if (m_desktop.getParent() instanceof JViewport) {
vx = ((JViewport)
m_desktop.getParent()).getViewPosition().x;
vy = ((JViewport)
m_desktop.getParent()).getViewPosition().y;
}
int w = m_desktop.getParent().getWidth();
int h = m_desktop.getParent().getHeight();
int x = getX();
int y = getY();
int ex = e.getX();
int ey = e.getY();
if ((ey + y > vy && ey + y < h+vy) &&
(ex + x > vx && ex + x < w+vx))
{
setLocation(ex-m_XDifference + x, ey-m_YDifference + y);
}
else if (!(ey + y > vy && ey + y < h+vy) &&
(ex + x > vx && ex + x < w+vx))
{
if (!(ey + y > vy) && ey + y < h+vy)
setLocation(ex-m_XDifference + x, vy-m_YDifference);
else if (ey + y > vy && !(ey + y < h+vy))
setLocation(ex-m_XDifference + x, (h+vy)-m_YDifference);
}
else if ((ey + y >vy && ey + y < h+vy) &&
!(ex + x > vx && ex + x < w+vx))
{
if (!(ex + x > vx) && ex + x < w+vx)
setLocation(vx-m_XDifference, ey-m_YDifference + y);
else if (ex + x > vx && !(ex + x < w))
setLocation((w+vx)-m_XDifference, ey-m_YDifference + y);
}
else if (!(ey + y > vy) && ey + y < h+vy &&
!(ex + x > vx) && ex + x < w+vx)
setLocation(vx-m_XDifference, vy-m_YDifference);
else if (!(ey + y > vy) && ey + y < h+vy &&
ex + x > vx && !(ex + x < w+vx))
setLocation((w+vx)-m_XDifference, vy-m_YDifference);
else if (ey + y > vy && !(ey + y < h+vy) &&
!(ex + x > vx) && ex + x < w+vx)
setLocation(vx-m_XDifference, (h+vy)-m_YDifference);
else if (ey + y > vy && !(ey + y < h+vy) &&
ex + x > vx && !(ex + x < w+vx))
setLocation((w+vx)-m_XDifference, (h+vy)-m_YDifference);
}
public void mouseEntered(MouseEvent e) {
setCursor(Cursor.getPredefinedCursor(
Cursor.MOVE_CURSOR));
}
public void mouseExited(MouseEvent e) {
setCursor(Cursor.getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
m_height = getHeight();
m_width = getWidth();
g.setColor(C_BACKGROUND);
g.fillRect(0,0,m_width,m_height);
Component[] components = m_desktop.getComponents();
m_widthratio = ((float)
m_desktop.getWidth())/((float) m_width);
m_heightratio = ((float)
m_desktop.getHeight())/((float) m_height);
for (int i=components.length-1; i>-1; i--) {
if (components[i].isVisible()) {
g.setColor(C_UNSELECTED);
if (components[i] instanceof JInternalFrame) {
if (((JInternalFrame) components[i]).isSelected())
g.setColor(C_SELECTED);
}
else if(components[i] instanceof WindowWatcher)
g.setColor(C_WWATCHER);
g.fillRect(
(int)(((float)components[i].getX())/m_widthratio),
(int)(((float)components[i].getY())/m_heightratio),
(int)(((float)components[i].getWidth())/m_widthratio),
(int)(((float)components[i].getHeight())/m_heightratio));
g.setColor(Color.black);
g.drawRect(
(int)(((float)components[i].getX())/m_widthratio),
(int)(((float)components[i].getY())/m_heightratio),
(int)(((float)components[i].getWidth())/m_widthratio),
(int)(((float)components[i].getHeight())/m_heightratio));
}
}
g.drawLine(m_width/2,0,m_width/2,m_height);
g.drawLine(0,m_height/2,m_width,m_height/2);
}
}
class EastResizeEdge extends JPanel
implements MouseListener, MouseMotionListener {
private int WIDTH = 3;
private int MIN_WIDTH = 50;
private boolean m_dragging;
private JComponent m_resizeComponent;
public EastResizeEdge(JComponent c) {
m_resizeComponent = c;
addMouseListener(this);
addMouseMotionListener(this);
setOpaque(true);
setBackground(Color.black);
}
public Dimension getPreferredSize() {
return new Dimension(WIDTH, m_resizeComponent.getHeight());
}
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {
m_dragging = false;
}
public void mouseDragged(MouseEvent e) {
if (m_resizeComponent.getWidth() + e.getX() >= MIN_WIDTH)
m_resizeComponent.setBounds(m_resizeComponent.getX(),
m_resizeComponent.getY(),
m_resizeComponent.getWidth() + e.getX(),
m_resizeComponent.getHeight());
else
m_resizeComponent.setBounds(m_resizeComponent.getX(),
m_resizeComponent.getY(),
MIN_WIDTH, m_resizeComponent.getHeight());
m_resizeComponent.validate();
}
public void mouseEntered(MouseEvent e) {
if (!m_dragging)
setCursor(Cursor.getPredefinedCursor(
Cursor.E_RESIZE_CURSOR));
}
public void mouseExited(MouseEvent e) {
if (!m_dragging)
setCursor(Cursor.getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
}
public void mousePressed(MouseEvent e) {
//toFront();
m_dragging = true;
}
}
class NorthResizeEdge extends JPanel
implements MouseListener, MouseMotionListener {
private static final int NORTH = 0;
private static final int NORTHEAST = 1;
private static final int NORTHWEST = 2;
private int CORNER = 10;
private int HEIGHT = 3;
private int MIN_WIDTH = 50;
private int MIN_HEIGHT = 50;
private int m_width, m_dragX, m_dragY, m_rightX, m_lowerY;
private boolean m_dragging;
private JComponent m_resizeComponent;
private int m_mode;
public NorthResizeEdge(JComponent c) {
m_resizeComponent = c;
addMouseListener(this);
addMouseMotionListener(this);
setOpaque(true);
setBackground(Color.black);
}
public Dimension getPreferredSize() {
return new Dimension(m_resizeComponent.getWidth(), HEIGHT);
}
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {
if (!m_dragging) {
if (e.getX() < CORNER) {
setCursor(Cursor.getPredefinedCursor(
Cursor.NW_RESIZE_CURSOR));
}
else if(e.getX() > getWidth()-CORNER) {
setCursor(Cursor.getPredefinedCursor(
Cursor.NE_RESIZE_CURSOR));
}
else {
setCursor(Cursor.getPredefinedCursor(
Cursor.N_RESIZE_CURSOR));
}
}
}
public void mouseReleased(MouseEvent e) {
m_dragging = false;
}
public void mouseDragged(MouseEvent e) {
int h = m_resizeComponent.getHeight();
int w = m_resizeComponent.getWidth();
int x = m_resizeComponent.getX();
int y = m_resizeComponent.getY();
int ex = e.getX();
int ey = e.getY();
switch (m_mode) {
case NORTH:
if (h-(ey-m_dragY) >= MIN_HEIGHT)
m_resizeComponent.setBounds(x, y + (ey-m_dragY),
w, h-(ey-m_dragY));
else
m_resizeComponent.setBounds(x,
m_lowerY-MIN_HEIGHT, w, MIN_HEIGHT);
break;
case NORTHEAST:
if (h-(ey-m_dragY) >= MIN_HEIGHT
&& w + (ex-(getWidth()-CORNER)) >= MIN_WIDTH)
m_resizeComponent.setBounds(x,
y + (ey-m_dragY), w + (ex-(getWidth()-CORNER)),
h-(ey-m_dragY));
else if (h-(ey-m_dragY) >= MIN_HEIGHT
&& !(w + (ex-(getWidth()-CORNER)) >= MIN_WIDTH))
m_resizeComponent.setBounds(x,
y + (ey-m_dragY), MIN_WIDTH, h-(ey-m_dragY));
else if (!(h-(ey-m_dragY) >= MIN_HEIGHT)
&& w + (ex-(getWidth()-CORNER)) >= MIN_WIDTH)
m_resizeComponent.setBounds(x,
m_lowerY-MIN_HEIGHT, w + (ex-(getWidth()-CORNER)),
MIN_HEIGHT);
else
m_resizeComponent.setBounds(x,
m_lowerY-MIN_HEIGHT, MIN_WIDTH, MIN_HEIGHT);
break;
case NORTHWEST:
if (h-(ey-m_dragY) >= MIN_HEIGHT
&& w-(ex-m_dragX) >= MIN_WIDTH)
m_resizeComponent.setBounds(x + (ex-m_dragX),
y + (ey-m_dragY), w-(ex-m_dragX),
h-(ey-m_dragY));
else if (h-(ey-m_dragY) >= MIN_HEIGHT
&& !(w-(ex-m_dragX) >= MIN_WIDTH)) {
if (x + MIN_WIDTH < m_rightX)
m_resizeComponent.setBounds(m_rightX-MIN_WIDTH,
y + (ey-m_dragY), MIN_WIDTH, h-(ey-m_dragY));
else
m_resizeComponent.setBounds(x,
y + (ey-m_dragY), w, h-(ey-m_dragY));
}
else if (!(h-(ey-m_dragY) >= MIN_HEIGHT)
&& w-(ex-m_dragX) >= MIN_WIDTH)
m_resizeComponent.setBounds(x + (ex-m_dragX),
m_lowerY-MIN_HEIGHT, w-(ex-m_dragX), MIN_HEIGHT);
else
m_resizeComponent.setBounds(m_rightX-MIN_WIDTH,
m_lowerY-MIN_HEIGHT, MIN_WIDTH, MIN_HEIGHT);
break;
}
m_rightX = x + w;
m_resizeComponent.validate();
}
public void mouseEntered(MouseEvent e) {
mouseMoved(e);
}
public void mouseExited(MouseEvent e) {
if (!m_dragging)
setCursor(Cursor.getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
}
public void mousePressed(MouseEvent e) {
m_dragging = true;
m_dragX = e.getX();
m_dragY = e.getY();
m_lowerY = m_resizeComponent.getY()
+ m_resizeComponent.getHeight();
if (e.getX() < CORNER) {
m_mode = NORTHWEST;
}
else if(e.getX() > getWidth()-CORNER) {
m_mode = NORTHEAST;
}
else {
m_mode = NORTH;
}
}
}
class SouthResizeEdge extends JPanel
implements MouseListener, MouseMotionListener {
private static final int SOUTH = 0;
private static final int SOUTHEAST = 1;
private static final int SOUTHWEST = 2;
private int CORNER = 10;
private int HEIGHT = 3;
private int MIN_WIDTH = 50;
private int MIN_HEIGHT = 50;
private int m_width, m_dragX, m_dragY, m_rightX;
private boolean m_dragging;
private JComponent m_resizeComponent;
private int m_mode;
public SouthResizeEdge(JComponent c) {
m_resizeComponent = c;
addMouseListener(this);
addMouseMotionListener(this);
setOpaque(true);
setBackground(Color.black);
}
public Dimension getPreferredSize() {
return new Dimension(m_resizeComponent.getWidth(), HEIGHT);
}
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {
if (!m_dragging) {
if (e.getX() < CORNER) {
setCursor(Cursor.getPredefinedCursor(
Cursor.SW_RESIZE_CURSOR));
}
else if(e.getX() > getWidth()-CORNER) {
setCursor(Cursor.getPredefinedCursor(
Cursor.SE_RESIZE_CURSOR));
}
else {
setCursor(Cursor.getPredefinedCursor(
Cursor.S_RESIZE_CURSOR));
}
}
}
public void mouseReleased(MouseEvent e) {
m_dragging = false;
}
public void mouseDragged(MouseEvent e) {
int h = m_resizeComponent.getHeight();
int w = m_resizeComponent.getWidth();
int x = m_resizeComponent.getX();
int y = m_resizeComponent.getY();
int ex = e.getX();
int ey = e.getY();
switch (m_mode) {
case SOUTH:
if (h+(ey-m_dragY) >= MIN_HEIGHT)
m_resizeComponent.setBounds(x, y, w, h+(ey-m_dragY));
else
m_resizeComponent.setBounds(x, y, w, MIN_HEIGHT);
break;
case SOUTHEAST:
if (h+(ey-m_dragY) >= MIN_HEIGHT
&& w + (ex-(getWidth()-CORNER)) >= MIN_WIDTH)
m_resizeComponent.setBounds(x, y,
w + (ex-(getWidth()-CORNER)), h+(ey-m_dragY));
else if (h+(ey-m_dragY) >= MIN_HEIGHT
&& !(w + (ex-(getWidth()-CORNER)) >= MIN_WIDTH))
m_resizeComponent.setBounds(x, y,
MIN_WIDTH, h+(ey-m_dragY));
else if (!(h+(ey-m_dragY) >= MIN_HEIGHT)
&& w + (ex-(getWidth()-CORNER)) >= MIN_WIDTH)
m_resizeComponent.setBounds(x, y,
w + (ex-(getWidth()-CORNER)), MIN_HEIGHT);
else
m_resizeComponent.setBounds(x,
y, MIN_WIDTH, MIN_HEIGHT);
break;
case SOUTHWEST:
if (h+(ey-m_dragY) >= MIN_HEIGHT
&& w-(ex-m_dragX) >= MIN_WIDTH)
m_resizeComponent.setBounds(x + (ex-m_dragX), y,
w-(ex-m_dragX), h+(ey-m_dragY));
else if (h+(ey-m_dragY) >= MIN_HEIGHT
&& !(w-(ex-m_dragX) >= MIN_WIDTH)) {
if (x + MIN_WIDTH < m_rightX)
m_resizeComponent.setBounds(m_rightX-MIN_WIDTH, y,
MIN_WIDTH, h+(ey-m_dragY));
else
m_resizeComponent.setBounds(x, y, w,
h+(ey-m_dragY));
}
else if (!(h+(ey-m_dragY) >= MIN_HEIGHT)
&& w-(ex-m_dragX) >= MIN_WIDTH)
m_resizeComponent.setBounds(x + (ex-m_dragX), y,
w-(ex-m_dragX), MIN_HEIGHT);
else
m_resizeComponent.setBounds(m_rightX-MIN_WIDTH,
y, MIN_WIDTH, MIN_HEIGHT);
break;
}
m_rightX = x + w;
m_resizeComponent.validate();
}
public void mouseEntered(MouseEvent e) {
mouseMoved(e);
}
public void mouseExited(MouseEvent e) {
if (!m_dragging)
setCursor(Cursor.getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
}
public void mousePressed(MouseEvent e) {
//toFront();
m_dragging = true;
m_dragX = e.getX();
m_dragY = e.getY();
if (e.getX() < CORNER) {
m_mode = SOUTHWEST;
}
else if(e.getX() > getWidth()-CORNER) {
m_mode = SOUTHEAST;
}
else {
m_mode = SOUTH;
}
}
}
class WestResizeEdge extends JPanel
implements MouseListener, MouseMotionListener {
private int WIDTH = 3;
private int MIN_WIDTH = 50;
private int m_dragX, m_rightX;
private boolean m_dragging;
private JComponent m_resizeComponent;
public WestResizeEdge(JComponent c) {
m_resizeComponent = c;
addMouseListener(this);
addMouseMotionListener(this);
setOpaque(true);
setBackground(Color.black);
}
public Dimension getPreferredSize() {
return new Dimension(WIDTH, m_resizeComponent.getHeight());
}
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {
m_dragging = false;
}
public void mouseDragged(MouseEvent e) {
if (m_resizeComponent.getWidth()-
(e.getX()-m_dragX) >= MIN_WIDTH)
m_resizeComponent.setBounds(
m_resizeComponent.getX() + (e.getX()-m_dragX),
m_resizeComponent.getY(),
m_resizeComponent.getWidth()-(e.getX()-m_dragX),
m_resizeComponent.getHeight());
else
if (m_resizeComponent.getX() + MIN_WIDTH < m_rightX)
m_resizeComponent.setBounds(m_rightX-MIN_WIDTH,
m_resizeComponent.getY(),
MIN_WIDTH, m_resizeComponent.getHeight());
else
m_resizeComponent.setBounds(m_resizeComponent.getX(),
m_resizeComponent.getY(),
MIN_WIDTH, m_resizeComponent.getHeight());
m_resizeComponent.validate();
}
public void mouseEntered(MouseEvent e) {
if (!m_dragging)
setCursor(Cursor.getPredefinedCursor(
Cursor.W_RESIZE_CURSOR));
}
public void mouseExited(MouseEvent e) {
if (!m_dragging)
setCursor(Cursor.getPredefinedCursor(
Cursor.DEFAULT_CURSOR));
}
public void mousePressed(MouseEvent e) {
//toFront();
m_rightX = m_resizeComponent.getX() +
m_resizeComponent.getWidth();
m_dragging = true;
m_dragX = e.getX();
}
}
JDesktopPane Cascade Demo
import java.beans.PropertyVetoException;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CascadeDemo extends JFrame implements ActionListener{
private static ImageIcon EARTH;
private int m_count;
private int m_tencount;
private JButton m_newFrame;
private JDesktopPane m_desktop;
private JComboBox m_UIBox;
private UIManager.LookAndFeelInfo[] m_infos;
public CascadeDemo() {
super("CascadeDemo");
EARTH = new ImageIcon("earth.jpg");
m_count = m_tencount = 0;
m_desktop = new JDesktopPane();
m_desktop.putClientProperty("JDesktopPane.dragMode","outline");
m_newFrame = new JButton("New Frame");
m_newFrame.addActionListener(this);
m_infos = UIManager.getInstalledLookAndFeels();
String[] LAFNames = new String[m_infos.length];
for(int i=0; i<m_infos.length; i++) {
LAFNames[i] = m_infos[i].getName();
}
m_UIBox = new JComboBox(LAFNames);
m_UIBox.addActionListener(this);
JPanel topPanel = new JPanel(true);
topPanel.add(m_newFrame);
topPanel.add(new JLabel("Look & Feel:",SwingConstants.RIGHT));
topPanel.add(m_UIBox);
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", topPanel);
getContentPane().add("Center", m_desktop);
setSize(570,400);
Dimension dim = getToolkit().getScreenSize();
setLocation(dim.width/2-getWidth()/2,
dim.height/2-getHeight()/2);
setVisible(true);
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(l);
}
public void newFrame() {
JInternalFrame jif = new JInternalFrame("Frame " + m_count,
true, true, true, true);
jif.setBounds(20*(m_count%10) + m_tencount*80,
20*(m_count%10), 200, 200);
JLabel label = new JLabel(EARTH);
jif.getContentPane().add(new JScrollPane(label));
m_desktop.add(jif);
try {
jif.setSelected(true);
}
catch (PropertyVetoException pve) {
System.out.println("Could not select " + jif.getTitle());
}
m_count++;
if (m_count%10 == 0) {
if (m_tencount < 3)
m_tencount++;
else
m_tencount = 0;
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == m_newFrame)
newFrame();
else if (e.getSource() == m_UIBox) {
m_UIBox.hidePopup(); // BUG WORKAROUND
try {
UIManager.setLookAndFeel(m_infos[m_UIBox.getSelectedIndex()].getClassName());
SwingUtilities.updateComponentTreeUI(this);
}
catch(Exception ex) {
System.out.println("Could not load " +
m_infos[m_UIBox.getSelectedIndex()].getClassName());
}
}
}
public static void main(String[] args) {
new CascadeDemo();
}
}
JDesktopPane demo
/*
Definitive Guide to Swing for Java 2, Second Edition
By John Zukowski
ISBN: 1-893115-78-X
Publisher: APress
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Polygon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Examples {
public static void main(String args[]) {
JFrame frame = new JFrame("Example Popup");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(0, 1));
JFrame frame2 = new JFrame("Desktop");
final JDesktopPane desktop = new JDesktopPane();
frame2.getContentPane().add(desktop);
JButton pick = new JButton("Pick");
pick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Hi");
}
});
frame2.getContentPane().add(pick, BorderLayout.SOUTH);
JButton messagePopup = new JButton("Message");
contentPane.add(messagePopup);
messagePopup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Component source = (Component) actionEvent.getSource();
JOptionPane.showMessageDialog(source, "Printing complete");
JOptionPane.showInternalMessageDialog(desktop,
"Printing complete");
}
});
JButton confirmPopup = new JButton("Confirm");
contentPane.add(confirmPopup);
confirmPopup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Component source = (Component) actionEvent.getSource();
JOptionPane.showConfirmDialog(source, "Continue printing?");
JOptionPane.showInternalConfirmDialog(desktop,
"Continue printing?");
}
});
JButton inputPopup = new JButton("Input");
contentPane.add(inputPopup);
inputPopup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Component source = (Component) actionEvent.getSource();
JOptionPane.showInputDialog(source, "Enter printer name:");
// Moons of Neptune
String smallList[] = { "Naiad", "Thalassa", "Despina",
"Galatea", "Larissa", "Proteus", "Triton", "Nereid" };
JOptionPane.showInternalInputDialog(desktop, "Pick a printer",
"Input", JOptionPane.QUESTION_MESSAGE, null, smallList,
"Triton");
// Moons of Saturn - includes two provisional designations to
// make 20
String bigList[] = { "Pan", "Atlas", "Prometheus", "Pandora",
"Epimetheus", "Janus", "Mimas", "Enceladus", "Tethys",
"Telesto", "Calypso", "Dione", "Helene", "Rhea",
"Titan", "Hyperion", "Iapetus", "Phoebe", "S/1995 S 2",
"S/1981 S 18" };
// Object saturnMoon = JOptionPane.showInputDialog(source, "Pick
// a printer", "Input", JOptionPane.QUESTION_MESSAGE, null,
// bigList, "Titan");
Object saturnMoon = JOptionPane.showInputDialog(source,
"Pick a printer", "Input",
JOptionPane.QUESTION_MESSAGE, null, bigList, null);
System.out.println("Saturn Moon: " + saturnMoon);
}
});
JButton optionPopup = new JButton("Option");
contentPane.add(optionPopup);
optionPopup.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Component source = (Component) actionEvent.getSource();
Icon greenIcon = new DiamondIcon(Color.green);
Icon redIcon = new DiamondIcon(Color.red);
Object iconArray[] = { greenIcon, redIcon };
JOptionPane.showOptionDialog(source, "Continue printing?",
"Select an Option", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, iconArray,
iconArray[1]);
Icon blueIcon = new DiamondIcon(Color.blue);
Object stringArray[] = { "Do It", "No Way" };
JOptionPane.showInternalOptionDialog(desktop,
"Continue printing?", "Select an Option",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, blueIcon, stringArray,
stringArray[0]);
}
});
frame.setSize(300, 200);
frame.setVisible(true);
frame2.setSize(300, 200);
frame2.setVisible(true);
}
}
class DiamondIcon implements Icon {
private Color color;
private boolean selected;
private int width;
private int height;
private Polygon poly;
private static final int DEFAULT_WIDTH = 10;
private static final int DEFAULT_HEIGHT = 10;
public DiamondIcon(Color color) {
this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public DiamondIcon(Color color, boolean selected) {
this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public DiamondIcon(Color color, boolean selected, int width, int height) {
this.color = color;
this.selected = selected;
this.width = width;
this.height = height;
initPolygon();
}
private void initPolygon() {
poly = new Polygon();
int halfWidth = width / 2;
int halfHeight = height / 2;
poly.addPoint(0, halfHeight);
poly.addPoint(halfWidth, 0);
poly.addPoint(width, halfHeight);
poly.addPoint(halfWidth, height);
}
public int getIconHeight() {
return height;
}
public int getIconWidth() {
return width;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
g.translate(x, y);
if (selected) {
g.fillPolygon(poly);
} else {
g.drawPolygon(poly);
}
g.translate(-x, -y);
}
}
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);
}
}
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);
}
}
}
}
Working with Internal Frames within a Desktop
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
public class InternalTest {
public static void main(String args[]) {
JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
JLayeredPane desktop = new JDesktopPane();
desktop.setOpaque(false);
desktop.add(createLayer("One"), JLayeredPane.POPUP_LAYER);
desktop.add(createLayer("Two"), JLayeredPane.DEFAULT_LAYER);
desktop.add(createLayer("Three"), JLayeredPane.PALETTE_LAYER);
contentPane.add(desktop, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.show();
}
static JInternalFrame createLayer(String label) {
return new SelfInternalFrame(label);
}
static class SelfInternalFrame extends JInternalFrame {
public SelfInternalFrame(String s) {
getContentPane().add(new JLabel(s, JLabel.CENTER),
BorderLayout.CENTER);
setBounds(50, 50, 100, 100);
setResizable(true);
setClosable(true);
setMaximizable(true);
setIconifiable(true);
setTitle(s);
setVisible(true);
}
}
}