importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;importjavax.swing.border.*;importjava.util.*;importjava.text.SimpleDateFormat;/*ComboBoxDemo2.javarequiresnootherfiles.*/publicclassComboBoxDemo2extendsJPanelimplementsActionListener{staticJFrameframe;JLabelresult;StringcurrentPattern;publicComboBoxDemo2(){setLayout(newBoxLayout(this,BoxLayout.PAGE_AXIS));String[]patternExamples={"ddMMMMMyyyy","dd.MM.yy","MM/dd/yy","yyyy.MM.ddG'at'hh:mm:ssz","EEE,MMMd,''yy","h:mma","H:mm:ss:SSS","K:mma,z","yyyy.MMMMM.ddGGGhh:mmaaa"};currentPattern=patternExamples[0];//SetuptheUIforselectingapattern.JLabelpatternLabel1=newJLabel("Enterthepatternstringor");JLabelpatternLabel2=newJLabel("selectonefromthelist:");JComboBoxpatternList=newJComboBox(patternExamples);patternList.setEditable(true);patternList.addActionListener(this);//CreatetheUIfordisplayingresult.JLabelresultLabel=newJLabel("CurrentDate/Time",JLabel.LEADING);//==LEFTresult=newJLabel("");result.setForeground(Color.black);result.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),BorderFactory.createEmptyBorder(5,5,5,5)));//Layouteverything.JPanelpatternPanel=newJPanel();patternPanel.setLayout(newBoxLayout(patternPanel,BoxLayout.PAGE_AXIS));patternPanel.add(patternLabel1);patternPanel.add(patternLabel2);patternList.setAlignmentX(Component.LEFT_ALIGNMENT);patternPanel.add(patternList);JPanelresultPanel=newJPanel(newGridLayout(0,1));resultPanel.add(resultLabel);resultPanel.add(result);patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);add(patternPanel);add(Box.createRigidArea(newDimension(0,10)));add(resultPanel);setBorder(BorderFactory.createEmptyBorder(10,10,10,10));reformat();}//constructorpublicvoidactionPerformed(ActionEvente){JComboBoxcb=(JComboBox)e.getSource();StringnewSelection=(String)cb.getSelectedItem();currentPattern=newSelection;reformat();}/**Formatsanddisplaystoday'sdate.*/publicvoidreformat(){Datetoday=newDate();SimpleDateFormatformatter=newSimpleDateFormat(currentPattern);try{StringdateString=formatter.format(today);result.setForeground(Color.black);result.setText(dateString);}catch(IllegalArgumentExceptioniae){result.setForeground(Color.red);result.setText("Error:"+iae.getMessage());}}/***CreatetheGUIandshowit.Forthreadsafety,*thismethodshouldbeinvokedfromthe*event-dispatchingthread.*/privatestaticvoidcreateAndShowGUI(){//Createandsetupthewindow.JFrameframe=newJFrame("ComboBoxDemo2");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Createandsetupthecontentpane.JComponentnewContentPane=newComboBoxDemo2();newContentPane.setOpaque(true);//contentpanesmustbeopaqueframe.setContentPane(newContentPane);//Displaythewindow.frame.pack();frame.setVisible(true);}publicstaticvoidmain(String[]args){//Scheduleajobfortheevent-dispatchingthread://creatingandshowingthisapplication'sGUI.javax.swing.SwingUtilities.invokeLater(newRunnable(){publicvoidrun(){createAndShowGUI();}});}}
阅读全文 >