Java Tutorial/Swing/JPanel
Содержание
A basic panel that displays a small up or down arrow.
<source lang="java">
/*
* 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.] * * --------------- * ArrowPanel.java * --------------- * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: ArrowPanel.java,v 1.6 2007/11/02 17:50:36 taqua Exp $ * * Changes * ------- * 25-Sep-2002 : Version 1 (DG); * 13-Oct-2002 : Added Javadocs (DG); * */
import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Polygon; import java.awt.Shape; import java.awt.geom.Rectangle2D; import javax.swing.JPanel; /**
* A basic panel that displays a small up or down arrow. * * @author David Gilbert */
public class ArrowPanel extends JPanel {
/** A constant for the up arrow. */ public static final int UP = 0; /** A constant for the down arrow. */ public static final int DOWN = 1; /** The arrow type. */ private int type = UP; /** The available area. */ private Rectangle2D available = new Rectangle2D.Float(); /** * Creates a new arrow panel. * * @param type * the arrow type. */ public ArrowPanel(final int type) { this.type = type; setPreferredSize(new Dimension(14, 9)); } /** * Paints the arrow panel. * * @param g * the graphics device for drawing on. */ public void paintComponent(final Graphics g) { super.paintComponent(g); final Graphics2D g2 = (Graphics2D) g; // first determine the size of the drawing area... final Dimension size = getSize(); final Insets insets = getInsets(); this.available.setRect(insets.left, insets.top, size.getWidth() - insets.left - insets.right, size.getHeight() - insets.top - insets.bottom); g2.translate(insets.left, insets.top); g2.fill(getArrow(this.type)); } /** * Returns a shape for the arrow. * * @param t * the arrow type. * * @return the arrow shape. */ private Shape getArrow(final int t) { switch (t) { case UP: return getUpArrow(); case DOWN: return getDownArrow(); default: return getUpArrow(); } } /** * Returns an up arrow. * * @return an up arrow. */ private Shape getUpArrow() { final Polygon result = new Polygon(); result.addPoint(7, 2); result.addPoint(2, 7); result.addPoint(12, 7); return result; } /** * Returns a down arrow. * * @return a down arrow. */ private Shape getDownArrow() { final Polygon result = new Polygon(); result.addPoint(7, 7); result.addPoint(2, 2); result.addPoint(12, 2); return result; }
}</source>
A JPanel with a textured background.
<source lang="java">
/*
* TexturedPanel.java * 2006-11-02 */
//cb.aloe.decor; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Insets; import java.awt.Paint; import java.awt.Rectangle; import java.awt.TexturePaint; import java.awt.image.BufferedImage; import javax.swing.Icon; import javax.swing.JPanel; /**
* A JPanel with a textured background. * * @author Christopher Bach */
public class TexturedPanel extends JPanel {
private TexturePaint ourPainter = null; private Color ourDefaultForeground = Color.white; private Color ourDefaultBackground = Color.gray; /** * Creates a new TexturedPanel with a simple striped pattern. */ public TexturedPanel() { super(); ourDefaultForeground = Color.white; ourDefaultBackground = getBackground(); setupDefaultPainter(ourDefaultForeground, ourDefaultBackground); } /** * Creates a new TexturedPanel with a simple striped pattern consisting of the * given foreground and background colors. */ public TexturedPanel(Color foreground, Color background) { super(); ourDefaultForeground = (foreground != null ? foreground : Color.white); ourDefaultBackground = (background != null ? background : getBackground()); setupDefaultPainter(ourDefaultForeground, ourDefaultBackground); } /** * Creates a new TexturedPanel with a simple pattern based on the provided * texture map and consisting of the given foreground and background colors. */ public TexturedPanel(Color foreground, Color background, boolean[][] texture) { super(); ourDefaultForeground = (foreground != null ? foreground : Color.white); ourDefaultBackground = (background != null ? background : getBackground()); setupTexturePainter(ourDefaultForeground, ourDefaultBackground, texture, 1); } /** * Creates a new TexturedPanel with a simple pattern based on the provided * texture map and consisting of the given foreground and background colors. */ public TexturedPanel(Color foreground, Color background, boolean[][] texture, int scale) { super(); ourDefaultForeground = (foreground != null ? foreground : Color.white); ourDefaultBackground = (background != null ? background : getBackground()); setupTexturePainter(ourDefaultForeground, ourDefaultBackground, texture, scale); } /** * Creates a new TexturedPanel that tiles the provided image. */ public TexturedPanel(Image texture) { super(); ourDefaultForeground = Color.white; ourDefaultBackground = getBackground(); if (texture != null) setupImagePainter(texture); else setupDefaultPainter(ourDefaultForeground, ourDefaultBackground); } /** * Creates a new TexturedPanel that tiles the provided icon. */ public TexturedPanel(Icon textureIcon) { super(); ourDefaultForeground = Color.white; ourDefaultBackground = getBackground(); if (textureIcon != null) { setupIconPainter(textureIcon); } else setupDefaultPainter(ourDefaultForeground, ourDefaultBackground); } /** * Sets up this TexturedPanel to paint a simple background based on the * provided texture and consisting of the provided colors. */ public void setTexture(Color foreground, Color background, boolean[][] texture) { if (foreground != null && background != null && texture != null && texture.length > 0 && texture[0].length > 0) { setupTexturePainter(foreground, background, texture, 1); } } /** * */ public void setTexture(Color foreground, Color background, boolean[][] texture, int scale) { setupTexturePainter(foreground, background, texture, scale); } /** * Sets up this TexturedPanel to paint a striped background consisting of the * provided colors. */ public void setTextureColors(Color foreground, Color background) { if (foreground != null && background != null) { ourDefaultForeground = foreground; ourDefaultBackground = background; setupDefaultPainter(foreground, background); } } /** * Sets up this TexturedPanel to paint a tiled background consisting of the * provided image. If the image is null, the background will revert to a * striped texture consisting of the last known colors. */ public void setTextureImage(Image texture) { if (texture != null) setupImagePainter(texture); else setupDefaultPainter(ourDefaultForeground, ourDefaultBackground); } /** * Sets up this TexturedPanel to paint a tiled background consisting of the * provided icon. If the icon is null, the background will revert to a striped * texture consisting of the last known colors. */ public void setTextureIcon(Icon textureIcon) { if (textureIcon != null) { setupIconPainter(textureIcon); } else setupDefaultPainter(ourDefaultForeground, ourDefaultBackground); } /** * Returns the image buffer used by this TexturedPanel"s painter. */ public Image getTexture() { if (ourPainter == null) return null; else return ourPainter.getImage(); } /** * Creates a new TexturePaint using the provided colors. */ private void setupDefaultPainter(Color foreground, Color background) { if (foreground == null || background == null) { ourPainter = null; return; } BufferedImage buff = new BufferedImage(6, 6, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2 = buff.createGraphics(); g2.setColor(background); g2.fillRect(0, 0, 6, 6); g2.setColor(foreground); g2.drawLine(0, 2, 6, 2); g2.drawLine(0, 5, 6, 5); ourPainter = new TexturePaint(buff, new Rectangle(0, 0, 6, 6)); g2.dispose(); } /** * Creates a new TexturePaint using the provided colors and texture map. */ private void setupTexturePainter(Color foreground, Color background, boolean[][] texture, int scale) { if (texture == null || texture.length < 1 || texture[0].length < 1) { setupDefaultPainter(foreground, background); return; } else if (foreground == null || background == null) { ourPainter = null; return; } scale = Math.max(1, scale); int w = texture[0].length; int h = texture.length; BufferedImage buff = new BufferedImage(w * scale, h * scale, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2 = buff.createGraphics(); g2.setColor(background); g2.fillRect(0, 0, w * scale, h * scale); g2.setColor(foreground); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { try { if (texture[i][j]) g2.fillRect(j * scale, i * scale, scale, scale); } // g2.drawLine(j, i, j, i); } catch (ArrayIndexOutOfBoundsException aob) { } } } ourPainter = new TexturePaint(buff, new Rectangle(0, 0, w * scale, h * scale)); g2.dispose(); } /** * Creates a new TexturePaint using the provided image. */ private void setupImagePainter(Image texture) { if (texture == null) { ourPainter = null; return; } int w = texture.getWidth(this); int h = texture.getHeight(this); if (w <= 0 || h <= 0) { ourPainter = null; return; } BufferedImage buff = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2 = buff.createGraphics(); g2.drawImage(texture, 0, 0, this); ourPainter = new TexturePaint(buff, new Rectangle(0, 0, w, h)); g2.dispose(); } /** * Creates a new TexturePaint using the provided icon. */ private void setupIconPainter(Icon texture) { if (texture == null) { ourPainter = null; return; } int w = texture.getIconWidth(); int h = texture.getIconHeight(); if (w <= 0 || h <= 0) { ourPainter = null; return; } BufferedImage buff = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2 = buff.createGraphics(); texture.paintIcon(this, g2, 0, 0); ourPainter = new TexturePaint(buff, new Rectangle(0, 0, w, h)); g2.dispose(); } /** * Paints this component with its textured background. */ protected void paintComponent(Graphics g) { super.paintComponent(g); if (ourPainter != null) { int w = getWidth(); int h = getHeight(); Insets in = getInsets(); int x = in.left; int y = in.top; w = w - in.left - in.right; h = h - in.top - in.bottom; if (w >= 0 && h >= 0) { Graphics2D g2 = (Graphics2D) g; Paint pt = g2.getPaint(); g2.setPaint(ourPainter); g2.fillRect(x, y, w, h); g2.setPaint(pt); } } }
}</source>
A panel that allows the user to select a date.
<source lang="java">
/*
* 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.] * * --------------------- * DateChooserPanel.java * --------------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: DateChooserPanel.java,v 1.11 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.* (DG); * 08-Dec-2001 : Dropped the getMonths() method (DG); * 13-Oct-2002 : Fixed errors reported by Checkstyle (DG); * 02-Nov-2005 : Fixed a bug where the current day-of-the-month is past * the end of the newly selected month when the month or year * combo boxes are changed - see bug id 1344319 (DG); * */
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.Date; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.UIManager; /**
* A panel that allows the user to select a date. * * @author David Gilbert */
public class DateChooserPanel extends JPanel implements ActionListener {
/** * The date selected in the panel. */ private Calendar chosenDate; /** * The color for the selected date. */ private Color chosenDateButtonColor; /** * The color for dates in the current month. */ private Color chosenMonthButtonColor; /** * The color for dates that are visible, but not in the current month. */ private Color chosenOtherButtonColor; /** * The first day-of-the-week. */ private int firstDayOfWeek; /** * The range used for selecting years. */ private int yearSelectionRange = 20; /** * The font used to display the date. */ private Font dateFont = new Font("SansSerif", Font.PLAIN, 10); /** * A combo for selecting the month. */ private JComboBox monthSelector; /** * A combo for selecting the year. */ private JComboBox yearSelector; /** * A button for selecting today"s date. */ private JButton todayButton; /** * An array of buttons used to display the days-of-the-month. */ private JButton[] buttons; /** * A flag that indicates whether or not we are currently refreshing the * buttons. */ private boolean refreshing = false; /** * The ordered set of all seven days of a week, * beginning with the "firstDayOfWeek". */ private int[] WEEK_DAYS; /** * Constructs a new date chooser panel, using today"s date as the initial * selection. */ public DateChooserPanel() { this(Calendar.getInstance(), false); } /** * Constructs a new date chooser panel. * * @param calendar the calendar controlling the date. * @param controlPanel a flag that indicates whether or not the "today" * button should appear on the panel. */ public DateChooserPanel(final Calendar calendar, final boolean controlPanel) { super(new BorderLayout()); this.chosenDateButtonColor = UIManager.getColor("textHighlight"); this.chosenMonthButtonColor = UIManager.getColor("control"); this.chosenOtherButtonColor = UIManager.getColor("controlShadow"); // the default date is today... this.chosenDate = calendar; this.firstDayOfWeek = calendar.getFirstDayOfWeek(); this.WEEK_DAYS = new int[7]; for (int i = 0; i < 7; i++) { this.WEEK_DAYS[i] = ((this.firstDayOfWeek + i - 1) % 7) + 1; } add(constructSelectionPanel(), BorderLayout.NORTH); add(getCalendarPanel(), BorderLayout.CENTER); if (controlPanel) { add(constructControlPanel(), BorderLayout.SOUTH); } setDate(calendar.getTime()); } /** * Sets the date chosen in the panel. * * @param theDate the new date. */ public void setDate(final Date theDate) { this.chosenDate.setTime(theDate); this.monthSelector.setSelectedIndex(this.chosenDate.get( Calendar.MONTH)); refreshYearSelector(); refreshButtons(); } /** * Returns the date selected in the panel. * * @return the selected date. */ public Date getDate() { return this.chosenDate.getTime(); } /** * Handles action-events from the date panel. * * @param e information about the event that occurred. */ public void actionPerformed(final ActionEvent e) { if (e.getActionCommand().equals("monthSelectionChanged")) { final JComboBox c = (JComboBox) e.getSource(); // In most cases, changing the month will not change the selected // day. But if the selected day is 29, 30 or 31 and the newly // selected month doesn"t have that many days, we revert to the // last day of the newly selected month... int dayOfMonth = this.chosenDate.get(Calendar.DAY_OF_MONTH); this.chosenDate.set(Calendar.DAY_OF_MONTH, 1); this.chosenDate.set(Calendar.MONTH, c.getSelectedIndex()); int maxDayOfMonth = this.chosenDate.getActualMaximum( Calendar.DAY_OF_MONTH); this.chosenDate.set(Calendar.DAY_OF_MONTH, Math.min(dayOfMonth, maxDayOfMonth)); refreshButtons(); } else if (e.getActionCommand().equals("yearSelectionChanged")) { if (!this.refreshing) { final JComboBox c = (JComboBox) e.getSource(); final Integer y = (Integer) c.getSelectedItem(); // in most cases, changing the year will not change the // selected day. But if the selected day is Feb 29, and the // newly selected year is not a leap year, we revert to // Feb 28... int dayOfMonth = this.chosenDate.get(Calendar.DAY_OF_MONTH); this.chosenDate.set(Calendar.DAY_OF_MONTH, 1); this.chosenDate.set(Calendar.YEAR, y.intValue()); int maxDayOfMonth = this.chosenDate.getActualMaximum( Calendar.DAY_OF_MONTH); this.chosenDate.set(Calendar.DAY_OF_MONTH, Math.min(dayOfMonth, maxDayOfMonth)); refreshYearSelector(); refreshButtons(); } } else if (e.getActionCommand().equals("todayButtonClicked")) { setDate(new Date()); } else if (e.getActionCommand().equals("dateButtonClicked")) { final JButton b = (JButton) e.getSource(); final int i = Integer.parseInt(b.getName()); final Calendar cal = getFirstVisibleDate(); cal.add(Calendar.DATE, i); setDate(cal.getTime()); } } /** * Returns a panel of buttons, each button representing a day in the month. * This is a sub-component of the DatePanel. * * @return the panel. */ private JPanel getCalendarPanel() { final JPanel p = new JPanel(new GridLayout(7, 7)); final DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(); final String[] weekDays = dateFormatSymbols.getShortWeekdays(); for (int i = 0; i < this.WEEK_DAYS.length; i++) { p.add(new JLabel(weekDays[this.WEEK_DAYS[i]], SwingConstants.CENTER)); } this.buttons = new JButton[42]; for (int i = 0; i < 42; i++) { final JButton b = new JButton(""); b.setMargin(new Insets(1, 1, 1, 1)); b.setName(Integer.toString(i)); b.setFont(this.dateFont); b.setFocusPainted(false); b.setActionCommand("dateButtonClicked"); b.addActionListener(this); this.buttons[i] = b; p.add(b); } return p; } /** * Returns the button color according to the specified date. * * @param theDate the date. * @return the color. */ private Color getButtonColor(final Calendar theDate) { if (equalDates(theDate, this.chosenDate)) { return this.chosenDateButtonColor; } else if (theDate.get(Calendar.MONTH) == this.chosenDate.get( Calendar.MONTH)) { return this.chosenMonthButtonColor; } else { return this.chosenOtherButtonColor; } } /** * Returns true if the two dates are equal (time of day is ignored). * * @param c1 the first date. * @param c2 the second date. * @return boolean. */ private boolean equalDates(final Calendar c1, final Calendar c2) { if ((c1.get(Calendar.DATE) == c2.get(Calendar.DATE)) && (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)) && (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR))) { return true; } else { return false; } } /** * Returns the first date that is visible in the grid. This should always * be in the month preceding the month of the selected date. * * @return the date. */ private Calendar getFirstVisibleDate() { final Calendar c = Calendar.getInstance(); c.set(this.chosenDate.get(Calendar.YEAR), this.chosenDate.get( Calendar.MONTH), 1); c.add(Calendar.DATE, -1); while (c.get(Calendar.DAY_OF_WEEK) != getFirstDayOfWeek()) { c.add(Calendar.DATE, -1); } return c; } /** * Returns the first day of the week (controls the labels in the date * panel). * * @return the first day of the week. */ private int getFirstDayOfWeek() { return this.firstDayOfWeek; } /** * Update the button labels and colors to reflect date selection. */ private void refreshButtons() { final Calendar c = getFirstVisibleDate(); for (int i = 0; i < 42; i++) { final JButton b = this.buttons[i]; b.setText(Integer.toString(c.get(Calendar.DATE))); b.setBackground(getButtonColor(c)); c.add(Calendar.DATE, 1); } } /** * Changes the contents of the year selection JComboBox to reflect the * chosen date and the year range. */ private void refreshYearSelector() { if (!this.refreshing) { this.refreshing = true; this.yearSelector.removeAllItems(); final Integer[] years = getYears(this.chosenDate.get( Calendar.YEAR)); for (int i = 0; i < years.length; i++) { this.yearSelector.addItem(years[i]); } this.yearSelector.setSelectedItem(new Integer(this.chosenDate.get( Calendar.YEAR))); this.refreshing = false; } } /** * Returns a vector of years preceding and following the specified year. * The number of years preceding and following is determined by the * yearSelectionRange attribute. * * @param chosenYear the selected year. * @return a vector of years. */ private Integer[] getYears(final int chosenYear) { final int size = this.yearSelectionRange * 2 + 1; final int start = chosenYear - this.yearSelectionRange; final Integer[] years = new Integer[size]; for (int i = 0; i < size; i++) { years[i] = new Integer(i + start); } return years; } /** * Constructs a panel containing two JComboBoxes (for the month and year) * and a button (to reset the date to TODAY). * * @return the panel. */ private JPanel constructSelectionPanel() { final JPanel p = new JPanel(); final int minMonth = this.chosenDate.getMinimum(Calendar.MONTH); final int maxMonth = this.chosenDate.getMaximum(Calendar.MONTH); final String[] months = new String[maxMonth - minMonth + 1]; for(int i=0;i<months.length;i++){ months[i] = ""+i; } this.monthSelector = new JComboBox(months); this.monthSelector.addActionListener(this); this.monthSelector.setActionCommand("monthSelectionChanged"); p.add(this.monthSelector); this.yearSelector = new JComboBox(getYears(0)); this.yearSelector.addActionListener(this); this.yearSelector.setActionCommand("yearSelectionChanged"); p.add(this.yearSelector); return p; } /** * Returns a panel that appears at the bottom of the calendar panel - * contains a button for selecting today"s date. * * @return the panel. */ private JPanel constructControlPanel() { final JPanel p = new JPanel(); p.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 5)); this.todayButton = new JButton("Today"); this.todayButton.addActionListener(this); this.todayButton.setActionCommand("todayButtonClicked"); p.add(this.todayButton); return p; } /** * Returns the color for the currently selected date. * * @return a color. */ public Color getChosenDateButtonColor() { return this.chosenDateButtonColor; } /** * Redefines the color for the currently selected date. * * @param chosenDateButtonColor the new color */ public void setChosenDateButtonColor(final Color chosenDateButtonColor) { if (chosenDateButtonColor == null) { throw new NullPointerException("UIColor must not be null."); } final Color oldValue = this.chosenDateButtonColor; this.chosenDateButtonColor = chosenDateButtonColor; refreshButtons(); firePropertyChange("chosenDateButtonColor", oldValue, chosenDateButtonColor); } /** * Returns the color for the buttons representing the current month. * * @return the color for the current month. */ public Color getChosenMonthButtonColor() { return this.chosenMonthButtonColor; } /** * Defines the color for the buttons representing the current month. * * @param chosenMonthButtonColor the color for the current month. */ public void setChosenMonthButtonColor(final Color chosenMonthButtonColor) { if (chosenMonthButtonColor == null) { throw new NullPointerException("UIColor must not be null."); } final Color oldValue = this.chosenMonthButtonColor; this.chosenMonthButtonColor = chosenMonthButtonColor; refreshButtons(); firePropertyChange("chosenMonthButtonColor", oldValue, chosenMonthButtonColor); } /** * Returns the color for the buttons representing the other months. * * @return a color. */ public Color getChosenOtherButtonColor() { return this.chosenOtherButtonColor; } /** * Redefines the color for the buttons representing the other months. * * @param chosenOtherButtonColor a color. */ public void setChosenOtherButtonColor(final Color chosenOtherButtonColor) { if (chosenOtherButtonColor == null) { throw new NullPointerException("UIColor must not be null."); } final Color oldValue = this.chosenOtherButtonColor; this.chosenOtherButtonColor = chosenOtherButtonColor; refreshButtons(); firePropertyChange("chosenOtherButtonColor", oldValue, chosenOtherButtonColor); } /** * Returns the range of years available for selection (defaults to 20). * * @return The range. */ public int getYearSelectionRange() { return this.yearSelectionRange; } /** * Sets the range of years available for selection. * * @param yearSelectionRange the range. */ public void setYearSelectionRange(final int yearSelectionRange) { final int oldYearSelectionRange = this.yearSelectionRange; this.yearSelectionRange = yearSelectionRange; refreshYearSelector(); firePropertyChange("yearSelectionRange", oldYearSelectionRange, yearSelectionRange); }
}</source>
Customizing JPanel Look and Feel
Property StringObject TypePanel.backgroundColorPanel.borderBorderPanel.fontFontPanel.foregroundColorPanelUIString
Gradient Panel
<source lang="java">
/*
* soapUI, copyright (C) 2004-2009 eviware.ru * * soapUI is free software; you can redistribute it and/or modify it under the * terms of version 2.1 of the GNU Lesser General Public License as published by * the Free Software Foundation. * * soapUI 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 at gnu.org. */
import java.awt.BorderLayout; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.LayoutManager; import java.awt.Paint; import javax.swing.JPanel; /**
* Created by IntelliJ IDEA. */
public class GradientPanel extends JPanel {
// ------------------------------ FIELDS ------------------------------ public final static int HORIZONTAL = 0; public final static int VERTICAL = 1; public final static int DIAGONAL_LEFT = 2; public final static int DIAGONAL_RIGHT = 3; private int direction = HORIZONTAL; private boolean cyclic; private int maxLength; // --------------------------- CONSTRUCTORS --------------------------- public GradientPanel() { this( HORIZONTAL ); } public GradientPanel( int direction ) { super( new BorderLayout() ); setOpaque( false ); this.direction = direction; } public GradientPanel( LayoutManager layoutManager ) { super( layoutManager ); setOpaque( false ); this.direction = HORIZONTAL; } // --------------------- GETTER / SETTER METHODS --------------------- public int getDirection() { return direction; } public void setDirection( int direction ) { this.direction = direction; } public boolean isCyclic() { return cyclic; } public void setCyclic( boolean cyclic ) { this.cyclic = cyclic; } public void setMaxLength( int maxLength ) { this.maxLength = maxLength; } // -------------------------- OTHER METHODS -------------------------- public void paintComponent( Graphics g ) { if( isOpaque() ) { super.paintComponent( g ); return; } int width = getWidth(); int height = getHeight(); // Create the gradient paint GradientPaint paint = null; Color sc = getForeground(); Color ec = getBackground(); switch( direction ) { case HORIZONTAL : { paint = new GradientPaint( 0, height / 2, sc, width, height / 2, ec, cyclic ); break; } case VERTICAL : { paint = new GradientPaint( width / 2, 0, sc, width / 2, maxLength > 0 ? maxLength : height, ec, cyclic ); break; } case DIAGONAL_LEFT : { paint = new GradientPaint( 0, 0, sc, width, height, ec, cyclic ); break; } case DIAGONAL_RIGHT : { paint = new GradientPaint( width, 0, sc, 0, height, ec, cyclic ); break; } } if( paint == null ) { throw new RuntimeException( "Invalid direction specified in GradientPanel" ); } // we need to cast to Graphics2D for this operation Graphics2D g2d = ( Graphics2D )g; // save the old paint Paint oldPaint = g2d.getPaint(); // set the paint to use for this operation g2d.setPaint( paint ); // fill the background using the paint g2d.fillRect( 0, 0, width, height ); // restore the original paint g2d.setPaint( oldPaint ); super.paintComponent( g ); }
}</source>
Subclass JPanel
<source lang="java">
import java.awt.Color; import java.awt.Graphics; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class OvalPanel extends JPanel {
Color color; public OvalPanel() { this(Color.black); } public OvalPanel(Color color) { this.color = color; } public void paintComponent(Graphics g) { int width = getWidth(); int height = getHeight(); g.setColor(color); g.drawOval(0, 0, width, height); } public static void main(String args[]) { JFrame frame = new JFrame("Oval Sample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new GridLayout(2, 2)); Color colors[] = { Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW }; for (int i = 0; i < 4; i++) { OvalPanel panel = new OvalPanel(colors[i]); panel.add(new JButton("asdf")); frame.add(panel); } frame.setSize(300, 200); frame.setVisible(true); }
}</source>
Using JPanel as a canvas
<source lang="java">
import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class OvalPanelCanvas extends JPanel {
public OvalPanelCanvas() { } public void paintComponent(Graphics g) { int width = getWidth(); int height = getHeight(); g.setColor(Color.black); g.drawOval(0, 0, width, height); } public static void main(String args[]) { JFrame frame = new JFrame("Oval Sample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new OvalPanelCanvas()); frame.setSize(300, 200); frame.setVisible(true); }
}</source>
Using JPanel as a container
JPanel components are opaque, while JComponents are not opaque
<source lang="java">
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class PanelWithComponents {
public static void main(String[] a) { JPanel panel = new JPanel(); JButton okButton = new JButton("OK"); panel.add(okButton); JButton cancelButton = new JButton("Cancel"); panel.add(cancelButton); JFrame frame = new JFrame("Oval Sample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.setSize(300, 200); frame.setVisible(true); }
}</source>