Java Tutorial/Swing/JComponent — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:31, 31 мая 2010
Содержание
- 1 A panel that displays a paint sample.
- 2 A Swing component that computes and displays a fractal image known as a "Julia set"
- 3 Extends JComponent to create drawing pad
- 4 how an icon is adapted to a component
- 5 HTML formatting by setting the text on a label
- 6 JComponent
- 7 Listening to Inherited Events of a JComponent from Container and Component
- 8 Painting JComponent Objects
A panel that displays a paint sample.
/*
* JCommon : a free general purpose class library for the Java(tm) platform
*
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ----------------
* PaintSample.java
* ----------------
* (C) Copyright 2000-2004, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* $Id: PaintSample.java,v 1.5 2007/11/02 17:50:36 taqua Exp $
*
* Changes (from 26-Oct-2001)
* --------------------------
* 26-Oct-2001 : Changed package to com.jrefinery.ui.*;
* 14-Oct-2002 : Fixed errors reported by Checkstyle (DG);
*
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Paint;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
/**
* A panel that displays a paint sample.
*
* @author David Gilbert
*/
public class PaintSample extends JComponent {
/** The paint. */
private Paint paint;
/** The preferred size of the component. */
private Dimension preferredSize;
/**
* Standard constructor - builds a paint sample.
*
* @param paint the paint to display.
*/
public PaintSample(final Paint paint) {
this.paint = paint;
this.preferredSize = new Dimension(80, 12);
}
/**
* Returns the current Paint object being displayed in the panel.
*
* @return the paint.
*/
public Paint getPaint() {
return this.paint;
}
/**
* Sets the Paint object being displayed in the panel.
*
* @param paint the paint.
*/
public void setPaint(final Paint paint) {
this.paint = paint;
repaint();
}
/**
* Returns the preferred size of the component.
*
* @return the preferred size.
*/
public Dimension getPreferredSize() {
return this.preferredSize;
}
/**
* Fills the component with the current Paint.
*
* @param g the graphics device.
*/
public void paintComponent(final Graphics g) {
final Graphics2D g2 = (Graphics2D) g;
final Dimension size = getSize();
final Insets insets = getInsets();
final double xx = insets.left;
final double yy = insets.top;
final double ww = size.getWidth() - insets.left - insets.right - 1;
final double hh = size.getHeight() - insets.top - insets.bottom - 1;
final Rectangle2D area = new Rectangle2D.Double(xx, yy, ww, hh);
g2.setPaint(this.paint);
g2.fill(area);
g2.setPaint(Color.black);
g2.draw(area);
}
}
A Swing component that computes and displays a fractal image known as a "Julia set"
/*
* Copyright (c) 2004 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book,
* please visit http://www.davidflanagan.ru/javaexamples3.
*/
//package je3.print;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.JobAttributes;
import java.awt.PageAttributes;
import java.awt.PrintJob;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
/**
* This class is a Swing component that computes and displays a fractal image
* known as a "Julia set". The print() method demonstrates printing with the
* Java 1.1 printing API, and is the main point of the example. The code that
* computes the Julia set uses complex numbers, and you don"t need to understand
* it.
*/
public class JuliaSet1 extends JComponent {
// These constants are hard-coded for simplicity
double x1 = -1.5, y1 = -1.5, x2 = 1.5, y2 = 1.5; // Region of complex plane
int width = 400, height = 400; // Mapped to these pixels
double cx, cy; // This complex constant defines the set we display
BufferedImage image; // The image we compute
// We compute values between 0 and 63 for each point in the complex plane.
// This array holds the color values for each of those values.
static int[] colors;
static { // Static initializer for the colors[] array.
colors = new int[64];
for (int i = 0; i < colors.length; i++) {
colors[63 - i] = (i * 4 << 16) + (i * 4 << 8) + i * 4; // grayscale
// (i*4) ^ ((i * 3)<<6) ^ ((i * 7)<<13); // crazy technicolor
}
}
// No-arg constructor with default values for cx, cy.
public JuliaSet1() {
this(-1, 0);
}
// This constructor specifies the {cx,cy} constant.
// For simplicity, the other constants remain hardcoded.
public JuliaSet1(double cx, double cy) {
this.cx = cx;
this.cy = cy;
setPreferredSize(new Dimension(width, height));
computeImage();
}
// This method computes a color value for each pixel of the image
void computeImage() {
// Create the image
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Now loop through the pixels
int i, j;
double x, y;
double dx = (x2 - x1) / width;
double dy = (y2 - y1) / height;
for (j = 0, y = y1; j < height; j++, y += dy) {
for (i = 0, x = x1; i < width; i++, x += dx) {
// For each pixel, call testPoint() to determine a value.
// Then map that value to a color and set it in the image.
// If testPoint() returns 0, the point is part of the Julia set
// and is displayed in black. If it returns 63, the point is
// displayed in white. Values in-between are displayed in
// varying shades of gray.
image.setRGB(i, j, colors[testPoint(x, y)]);
}
}
}
// This is the key method for computing Julia sets. For each point z
// in the complex plane, we repeatedly compute z = z*z + c using complex
// arithmetic. We stop iterating when the magnitude of z exceeds 2 or
// after 64 iterations. We return the number of iterations-1.
public int testPoint(double zx, double zy) {
for (int i = 0; i < colors.length; i++) {
// Compute z = z*z + c;
double newx = zx * zx - zy * zy + cx;
double newy = 2 * zx * zy + cy;
zx = newx;
zy = newy;
// Check magnitude of z and return iteration number
if (zx * zx + zy * zy > 4)
return i;
}
return colors.length - 1;
}
// This method overrides JComponent to display the julia set.
// Just scale the image to fit and draw it.
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
// This method demonstrates the Java 1.1 java.awt.PrintJob printing API.
// It also demonstrates the JobAttributes and PageAttributes classes
// added in Java 1.3. Display the Julia set with ShowBean and use
// the Command menu to invoke this print command.
public void print() {
// Create some attributes objects. This is Java 1.3 stuff.
// In Java 1.1, we"d use a java.util.Preferences object instead.
JobAttributes jattrs = new JobAttributes();
PageAttributes pattrs = new PageAttributes();
// Set some example attributes: monochrome, landscape mode
pattrs.setColor(PageAttributes.ColorType.MONOCHROME);
pattrs.setOrientationRequested(PageAttributes.OrientationRequestedType.LANDSCAPE);
// Print to file by default
jattrs.setDestination(JobAttributes.DestinationType.FILE);
jattrs.setFileName("juliaset.ps");
// Look up the Frame that holds this component
Component frame = this;
while (!(frame instanceof Frame))
frame = frame.getParent();
// Get a PrintJob object to print the Julia set with.
// The getPrintJob() method displays a print dialog and allows the user
// to override and modify the default JobAttributes and PageAttributes
Toolkit toolkit = this.getToolkit();
PrintJob job = toolkit.getPrintJob((Frame) frame, "JuliaSet1", jattrs, pattrs);
// We get a null PrintJob if the user clicked cancel
if (job == null)
return;
// Get a Graphics object from the PrintJob.
// We print simply by drawing to this Graphics object.
Graphics g = job.getGraphics();
// Center the image on the page
Dimension pagesize = job.getPageDimension(); // how big is page?
Dimension panesize = this.getSize(); // how big is image?
g.translate((pagesize.width - panesize.width) / 2, // center it
(pagesize.height - panesize.height) / 2);
// Draw a box around the Julia Set and label it
g.drawRect(-1, -1, panesize.width + 2, panesize.height + 2);
g.drawString("Julia Set for c={" + cx + "," + cy + "}", 0, -15);
// Set a clipping region
g.setClip(0, 0, panesize.width, panesize.height);
// Now print the component by calling its paint method
this.paint(g);
// Finally tell the printer we"re done with the page.
// No output will be generated if we don"t call dispose() here.
g.dispose();
}
}
Extends JComponent to create drawing pad
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
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.JComponent;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
final DrawPad drawPad = new DrawPad();
frame.add(drawPad, BorderLayout.CENTER);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawPad.clear();
}
});
frame.add(clearButton, BorderLayout.SOUTH);
frame.setSize(280, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class DrawPad extends JComponent {
Image image;
Graphics2D graphics2D;
int currentX, currentY, oldX, oldY;
public DrawPad() {
setDoubleBuffered(false);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
currentX = e.getX();
currentY = e.getY();
if (graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
});
}
public void paintComponent(Graphics g) {
if (image == null) {
image = createImage(getSize().width, getSize().height);
graphics2D = (Graphics2D) image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
clear();
}
g.drawImage(image, 0, 0, null);
}
public void clear() {
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
graphics2D.setPaint(Color.black);
repaint();
}
}
how an icon is adapted to a component
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class IconAdapterTester {
public static void main(String[] args) {
Icon icon = new MyIcon(300);
JComponent component = new IconAdapter(icon);
JFrame frame = new JFrame();
frame.add(component, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
class IconAdapter extends JComponent {
public IconAdapter(Icon icon) {
this.icon = icon;
}
public void paintComponent(Graphics g) {
icon.paintIcon(this, g, 0, 0);
}
public Dimension getPreferredSize() {
return new Dimension(icon.getIconWidth(), icon.getIconHeight());
}
private Icon icon;
}
class MyIcon implements Icon {
public MyIcon(int aWidth) {
width = aWidth;
}
public int getIconWidth() {
return width;
}
public int getIconHeight() {
return width / 2;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g;
Rectangle2D.Double body = new Rectangle2D.Double(x, y + width / 6,
width - 1, width / 6);
Ellipse2D.Double frontTire = new Ellipse2D.Double(x + width / 6, y + width
/ 3, width / 6, width / 6);
Ellipse2D.Double rearTire = new Ellipse2D.Double(x + width * 2 / 3, y
+ width / 3, width / 6, width / 6);
g2.fill(frontTire);
g2.fill(rearTire);
g2.setColor(Color.BLACK);
g2.fill(body);
}
private int width;
}
HTML formatting by setting the text on a label
The components that supported HTML:
- JButton,
- JLabel,
- JMenuItem,
- JMenu,
- JRadioButtonMenuItem,
- JCheckBoxMenuItem,
- JTabbedPane,
- JToolTip,
- JToggleButton,
- JCheckBox,
- JRadioButton.
/*
*
* Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
*
* Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
* modify and redistribute this software in source and binary code form,
* provided that i) this copyright notice and license appear on all copies of
* the software; and ii) Licensee does not utilize the software in a manner
* which is disparaging to Sun.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
* LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
* INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
* CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
* OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*
* This software is not designed or intended for use in on-line control of
* aircraft, air traffic, aircraft navigation or aircraft communications; or in
* the design, construction, operation or maintenance of any nuclear
* facility. Licensee represents and warrants that it will not use or
* redistribute the Software for such purposes.
*/
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
/* HtmlDemo.java needs no other files. */
public class HtmlDemo extends JPanel implements ActionListener {
JLabel theLabel;
JTextArea htmlTextArea;
public HtmlDemo() {
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
String initialText = "<html>\n" + "Color and font test:\n" + "<ul>\n"
+ "<li><font color=red>red</font>\n" + "<li><font color=blue>blue</font>\n"
+ "<li><font color=green>green</font>\n" + "<li><font size=-2>small</font>\n"
+ "<li><font size=+2>large</font>\n" + "<li><i>italic</i>\n" + "<li><b>bold</b>\n"
+ "</ul>\n";
htmlTextArea = new JTextArea(10, 20);
htmlTextArea.setText(initialText);
JScrollPane scrollPane = new JScrollPane(htmlTextArea);
JButton changeTheLabel = new JButton("Change the label");
changeTheLabel.setMnemonic(KeyEvent.VK_C);
changeTheLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
changeTheLabel.addActionListener(this);
theLabel = new JLabel(initialText) {
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public Dimension getMinimumSize() {
return new Dimension(200, 200);
}
public Dimension getMaximumSize() {
return new Dimension(200, 200);
}
};
theLabel.setVerticalAlignment(SwingConstants.CENTER);
theLabel.setHorizontalAlignment(SwingConstants.CENTER);
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
leftPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory
.createTitledBorder("Edit the HTML, then click the button"), BorderFactory
.createEmptyBorder(10, 10, 10, 10)));
leftPanel.add(scrollPane);
leftPanel.add(Box.createRigidArea(new Dimension(0, 10)));
leftPanel.add(changeTheLabel);
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
rightPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory
.createTitledBorder("A label with HTML"), BorderFactory.createEmptyBorder(10, 10, 10, 10)));
rightPanel.add(theLabel);
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
add(leftPanel);
add(Box.createRigidArea(new Dimension(10, 0)));
add(rightPanel);
}
// React to the user pushing the Change button.
public void actionPerformed(ActionEvent e) {
theLabel.setText(htmlTextArea.getText());
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("HtmlDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new HtmlDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// 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();
}
});
}
}
JComponent
All Swing components derive from the abstract javax.swing.JComponent class. The following are the JComponent class"s methods to manipulate the appearance of the component.
public int getWidth ()Returns the current width of this component in pixel.public int getHeight ()Returns the current height of this component in pixel.public int getX()Returns the current x coordinate of the component"s top-left corner.public int getY ()Returns the current y coordinate of the component"s top-left corner.public java.awt.Graphics getGraphics()Returns this component"s Graphics object you can draw on. This is useful if you want to change the appearance of a component.public void setBackground (java.awt.Color bg)Sets this component"s background color.public void setEnabled (boolean enabled)Sets whether or not this component is enabled.public void setFont (java.awt.Font font)Set the font used to print text on this component.public void setForeground (java.awt.Color fg)Set this component"s foreground color.public void setToolTipText(java.lang.String text)Sets the tool tip text.public void setVisible (boolean visible)Sets whether or not this component is visible.
Listening to Inherited Events of a JComponent from Container and Component
Class Event Listener Event Object
Component ComponentListener componentHidden(ComponentEvent)
componentMoved(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)
Component FocusListener focusGained(FocusEvent)
focusLost(FocusEvent)
Component HierarchyBoundsListener ancestorMoved(HierarchyEvent)
ancestorResized(HierarchyEvent)
Component HierarchyListener hierarchyChanged(HierarchyEvent)
Component InputMethodListener caretPositionChanged (InputMethodEvent)
inputMethodTextChanged (InputMethodEvent)
Component KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
Component MouseListener mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
Component MouseMotionListener mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
Component MouseWheelListener mouseWheelMoved(MouseWheelEvent)
Container ContainerListener componentAdded(ContainerEvent)
Painting JComponent Objects
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyComponent extends JComponent {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Customize after calling super.paintComponent(g)
g.drawString("string",20,20);
}
}
public class PaintingJComponentObjects {
public static void main(String[] args) {
JFrame aWindow = new JFrame();
aWindow.setBounds(30, 30, 300, 300); // Size
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyComponent com = new MyComponent();
aWindow.add(com);
aWindow.setVisible(true); // Display the window
}
}