综合

使用Decorator模式实现日期选择组件(4)

2019-09-10 17:21:22来源:励志吧0次阅读

NAVIGATION/导航

下面展示的就是导航栏的实现代码,虽然有点长,但同样非常地简单。代码由定义了4个图象文件的代码开始。(我计划以后放弃箭头采用代码实现,但是现在仍然在用图象文件。)用下面的代码,把图象作为资源获取过来。

ClassLoader loader = getClass().getClassLoader();

loader.getResource( "IMAGE_FILE_NAME" );

classloader在找类的地方找图象资源;比如,程序在文件系统中运行,它将要在classpath中查找文件路径。因为没有用到绝对路径,代码是更加容易的打包成jar文件,并且文件也不再需要建立在文件系统中。导航栏是一个四个用图象做标签的按纽,按纽的动作监听通过Date_selector的roll()来包装日历对象,并且月份的改变也激发标题栏的改变。有一点非常重要就是导航条不知道也不影响标题。标题包装器是一个监听,所以它能自动的更新标题。导航条根本就不知道标题包装器的存在。

public class Navigable_date_selector extends JPanel implements Date_selector

{  private    Date_selector selector;

// Names of image files used for the navigator bar

private static final String

NEXT_YEAR    = "images/10px.red.arrow.right.double.gif",

NEXT_MONTH   = "images/10px.red.arrow.right.gif",

PREVIOUS_YEAR  = "images/10px.red.arrow.left.double.gif",

PREVIOUS_MONTH = "images/10px.red.arrow.left.gif";

// These constants are used to identify the button and

// as the button caption in the event that the appropriate

// image file can't be located

private static final String FORWARD_MONTH  = ">"  ,

FORWARD_YEAR  = ">>"  ,

BACK_MONTH   = "<"  ,

BACK_YEAR    = "<<"

private JPanel navigation = new JPanel();

public Navigable_date_selector( Date_selector selector )

{  this.selector = selector;

setBorder( null );

setOpaque( false );

setLayout( new BorderLayout() );

add( (JPanel)selector, BorderLayout.CENTER );

navigation.setLayout(new FlowLayout());

navigation.setBorder( null );

navigation.setBackground( com.holub.ui.Colors.LIGHT_YELLOW );

navigation.add( make_navigation_button(BACK_YEAR  ) );

navigation.add( make_navigation_button(BACK_MONTH  ) );

navigation.add( make_navigation_button(FORWARD_MONTH) );

navigation.add( make_navigation_button(FORWARD_YEAR ) );

add(navigation, BorderLayout.SOUTH);

}

// ...

// I left out a few constructors and utility methods that go here

// ...

private final Navigation_handler navigation_listener

= new Navigation_handler();

/** Handle clicks from the navigation bar buttons */

private class Navigation_handler implements ActionListener

{  public void actionPerformed(ActionEvent e)

{  String direction = e.getActionCommand();

if   (direction==FORWARD_YEAR )selector.roll(Calendar.YEAR,true);

else if(direction==BACK_YEAR  )selector.roll(Calendar.YEAR,false);

else if(direction==FORWARD_MONTH)

{

selector.roll(Calendar.MONTH,true);

if( selector.get(Calendar.MONTH) == Calendar.JANUARY )

selector.roll(Calendar.YEAR,true);

}

else if (direction==BACK_MONTH )

{

selector.roll(Calendar.MONTH,false);

if( selector.get(Calendar.MONTH) == Calendar.DECEMBER )

selector.roll(Calendar.YEAR,false);

}

else

{  assert false: "Unexpected direction";

}

}

}

private JButton make_navigation_button(String caption)

{

ClassLoader loader = getClass().getClassLoader();

URL image =

(cap

小孩子老是流鼻血是什么原因
幼儿小便黄
幼儿口臭
孩子上火怎么办
分享到: