??xml version="1.0" encoding="utf-8" standalone="yes"?>免费一级在线观看,亚洲xxx大片,亚洲欧洲在线免费http://www.aygfsteel.com/jiangshachina/category/33264.html同是Java爱好者,盔R何必曾相识Q?lt;br>    a cup of Java, cheers!zh-cnTue, 16 Jul 2013 07:40:36 GMTTue, 16 Jul 2013 07:40:36 GMT60Custom Layout Manager: PyramidLayout(?http://www.aygfsteel.com/jiangshachina/archive/2012/07/15/383156.htmlSha JiangSha JiangSun, 15 Jul 2012 14:14:00 GMThttp://www.aygfsteel.com/jiangshachina/archive/2012/07/15/383156.htmlhttp://www.aygfsteel.com/jiangshachina/comments/383156.htmlhttp://www.aygfsteel.com/jiangshachina/archive/2012/07/15/383156.html#Feedback3http://www.aygfsteel.com/jiangshachina/comments/commentRss/383156.htmlhttp://www.aygfsteel.com/jiangshachina/services/trackbacks/383156.html
Custom Layout Manager: PyramidLayout
    已有太多关于自定义部局理器的文章了。本文仅是一学习笔讎ͼ描述了如何实CU像堆金字塔似的部局理器,很简单,也有点儿意思,可能你也会感兴趣的?2012.07.17最后更?   

    I have developed Swing application for several years, although I'm not professional GUI developer, I'm shamed of never creating any custom layout manager. Maybe the existing Swing layout managers are too powerful to create new ones. At least, GridBagLayout is powerful enough for my real works. And we have much more flexible GroupLayout and SpringLayout, of course, both of them are too complex, in fact I never use them directly. However I indirectly take advantage of GroupLayout due to using NetBeans' GUI designer Matisse.

1. Layout Manager basics
    Let's start with some layout manager foundation. Before this time I learn to customize layout, I always think layout manager is very mysterious. Layout is like a magic player that put a variety of components to right positions in containers. I haven't browsed any code of any layout, event the simplest one. That's why I think layout is mystery. But it's simple for me now.
    Generally, all of layout implements one or both of LayoutManager and LayoutManager2 interfaces. LayoutManager2 is LayoutManager's sub-interface, then if someone implements LayoutManager2 that means it really implements LayoutManager. Mostly all modern layouts implements LayoutManager2.
    Interface LayoutManager defines the basic methods must be implemented by every layout, all of them are intuitional: add new component--addLayoutComponent(); remove component--removeLayoutComponent(); calculate preferred size--preferredLayoutSize(); calculate minimum size--minimumLayoutSize(); how to layout the components--layoutContainer(). Absolutely, the layoutContainer() method is essential, you must instruct the parent container how to allocate space(bounds) for every component.
    The extension interface LayoutManager2 introduces more methods that if you have to: support constraints--addLayoutComponent(Component, Object); specify maximum size--maximumLayoutSize(); specify alignment--getLayoutAlignmentX() and getLayoutAlignmentY(); destroy specific caches or reset some variables when invaliding container--invalidateLayout().

2. PyramidLayout
    Now let's feature a simple and funny layout manager--PyramidLayout. The layout allows container to add components like building a Pyramid, as shown as the image below,

    As the above, PyramidLayout puts the first component on the bottom, then puts the second on top of the first, but its bounds is smaller, ... It looks like a Pyramid, doesn't it? Here is the full codes,
