swing第一刀,Swing 边框(一)

Swing组件提供了对组件周围的边框区域进行定制的功能。为了简单,我们可以使用预定义的八个边框,或者是我们可以创建自己的边框。在本章中,我们将会了解如何最好的使用已存在边框以及如何创建我们自己的边框。

7.1 Some Basics _disibledevent=>swing_7_1swing第一刀,Swing 边框(一)

7.1.1 Exploring the Border Inteface

我们可以在javax.swing.border包中找到Border接口。这个接口构成了所有边框类的基础。这个接口直接由AbstractBorder类实现,这个类是所有预定义的Swing边框类的父类:BevelBorder,CompoundBorder,EmptyBorder,EtchedBorder,LineBorder,MatteBorder,SoftBevelBorder以及TitledBorder。另外一个有趣的类就是BorderFactory类,我们可以在javax.swing包中找到这个类。这个类使用工厂设计模式来创建边框,隐藏了实现细节,并且可以缓存各种选项来优化共同使用。
在这里显示的Border接口由三个方法构成:paintBorder(),getBordernsets()以及isBorderOpaque()。这些方法会在后面的章节中进行描述。
paintBorder()
paintBorder()方法是这个接口的关键方法。其定义如下:
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height)
边框实现的绘制是由这个方法完成的。通常,Border实现首先会询问Insets维度,然后在外层区域的四个边进行绘制,如图7-2所示。如果边框是不透明的,paintBorder()实现必须填充整个内部区域。如果一个边框是不透明的,并没有填充区域,那么这是一个bug并且需要修正。
列表7-1显示了一个简单的paintBorder()实现,这个实现使用比上部与下部略浅的颜色填充左边与右边。
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Insets insets = getBorderInsets(c); Color color = c.getForeground(); Color brighterColor = color.brighter(); // Translate coordinate space g.translate(x, y); // Top g.setColor(color); g.fillRect(0, 0, width, insets.top); // Left g.setColor(brighterColor); g.fillRect(0, insets.top, insets.left, height-insets.top-insets.bottom); // Bottom g.setColor(color); g.fillRect(0, height-insets.bottom, width, insets.bottom); // Right g.setColor(brighterColor); g.fillRect(width-insets.right, insets.top, insets.right, height-insets.top-insets.bottom); // Translate coordinate space back g.translate(-x, -y); }
Tags:  swing边框 aswing swing 边框一 swing第一刀

延伸阅读

最新评论

发表评论