public class PyramidLayout implements LayoutManager2 {

    
private List<Component> comps = new LinkedList<Component>();

    
public void addLayoutComponent(final Component comp,
            
final Object constraints) {
        
synchronized (comp.getTreeLock()) {
            comps.add(comp);
        }
    }

    
public void addLayoutComponent(final String name, final Component comp) {
        addLayoutComponent(comp, null);
    }

    
public void removeLayoutComponent(final Component comp) {
        
synchronized (comp.getTreeLock()) {
            comps.remove(comp);
        }
    }

    
public float getLayoutAlignmentX(final Container target) {
        
return 0.5F;
    }

    
public float getLayoutAlignmentY(final Container target) {
        
return 0.5F;
    }

    
public void invalidateLayout(final Container target) {
        System.out.println();
    }

    
public Dimension preferredLayoutSize(final Container parent) {
        
synchronized (parent.getTreeLock()) {
            Insets insets = parent.getInsets();
            
int width = insets.left + insets.right;
            
int height = insets.top + insets.bottom;
            
if (comps.size() == 0) {
                
return new Dimension(width, height);
            }

            Dimension size = comps.get(0).getPreferredSize();
            width += size.width;
            height += size.height;

            
return new Dimension(width, height);
        }
    }

    
public Dimension minimumLayoutSize(final Container parent) {
        
synchronized (parent.getTreeLock()) {
            Insets insets = parent.getInsets();
            
int width = insets.left + insets.right;
            
int height = insets.top + insets.bottom;
            
if (comps.size() == 0) {
                
return new Dimension(width, height);
            }

            Dimension size = comps.get(0).getMinimumSize();
            width += size.width;
            height += size.height;

            
return new Dimension(width, height);
        }
    }

    
public Dimension maximumLayoutSize(final Container target) {
        
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
    }

    
public void layoutContainer(final Container parent) {
        
synchronized (parent.getTreeLock()) {
            Dimension parentSize = parent.getSize();
            
int compsCount = comps.size();
            Dimension step = new Dimension(parentSize.width / (2 * compsCount),
                    parentSize.height / (2 * compsCount));

            
for (int i = 0; i < compsCount; i++) {
                Component comp = comps.get(i);
                comp.setBounds(calcBounds(parentSize, step, i));
                parent.setComponentZOrder(comp, compsCount - i - 1);
            }
        }
    }

   
private Rectangle calcBounds(Dimension parentSize, Dimension step, int index) {
        
int x = step.width * index;
        
int y = step.height * index;
        
int width = parentSize.width - step.width * 2 * index;
        
int height = parentSize.height - step.height * 2 * index;
        
return new Rectangle(x, y, width, height);
    }
}
    Collection instance "comps" manages all of components, in this case, I take a LinkedList object to add and remove UI components. The layout doesn't concern any constraint, so the two addLayoutComponent() methods have the same actions. Please see the codes for details.
    As aforementioned, layoutContainer() method really takes charge of layouting the components. The key work is allocating space for each component, namely, specifying the bounds. Calculating bounds values just applies the simplest arithmetic operations.
    According to the intention, the bottom component fills the whole parent container, so it determines the preferred and the minimum sizes. For details, please take a look at methods preferredLayoutSize() and minimumLayoutSize(). Since the layout manager doesn't take care of the maximum size, the maximumLayoutSize() method simply returns a constant value.


Sha Jiang 2012-07-15 22:14 发表评论
]]>
构徏不规则窗??http://www.aygfsteel.com/jiangshachina/archive/2011/05/31/351369.htmlSha JiangSha JiangTue, 31 May 2011 12:46:00 GMThttp://www.aygfsteel.com/jiangshachina/archive/2011/05/31/351369.htmlhttp://www.aygfsteel.com/jiangshachina/comments/351369.htmlhttp://www.aygfsteel.com/jiangshachina/archive/2011/05/31/351369.html#Feedback0http://www.aygfsteel.com/jiangshachina/comments/commentRss/351369.htmlhttp://www.aygfsteel.com/jiangshachina/services/trackbacks/351369.html
构徏不规则窗?/span>
在开发一个新微博Swing客户端的q程中希望能展现不规则的H体界面Q原?a >JDK 6 update 10提供了创建指定Ş状窗体的Ҏ,单易用,C此处?2010.05.31最后更?

Java?a >JDK 6 update 10开始将内徏支持构徏指定形状的窗体,ccom.sun.awt.AWTUtilities中的ҎsetWindowShape会根据不同的Shape实现L造相应Ş状的H体。AWTUtilitiescL攑֜SUN的包中,在用该Ҏ时应该通过反射去进行调用,如下代码所C,
Class<?> clazz = Class.forName("com.sun.awt.AWTUtilities");
Method method 
= clazz.getMethod("setWindowShape", Window.class, Shape.class);

1. 创徏正常H体
先创Z个简单的界面Q它使用BorderLayoutQ在其中安放5个JButtonQ如下代码所C,
public class ShapedFrame extends JFrame {

    
private static final long serialVersionUID = -2291343874280454383L;

    
private JButton centerButton = new JButton("Center");

    
public ShapedFrame() {
        
super("Shaped Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initUI();
    }

    
private void initUI() {
        Container container 
= getContentPane();
        container.setLayout(
new BorderLayout());

        container.add(
new JButton("TOP"), BorderLayout.PAGE_START);
        container.add(
new JButton("RIGHT"), BorderLayout.LINE_END);
        container.add(
new JButton("BOTTOM"), BorderLayout.PAGE_END);
        container.add(
new JButton("LEFT"), BorderLayout.LINE_START);
        container.add(centerButton, BorderLayout.CENTER);
    }

    
public static void main(String[] args) {
        SwingUtilities.invokeLater(
new Runnable() {

            @Override
            
public void run() {
                ShapedFrame frame 
= new ShapedFrame();
                frame.setSize(
new Dimension(400300));
                frame.setUndecorated(
true);
                setAtCenter(frame);
                frame.setVisible(
true);
            }
        });
    }

    
// Window|于屏幕正中
    private static void setAtCenter(Window window) {
        Dimension screenSize 
= Toolkit.getDefaultToolkit().getScreenSize();
        window.setLocation((screenSize.width 
- window.getWidth()) / 2,
                (screenSize.height 
- window.getHeight()) / 2);
    }
}

执行上述E序的效果如下图所C,


2. 创徏不规则窗?
Z上述E序创徏不规则窗体,使整个窗体正好缺失掉RIGHT JButton所在的区域Q如下代码所C,
public class ShapedFrame extends JFrame {

    
private static final long serialVersionUID = -2291343874280454383L;

    
private static Method method = null;

    
static {
        
try {
            Class
<?> clazz = Class.forName("com.sun.awt.AWTUtilities");
            method 
= clazz.getMethod("setWindowShape", Window.class, Shape.class);
        } 
catch (Exception e) {
            e.printStackTrace();
        }
    }

    
private JButton centerButton = new JButton("Center");

    
public ShapedFrame() {
        
super("Shaped Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initUI();
        addComponentListener(componentListener);
    }

    
private void initUI() {
        Container container 
= getContentPane();
        container.setLayout(
new BorderLayout());

        container.add(
new JButton("TOP"), BorderLayout.PAGE_START);
        container.add(
new JButton("RIGHT"), BorderLayout.LINE_END);
        container.add(
new JButton("BOTTOM"), BorderLayout.PAGE_END);
        container.add(
new JButton("LEFT"), BorderLayout.LINE_START);
        container.add(centerButton, BorderLayout.CENTER);
    }

    
private ComponentListener componentListener = new ComponentAdapter() {

        @Override
        
public void componentResized(ComponentEvent evt) { // 当UIlg(JFrame)的尺寸发生改变时Q调用该Ҏ
            Rectangle frameRect = getBounds();
            Rectangle spaceRect 
= centerButton.getBounds();

            Point o1 
= new Point(00);
            Point o2 
= new Point(frameRect.width, 0);
            Point o3 
= new Point(frameRect.width, frameRect.height);
            Point o4 
= new Point(0, frameRect.height);

            Point i1 
= new Point(spaceRect.x + spaceRect.width, spaceRect.y);
            Point i2 
= new Point(frameRect.width, spaceRect.y);
            Point i3 
= new Point(frameRect.width, spaceRect.y
                    
+ spaceRect.height);
            Point i4 
= new Point(spaceRect.x + spaceRect.width, spaceRect.y + spaceRect.height);

            
int[] xpoints = new int[] { o1.x, o2.x, i2.x, i1.x, i4.x, i3.x, o3.x, o4.x };
            
int[] ypoints = new int[] { o1.y, o2.y, i2.y, i1.y, i4.y, i3.y, o3.y, o4.y };
            
int npoints = 8
            
// 构徏一个六边ŞQ将RIGHT JButton所处的位置I缺出来
            Shape shape = new Polygon(xpoints, ypoints, npoints);

            setWindowShape(ShapedFrame.
this, shape);
        }
    };

    
// 讄Window的Ş?/span>
    private static void setWindowShape(Window window, Shape shape) {
        
try {
            method.invoke(
null, window, shape);
        } 
catch (Exception e) {
            e.printStackTrace();
        }
    }

    
public static void main(String[] args) {
        SwingUtilities.invokeLater(
new Runnable() {

            @Override
            
public void run() {
                ShapedFrame frame 
= new ShapedFrame();
                frame.setSize(
new Dimension(400300));
                frame.setUndecorated(
true);
                setAtCenter(frame);
                frame.setVisible(
true);
            }
        });
    }

    
// Window|于屏幕正中
    private static void setAtCenter(Window window) {
        Dimension screenSize 
= Toolkit.getDefaultToolkit().getScreenSize();
        window.setLocation((screenSize.width 
- window.getWidth()) / 2,
                (screenSize.height 
- window.getHeight()) / 2);
    }
}

执行上述E序后,会有如下图所C的效果Q?br />



Sha Jiang 2011-05-31 20:46 发表评论
]]>
你所不知道的五g事情--改进Swing(?http://www.aygfsteel.com/jiangshachina/archive/2010/10/25/336125.htmlSha JiangSha JiangMon, 25 Oct 2010 14:23:00 GMThttp://www.aygfsteel.com/jiangshachina/archive/2010/10/25/336125.htmlhttp://www.aygfsteel.com/jiangshachina/comments/336125.htmlhttp://www.aygfsteel.com/jiangshachina/archive/2010/10/25/336125.html#Feedback0http://www.aygfsteel.com/jiangshachina/comments/commentRss/336125.htmlhttp://www.aygfsteel.com/jiangshachina/services/trackbacks/336125.html阅读全文

Sha Jiang 2010-10-25 22:23 发表评论
]]>
数据加蝲模糊q度指示面板的实C应用(?http://www.aygfsteel.com/jiangshachina/archive/2009/11/29/304120.htmlSha JiangSha JiangSun, 29 Nov 2009 12:33:00 GMThttp://www.aygfsteel.com/jiangshachina/archive/2009/11/29/304120.htmlhttp://www.aygfsteel.com/jiangshachina/comments/304120.htmlhttp://www.aygfsteel.com/jiangshachina/archive/2009/11/29/304120.html#Feedback5http://www.aygfsteel.com/jiangshachina/comments/commentRss/304120.htmlhttp://www.aygfsteel.com/jiangshachina/services/trackbacks/304120.html数据加蝲模糊q度指示面板的实C应用
当在加蝲数据(或其它耗时工作)Ӟ需要显CZ个进度指C面板,本文介绍了一U简易的实现方式?2009.11.30最后更?

对于许多Swing应用Q在与用L交互q程中可能需要与数据库进行通信(如,加蝲数据)。而这个过E往往比较耗时Qؓ了不造成"假死"现象Q一般都会显CZ个模p进度指C器(不一定?a >JProgressBarQ简单地用一个图片代替即?Q当数据加蝲完毕后,该进度指C器自动消失?br />     一般地Q该模糊q度指示器不会展C在一个弹出的对话框中(因ؓq样不美?Q而是直接昄在需要展C加蝲数据的面板中Qƈ且对该面板进行模p处理。实现这一功能的关键就在于Q在屏幕的同一区域内展CZ层面板:一层是展示数据的面板;另一层是展示q度指示器的面板。当加蝲数据Ӟ昄q度指示器面板,q模p数据面板;当数据加载完毕后Q隐藏进度指C器面板Qƈ使数据面板清晰显C。下面将使用org.jdesktop.swingx.StackLayout方式来实Cq功能?br />
1. LoadingPanel--加蝲指示器面?/span>
    首先创徏一个加载指C器面板。如前所qͼ我们不必使用真正的进度条作ؓq度指示器,仅需要用一张动态图片来代替卛_。LoadingPanel的完整代码如下所C,
public class LoadingPanel extends JPanel {

    
private static final long serialVersionUID = 1962748329465603630L;

    
private String mesg = null;

    
public LoadingPanel(String mesg) {
        
this.mesg = mesg;
        initUI();
        interceptInput();
        setOpaque(
false);
        setVisible(
false);
    }

    
private void initUI() {
        JLabel label 
= new JLabel(mesg);
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setIcon(
new ImageIcon(getClass().getResource("/path/to/spinner.gif")));

        setLayout(
new BorderLayout());
        add(label, BorderLayout.CENTER);
    }

    
private void interceptInput() {
        addMouseListener(
new MouseAdapter() {});
        addMouseMotionListener(
new MouseMotionAdapter() {});
        addKeyListener(
new KeyAdapter() {});

        addComponentListener(
new ComponentAdapter() {
            @Override
            
public void componentShown(ComponentEvent e) {
                requestFocusInWindow();
            }
        });
        setFocusTraversalKeysEnabled(
false);
    }
}
上述代码很容易理解,LoadingPanel中仅有一个JLabelQ它会展CZ张图?spinner.gif)及一D信息。但有两D代码需要特别说明:
[1]构造器中的两行代码

setVisible(false);
setOpaque(
false);
LoadingPanel只在加蝲数据时才昄Q其它时候是不显C的Q所以它默认不可见。另外,在显CLoadingPanel的同Ӟ我们仍然希望能看到数据面板,所以LoadingPanel应该是透明的?br /> [2]interceptInputҎ
当LoadingPanel昄之后Q我们不希望用户q能够操作数据面板,那么需要屏蔽掉用户(鼠标Q键?输入?br />
addMouseListener(new MouseAdapter() {});
addMouseMotionListener(
new MouseMotionAdapter() {});
addKeyListener(
new KeyAdapter() {});
上述三行代码׃得LoadingPanel能捕h有的鼠标与键盘事Ӟq忽略掉它们。但仅仅如此q不够,在展CLoadingPanelӞ数据面板中的某个UIlg很可能已l获得焦点了Q那么用户仍然可以通过键盘操控数据面板中的lg(因ؓpȝ会把键盘事g发送给当前获取焦点的组?。而且Q即使数据面板中没有Mlg获得焦点Q用户仍然可以通过Tab键把焦点转移到数据面板中的组件上。ؓ了阻止这一操作Q还需要加上如下几行代码,
addComponentListener(new ComponentAdapter() { // 一旦LoadingPanel可见Q即获取焦点
    @Override
    
public void componentShown(ComponentEvent e) {
        requestFocusInWindow();
    }
});
setFocusTraversalKeysEnabled(
false); // L用户转移焦点

2. CZE序

    在此处的CZE序中,数据面板(dataPanel)中仅有一个按钮,当点击该按钮时会昄loadingPanelQ且模糊掉dataPanelQƈ会启动一个新的线E,该线E会在睡眠大U?U?模拟耗时的数据加载工?之后隐藏loadingPanelQ且使dataPanel重新清晰可见?br />     值得注意的是Q该CZE序使用?a >SwingX中的两个lgQ?a >JXPanel?a >StackLayout。JXPanel提供了一个方?setAlpha)以方便地讄Panel的透明?Alpha?Q而StackLayout允许在同一块区域内d多层lgQƈ能同时展C所有层的组?而,CardLayout一ơ只能显C某一层的lg)。完整的CZE序如下所C,
public class LoadDataDemo extends JFrame {

    
private static final long serialVersionUID = 5927602404779391420L;

    
private JXPanel dataPanel = null// 使用org.jdesktop.swingx.JXPanelQ以方便讄清晰?/span>

    
private LoadingPanel loadingPanel = null;

    
public LoadDataDemo() {
        
super("LoadData Demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initUI();
    }

    
private void initUI() {
        JButton button 
= new JButton("Load Data");
        button.addActionListener(handler);
        dataPanel 
= new JXPanel(new FlowLayout(FlowLayout.CENTER));
        dataPanel.add(button);

        loadingPanel 
= new LoadingPanel("Loading");

        
// 使用org.jdesktop.swingx.StackLayoutQ将loadingPanel|于dataPanel的上?/span>
        JPanel centerPanel = new JXPanel(new StackLayout());
        centerPanel.add(dataPanel, StackLayout.TOP);
        centerPanel.add(loadingPanel, StackLayout.TOP);

        Container container 
= getContentPane();
        container.setLayout(
new BorderLayout());
        container.add(centerPanel, BorderLayout.CENTER);
    }

    
transient private ActionListener handler = new ActionListener() {

        
public void actionPerformed(ActionEvent e) {
           
// dataPanel及其子组件的清晰度设|ؓ50%Qƈ昄loadingPanel
            dataPanel.setAlpha(0.5F);
            loadingPanel.setVisible(
true);

            Thread thread 
= new Thread() {
                
public void run() {
                    
try {
                        Thread.sleep(
3000L); // 睡眠U?U钟Q以模拟加蝲数据的过E?/span>
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                   
// 数据加蝲完毕后,重新隐藏loadingPanelQƈ使dataPanel及其子组仉新清晰可?/span>
                    loadingPanel.setVisible(false);
                    dataPanel.setAlpha(1F);
                };
            };
            thread.start();
        }
    };

    
public static void main(String[] args) {
        LoadDataDemo demo 
= new LoadDataDemo();
        demo.setSize(
new Dimension(400300));
        demo.setVisible(
true);
    }
}

3. 不用SwingX

    SwingX为我们提供了一pd功能强大Q用简易的Swing扩展lgQ我强烈你去使用它。但若因故,你不准备使用它时Q我们仍然有替代的解x案,但此处仅qC二?br /> [1]对于讄Alpha|需要创Z个承自JPanel的DataPanelc,覆写paintComponentҎQ在其中使用Alpha合成Q?br />
Graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
[2]对于StackLayoutQ我们可以用GlassPane(ȝH格)或LayeredPane(分层H格)q行替换Q将LoadingPanel讄为GlassPane或LayeredPanel中的一层。由于一个JFrame只有一个GlassPaneQؓ了程序的灉|性,一般首选用LayeredPane?br />


Sha Jiang 2009-11-29 20:33 发表评论
]]>
利用SwingX与TimingFramework实现淡入淡出(?http://www.aygfsteel.com/jiangshachina/archive/2009/09/28/296709.htmlSha JiangSha JiangMon, 28 Sep 2009 01:46:00 GMThttp://www.aygfsteel.com/jiangshachina/archive/2009/09/28/296709.htmlhttp://www.aygfsteel.com/jiangshachina/comments/296709.htmlhttp://www.aygfsteel.com/jiangshachina/archive/2009/09/28/296709.html#Feedback0http://www.aygfsteel.com/jiangshachina/comments/commentRss/296709.htmlhttp://www.aygfsteel.com/jiangshachina/services/trackbacks/296709.html利用SwingX与TimingFramework实现淡入淡出
本文使用SwingX?a >TimingFramework展示了如何实现E入E出效果,E序z实用,希望对大家能有所助益?2009.09.28最后更?

在Swing中?a >AlphaComposite讄界面的半透明度,再配?a >javax.swing.Timer可以比较Ҏ地实现E入E出效果。但需要我们承具体的UIlgQƈ重写它的paintComponentҎQ同时还要ؓTimer提供一个ActionListener的实现。这些对于程序员来说Q显得有些乏呟?br />     q运地是QSwingX中的JXPanel(JPanel的子c?通过setAlphaҎ来设|半透明度,JXPanel中的所有UIlg都可随之半透明化。TimingFramework提供的Animator可以帮助我们非线性地讄JXPanel中的alpha倹{故Q我们在实现淡入淡出Ӟ可以使用JXPanel来替代JPanelQ用Animator来替代Timer?br />

    下面是一个非常简单的CZQ该CZ在一个用CardLayout的JPanel--cardPanelQ中另包含了两个JXPanel--panelA和panelBQ这两个子容器中又分别有一个JButton--buttonA和buttonB。当点击buttonAӞE入显CpanelBQ当点击buttonBӞE入显CpanelA?br />
 1 public class FadingCardDemo extends JFrame {
 2 
 3     private static final long serialVersionUID = 8005909309849021746L;
 4 
 5     private String CARD_A = "CARD_A";
 6     private String CARD_B = "CARD_B";
 7 
 8     private JPanel cardPanel = null;
 9     private JXPanel panelA = null;
10     private JXPanel panelB = null;
11     private JButton buttonA = null;
12     private JButton buttonB = null;
13 
14     public FadingCardDemo() {
15         super("FadingButton Demo");
16         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17         initUI();
18     }
19 
20     private void initUI() {
21         cardPanel = new JPanel(new CardLayout());
22 
23         buttonA = new JButton("Button A");
24         buttonA.addActionListener(actionHandler);
25         panelA = new JXPanel(new BorderLayout());
26         panelA.add(buttonA, BorderLayout.CENTER);
27         cardPanel.add(panelA, CARD_A);
28 
29         buttonB = new JButton("Button B");
30         buttonB.addActionListener(actionHandler);
31         panelB = new JXPanel(new BorderLayout());
32         panelB.add(buttonB, BorderLayout.CENTER);
33         cardPanel.add(panelB, CARD_B);
34 
35         Container container = getContentPane();
36         container.setLayout(new BorderLayout());
37         container.add(cardPanel, BorderLayout.CENTER);
38     }
39 
40     private ActionListener actionHandler = new ActionListener() {
41 
42         private Animator animator = null;
43 
44         public void actionPerformed(ActionEvent e) {
45             if (animator == null) {
46                 animator = new Animator(2000);
47                 animator.setDeceleration(0.2F);
48                 animator.setAcceleration(0.4F);
49             } else if (animator.isRunning()) {
50                 animator.stop();
51             }
52 
53             JButton button = (JButton) e.getSource();
54             if (button == buttonA) {
55                 animator.addTarget(new PropertySetter(panelB, "alpha"1.0F));
56                 panelB.setAlpha(0.1F);
57                 ((CardLayout) cardPanel.getLayout()).show(cardPanel, CARD_B);
58             } else if (button == buttonB) {
59                 animator.addTarget(new PropertySetter(panelA, "alpha"1.0F));
60                 panelA.setAlpha(0.1F);
61                 ((CardLayout) cardPanel.getLayout()).show(cardPanel, CARD_A);
62             }
63             animator.start();
64         }
65     };
66 
67     public static void main(String[] args) {
68         SwingUtilities.invokeLater(new Runnable() {
69             public void run() {
70                 FadingCardDemo demo = new FadingCardDemo();
71                 demo.setSize(new Dimension(400300));
72                 demo.setVisible(true);
73             }
74         });
75     }
76 }


Sha Jiang 2009-09-28 09:46 发表评论
]]>
一个简单的CheckBox Tree实现(?http://www.aygfsteel.com/jiangshachina/archive/2009/08/05/289996.htmlSha JiangSha JiangWed, 05 Aug 2009 13:10:00 GMThttp://www.aygfsteel.com/jiangshachina/archive/2009/08/05/289996.htmlhttp://www.aygfsteel.com/jiangshachina/comments/289996.htmlhttp://www.aygfsteel.com/jiangshachina/archive/2009/08/05/289996.html#Feedback3http://www.aygfsteel.com/jiangshachina/comments/commentRss/289996.htmlhttp://www.aygfsteel.com/jiangshachina/services/trackbacks/289996.html一个简单的CheckBox Tree实现
CheckBox Tree是一个十分常用的UIlgQ它能用户方便地按特定规则N树中的节点?/span>本文实现了一U简单的Checking规则Q当N了某节点后Q该节点的所有下U节点全部被N;当取消勾选某节点后,该节点的所有下U节点全部被取消N?2009.08.05最后更?

实现CheckBox Tree的常用方法,是使用JCheckBox作ؓJTree的TreeCellRendrerQƈ且需要实现特定的Checking规则来勾?取消NCheckBox?br />
1. 树节?/span>
DefaultMutableTreeNode是最常用的TreeNode实现Q此处我们将扩展q一实现--CheckBoxTreeNodeQ增加一个属?span style="color: #2000ff;">isChecked
Q用于标识该节点是否要被N上。该cȝ完整代码如下所C:
public class CheckBoxTreeNode extends DefaultMutableTreeNode {

       
private static final long serialVersionUID = 3195314943599939279L;

       
private boolean isChecked = false;

       
public CheckBoxTreeNode(Object userObject) {
               
super(userObject);
       }

       
public boolean isChecked() {
               
return isChecked;
       }

       
public void setChecked(boolean isChecked) {
               
this.isChecked = isChecked;
       }
}

2. 渲染?/span>
如本文开头所qͼ我们用JCheckBox作ؓ树节点展现Ş式的渲染器,同时定对节点进行勾选或取消N的规则。CheckBoxTreeCellRenderer本nx一个JCheckBoxQ那么在实现getTreeCellRendererComponentҎӞ只简单地q回它自q实例卛_Q而对于勾选或取消N的条gQ则由CheckBoxTreeNode中的isChecked属性来定Q完整的代码如下所C:
public class CheckBoxTreeCellRenderer extends JCheckBox implements TreeCellRenderer {

       
private static final long serialVersionUID = -6432020851855339311L;

       
public CheckBoxTreeCellRenderer() {
               setOpaque(
false);
       }

       
public Component getTreeCellRendererComponent(JTree tree, Object value,
                       
boolean selected, boolean expanded, boolean leaf, int row,
                       
boolean hasFocus) {
               CheckBoxTreeNode node 
= ((CheckBoxTreeNode) value); // 获取树节点对象?/span>
               setText(node.toString()); // 讄CheckBox所展示的文本?br />
               
// 当树节点被设|ؓN时Q则该节点对应的CheckBox被勾选上Q否则,取消N?/span>
               if (node.isChecked()) {
                       setSelected(
true);
                       setForeground(Color.BLUE);
               } 
else {
                       setSelected(
false);
                       setForeground(tree.getForeground());
               }
               
return this;
       }
}

3. ?/span>
此处对JTreeq行扩展Q创建CheckBoxTreeQ该cd是ؓJTreed了一个MouseListenerQ以侦听鼠标选中树节点后Q如何设|勾选标讎ͼql树?br />
public class CheckBoxTree extends JTree {

       
private static final long serialVersionUID = -217950037507321241L;

       
public CheckBoxTree(TreeModel newModel) {
               
super(newModel);
               addCheckingListener();
       }

       
private void addCheckingListener() {
               addMouseListener(
new MouseAdapter() {

                       @Override
                       
public void mousePressed(MouseEvent e) {
                               
int row = getRowForLocation(e.getX(), e.getY());
                               TreePath treePath 
= getPathForRow(row);
                               
if (treePath == null) {
                                       
return;
                               }

                               CheckBoxTreeNode node 
= ((CheckBoxTreeNode) treePath.getLastPathComponent());
                               
boolean checking = !node.isChecked(); // 如果该节点已被勾选上Q则此次取消勾选;反之Q亦反?/span>
                               checkNode(node, checking);

                               repaint(); 
// 重绘整棵树?/span>
                       }

                       
// 递归地勾选或取消N指定节点及其所有下U节点的CheckBox?/span>
                       private void checkNode(CheckBoxTreeNode node, boolean checking) {
                               node.setChecked(checking);
                               
if (!node.isLeaf()) {
                                       Enumeration
<CheckBoxTreeNode> children = node.children();
                                       
while (children.hasMoreElements()) {
                                               checkNode(children.nextElement(), checking);
                                       }
                               }
                       }
               });
       }
}
上述E序有两个关键点Q?. 讄当前节点及其子节点的N标?-checkNodeQ?. 重绘?-repaint。调用repaintҎҎq行l制ӞҎTreeCellRenderer.getTreeCellRendererComponent׃被调用,此时E序׃ҎcheckNodeҎ讑֮?span style="color: #2000ff;">isChecked来勾选或取消N对应的树节点CheckBox。简a之,是先设|树型数据中的勾选标讎ͼ然后渲染器再Ҏq些标记来渲染CheckBox?br />

Sha Jiang 2009-08-05 21:10 发表评论
]]>
判定一个点是否在三角Ş??http://www.aygfsteel.com/jiangshachina/archive/2008/07/24/217214.htmlSha JiangSha JiangThu, 24 Jul 2008 09:02:00 GMThttp://www.aygfsteel.com/jiangshachina/archive/2008/07/24/217214.htmlhttp://www.aygfsteel.com/jiangshachina/comments/217214.htmlhttp://www.aygfsteel.com/jiangshachina/archive/2008/07/24/217214.html#Feedback13http://www.aygfsteel.com/jiangshachina/comments/commentRss/217214.htmlhttp://www.aygfsteel.com/jiangshachina/services/trackbacks/217214.html判定一个点是否在三角Ş?/span>
如何判定一个点P是否存在于指定的三角形ABC内,q肯定是一个简单的问题Q本文仅用一个图形界面程序展CZ该问题,有兴的朋友可以看看?2008.07.24最后更?

在此处用一U常见且便的ҎQ?strong>如果三角形PABQPAC和PBC的面U之和与三角形ABC的面U相{,卛_判定点P在三角ŞABC?包括在三条边??br /> 可知Q该Ҏ的关键在于如何计三角Ş的面U。幸q地是,当知道三角Ş点(AQB和C)的坐?(Ax, Ay)Q?Bx, By)?Cx, Cy))之后Q即可计出光U:
= |(Ax * By + Bx * Cy + Cx * Zy - Ay * Bx - By * Cx - Cy * Ax) / 2|

关键的代码如下,
// q定的三个点的坐标,计算三角形面U?br /> // Point(java.awt.Point)代表点的坐标?/span>
private static double triangleArea(Point pos1, Point pos2, Point pos3) {
    
double result = Math.abs((pos1.x * pos2.y + pos2.x * pos3.y + pos3.x * pos1.y
            
- pos2.x * pos1.y - pos3.x * pos2.y - pos1.x * pos3.y) / 2.0D);
    
return result;
}

// 判断点pos是否在指定的三角形内?/span>
private static boolean inTriangle(Point pos, Point posA, Point posB,
        Point posC) {
    
double triangleArea = triangleArea(posA, posB, posC);
    
double area = triangleArea(pos, posA, posB);
    area 
+= triangleArea(pos, posA, posC);
    area 
+= triangleArea(pos, posB, posC);
    
double epsilon = 0.0001;  // ׃点数的计算存在着误差Q故指定一个够小的数Q用于判定两个面U是?q似)相等?/span>
    if (Math.abs(triangleArea - area) < epsilon) {
        
return true;
    }
    
return false;
}

执行该应用程序,用鼠标在其中点击三次Q即可绘制一个三角ŞQ如下组图所C:

然后仅需Ud鼠标Q就会出C个空心圆圈。如果圆圈的中心在三角内(包含在三条边?Q则圆圈昄为红Ԍ否则Q显CZؓ蓝色。如下组图所C:


完整代码如下Q?br />
public class CanvasPanel extends JPanel {

    
private static final long serialVersionUID = -6665936180725885346L;

    
private Point firstPoint = null;

    
private Point secondPoint = null;

    
private Point thirdPoint = null;

    
public CanvasPanel() {
        setBackground(Color.WHITE);
        addMouseListener(mouseAdapter);
        addMouseMotionListener(mouseAdapter);
    }

    
public void paintComponent(Graphics g) {
        
super.paintComponent(g);
        drawTriangel(g);
    }

    
private void drawTriangel(Graphics g) {
        
if (firstPoint != null && secondPoint != null) {
            g.drawLine(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);
            
if (thirdPoint != null) {
                g.drawLine(firstPoint.x, firstPoint.y, thirdPoint.x, thirdPoint.y);
                g.drawLine(secondPoint.x, secondPoint.y, thirdPoint.x, thirdPoint.y);
            }
        }
    }

    
private static boolean inTriangle(Point pos, Point posA, Point posB,
            Point posC) {
        
double triangeArea = triangleArea(posA, posB, posC);
        
double area = triangleArea(pos, posA, posB);
        area 
+= triangleArea(pos, posA, posC);
        area 
+= triangleArea(pos, posB, posC);
        
double epsilon = 0.0001;
        
if (Math.abs(triangeArea - area) < epsilon) {
            
return true;
        }
        
return false;
    }

    
private static double triangleArea(Point pos1, Point pos2, Point pos3) {
        
double result = Math.abs((pos1.x * pos2.y + pos2.x * pos3.y + pos3.x * pos1.y
                           
- pos2.x * pos1.y - pos3.x * pos2.y - pos1.x * pos3.y) / 2.0D);
        
return result;
    }

    
private MouseInputAdapter mouseAdapter = new MouseInputAdapter() {

        
public void mouseReleased(MouseEvent e) {
            Point pos 
= e.getPoint();
            
if (firstPoint == null) {
                firstPoint 
= pos;
            } 
else if (secondPoint == null) {
                secondPoint 
= pos;
                Graphics g 
= CanvasPanel.this.getGraphics();
                CanvasPanel.
this.paintComponent(g);
                g.drawLine(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);
            } 
else if (thirdPoint == null) {
                thirdPoint 
= pos;
                Graphics g 
= CanvasPanel.this.getGraphics();
                CanvasPanel.
this.paintComponent(g);
                g.drawLine(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y);
                g.drawLine(firstPoint.x, firstPoint.y, thirdPoint.x, thirdPoint.y);
                g.drawLine(secondPoint.x, secondPoint.y, thirdPoint.x, thirdPoint.y);
            }
        }

        
public void mouseMoved(MouseEvent e) {
            Point pos 
= e.getPoint();
            Graphics2D g2 
= (Graphics2D) CanvasPanel.this.getGraphics();
            CanvasPanel.
this.paintComponent(g2);
            
if (firstPoint != null && secondPoint == null) {
                g2.drawLine(firstPoint.x, firstPoint.y, pos.x, pos.y);
            } 
else if (firstPoint != null && secondPoint != null && thirdPoint == null) {
                g2.drawLine(firstPoint.x, firstPoint.y, pos.x, pos.y);
                g2.drawLine(secondPoint.x, secondPoint.y, pos.x, pos.y);
            } 
else if (firstPoint != null && secondPoint != null && thirdPoint != null) {
                
if (inTriangle(pos, firstPoint, secondPoint, thirdPoint)) {
                    g2.setColor(Color.RED);
                } 
else {
                    g2.setColor(Color.BLUE);
                }
                
int radius = 4;
                g2.drawOval(pos.x 
- radius, pos.y - radius, radius * 2, radius * 2);
            }
        }
    };
}

public class Triangle extends JFrame {

    
private static final long serialVersionUID = 1L;

    
private CanvasPanel mainPanel = null;

    
public Triangle() {
        setTitle(
"Triangle");
        setSize(
new Dimension(300200));
        setResizable(
false);

        init();

        Container container 
= getContentPane();
        container.add(mainPanel);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(
true);
    }

    
private void init() {
        mainPanel 
= new CanvasPanel();
    }

    
public static void main(String[] args) {
        
new Triangle();
    }
}



Sha Jiang 2008-07-24 17:02 发表评论
]]>
վ֩ģ壺 | ¤| | | ɳ| ԭ| Դ| | ʯɽ| | ƽ| ֽ| | ɽ| | ˮ| ƽ| | | ͭ| | Ʊ| ƽ| | | ɳ| ˷| ֶ| | Դ| | | | ӽ| Ž| ѳ| | | ɽ| ɳ| |