Problem in JSeparator

Here is the Code u can see
Make a main Method here Ok
i havent make it because in my application this call call by some auther class
So dear's the mail problem is
JSeparator hh = new JSeparator(SwingConstants.VERTICAL);
panel3.add(hh);
This line is not working . WHY can u tell me PL
import javax.swing.*;
import java.awt.*;
public class bookdata
     JFrame frame;
     JPanel panel , panel2 , panel3;
     JButton but1,but2,but3,but4,but5,but6;
     Color cc;
     BoxLayout bak;
     ImageIcon icon;
     FlowLayout flo;
     public bookdata()
          icon = new ImageIcon("book/book.jpg");
          frame = new JFrame("Book Database");
          frame.setResizable(false);
          frame.setIconImage(new ImageIcon("book/logo.gif").getImage());
          Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
          int x = (d.width - 550)/2;
          int y = (d.height - 500)/2;
          frame.setBounds(x,y,400,300);
     public void main1()
          JLabel label = new JLabel(icon);
          flo = new FlowLayout();
          panel3 = new JPanel();
          but1 = new JButton("NEW BOOK");
          but2 = new JButton("EDIT");
          but3 = new JButton("DELET");
          but4 = new JButton("SHOW");
          but5 = new JButton("LONE");
          but6 = new JButton();
          panel = new JPanel();
          bak = new BoxLayout(panel,BoxLayout.Y_AXIS);
          panel.setLayout(bak);
          // 1st 220 is for R
          // 2nd 177 is for G
          // 3rd 162 is for B
          // 4th 255 is for Alpha
          cc = new Color(51,51,255);
          panel2 = new JPanel();
          panel2.setLayout(flo);
          panel2.setBackground(cc);
          panel2.add(label);
          JSeparator hh = new JSeparator(SwingConstants.VERTICAL);
          SpringLayout layout = new SpringLayout();
          panel3.setLayout(layout);
          panel3.add(but1);          // pp1
          panel3.add(but2);          // pp2
          panel3.add(but3);          // pp3
          panel3.add(but4);          // pp4
          panel3.add(but5);          // pp5
          panel3.add(hh);
          layout.putConstraint(SpringLayout.WEST, but1, 15,SpringLayout.WEST, panel3);          // pp1
     layout.putConstraint(SpringLayout.NORTH, but1, 25,SpringLayout.NORTH, panel3);
          layout.putConstraint(SpringLayout.WEST, but2, 15,SpringLayout.WEST, panel3);          // pp2
     layout.putConstraint(SpringLayout.NORTH, but2, 55,SpringLayout.NORTH, panel3);
          layout.putConstraint(SpringLayout.WEST, but3, 15,SpringLayout.WEST, panel3);          // pp3
     layout.putConstraint(SpringLayout.NORTH, but3, 85,SpringLayout.NORTH, panel3);
          layout.putConstraint(SpringLayout.WEST, but4, 15,SpringLayout.WEST, panel3);          // pp4
     layout.putConstraint(SpringLayout.NORTH, but4, 115,SpringLayout.NORTH, panel3);
          layout.putConstraint(SpringLayout.WEST, but5, 15,SpringLayout.WEST, panel3);          // pp5
     layout.putConstraint(SpringLayout.NORTH, but5, 145,SpringLayout.NORTH, panel3);
          layout.putConstraint(SpringLayout.WEST, hh, 100,SpringLayout.WEST, panel3);
     layout.putConstraint(SpringLayout.NORTH, hh, 500,SpringLayout.NORTH, panel3);
          frame.getContentPane().add(panel);
          panel.add(panel2);
          panel.add(panel3);
          frame.setSize(600,500);
          frame.setVisible(true);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
********************************************************************************************

1. Please use code tags when you are posting code (press the code button above the message window).
2.
Why should we add a main-method? Since you are the one asking for help it's in your own interest to make it as easy as possible for us to help you. If you couldn't be bothered spending an extra minute or two to write that main-method, why should anyone here bother?
3.
Don't just say "the line is not working". What does this mean? Does it not compile? Does it compile, but the result when you run it is not what you expect? Being clear about the problem is extra important when you post code that won't run, and without code tags.

Similar Messages

  • Max vertical size problems

    sun jdk 1.4.1
    Why is the JTextFields maximum vertical size "infinite" by default ?
    If it is resized taller then the preferred size, it looks stupid (
    it has more space than needed for one line, but the extra space is unused ).
    Which leads to the following problem : If I have a panel
    with BoxLayout(X_AXIS) that contains a JTextField and a VerticalGlue,
    the text field takes all the extra vertical space. The glue takes none !
    Why ?
    Shouldn't the extra space be distributed evenly accross all components ?
    Actually this is what happens with other components, but JTextField seems to have some kind of higher priority and takes all the available space. Is this a bug ?
    Similar problem with JSeparator ( a horizontal "line" ):
    Why does it have a maximum height of 32767 ?
    It is just a line, always 2 pixels ( or so ) high.
    Now it takes up part of extra space, instead of always being 2 pixel high.
    I am using the following code to fix these problems, but I think that I shouldn't have to, that those are some kind of bugs in Swing :
    Dimension dim1 = new Dimension(stupidComponent.getMaximumSize());
    dim1.height = stupidComponent.getPreferredSize().height;
    stupidComponent.setMaximumSize(dim1);
    Any comments ?
    stein

    Layout managers all have their areas of specialty. If you find yourself fighting with one of them to get what you want it might be wise to try a different one. We have lots of options available.

  • Spacing problem

    Hi,
    I am working on Java Swings and Iam new to it.
    Can anybody help me with my problem please...
    I have 5 panels and all these are palced in one main panel.
    I have :
    Panel1
    Panle2
    Panel3
    Panel4
    Panle5
    Panel6
    panel7
    All these are placed in main panel according to the ActionListener.
    when event1 is triggered,I need to place panel1,Panel2,Panel3,Panel4,Panel5 in Main panel.
    When event2 is triggered ,I need to place panel1,panel6,panel3,panel4,panel5 in main Panel.
    When event3 is triggered ,I need to palce panel1,panel2,panel7,panel4,panel5 in main panel.
    I coded all the panels and placed the components.But I when i place the panels ,I am getting spacing problems.
    and when I resize the main panel,I am losing components in the panels.
    Can anybody help with code please.
    I also need calender textfield with small icon besides it that pops up calender and when user selects date it should take in "yyyymmdd" format.
    Thanks,
    Tutika.

    Don't forget to use the [url
    http://forum.java.sun.com/help.jspa?sec=formatting]Cod
    e Formatting Tags so the posted code retainsits original formatting.
    If you add components to a visible panel then you
    need to revalidate() the panel so the layout manager
    can be invoked again.
    sorry,
    Here is my view code:
    public class CalenderAdmin1 extends JFrame {
         private static final long           serialVersionUID = 1L;
         // Top panel to which all the panels are attached
         // based upon events
         public JPanel jContentPane = null;
         private JScrollPane jScrollPaneContent = null;
         // Main panel variadle declaration
         private JPanel mainPanel = null;
        private JLabel jLblCalender = null;     
         private JComboBox jCmbBxCalender = null;     
        private JRadioButton jRBttnDay = null;     
         private JRadioButton jRBttnEvent = null;
         // counselorPanel variable declaration
         private JPanel      counselorPanel = null;
         private JLabel jLblCounselor = null;
         private JLabel jLblLocation = null;
        private JLabel jLblType = null;
         private JLabel jLblType1 = null;
         private JComboBox jCmbBxCounselor = null;
         private JComboBox jCmbBxLocation = null;     
         private JComboBox jCmbBxType = null;
        private JRadioButton jRBttnOffice = null;
         private JRadioButton jRBttnCounselor = null;
    //      officePanel variable declaration
         private JPanel      officePanel = null;
        private JLabel jLblPanelOfficeType = null;
         private JLabel jLblPanelOfficeLocation = null;
        private JComboBox jCmbBxPanelOfficeLocation = null;
         private JComboBox jCmbBxPanelOfficeType = null;
         // timepanel variable declaration
         private JPanel      timePanel = null;
         private JLabel jLblStartDate = null;
         private JLabel jLblStartTime = null;
         private JLabel jLblEndTime = null;
         private JTextField jTxtFStartDate = null;
        private JComboBox jCmbBxStartTimeHrs = null;
        private JLabel jLblStartTimeColon = null;
         private JComboBox jCmbBxStartTimeMin = null;
         private JComboBox jCmbBxEndTimeHrs = null;
         private JLabel jLblEndTimeColon = null;
         private JComboBox jCmbBxEndTimeMin = null;
         // recurrencePanel variable declaration
         private JPanel      recurrencePanel = null;
         private JLabel jLblRecurrence = null;
        private JLabel jLblSunday = null;
         private JLabel jLblMonday = null;
         private JLabel jLblTuesday = null;
         private JLabel jLblWednesday = null;
         private JLabel jLblThursday = null;
         private JLabel jLblFriday = null;
         private JLabel jLblSaturday = null;
        private JCheckBox jChkBxMonday = null;
         private JCheckBox jChkBxTuesday = null;
         private JCheckBox jChkBxWednesday = null;
         private JCheckBox jChkBxThursday = null;
         private JCheckBox jChkBxFriday = null;
         private JCheckBox jChkBxSaturday = null;
         private JCheckBox jChkBxSunday = null;
         private JLabel jLblEndDate = null;
         private JTextField jTxtFEndDate = null;
         // butonsPanel varaiable declaration     
         private JPanel      buttonsPanel = null;
        private JButton jBttnCancel = null;
         private JButton jBttnSave = null;
         // eventsPanel variable declaration
         private JPanel  eventsPanel = null;
        private JLabel jLblEvents = null;
         private JLabel jLblEventType = null;
         private JLabel jLblEventStartTime = null;
         private JLabel jLblEventEndTime = null;
         private JComboBox jCmbBxEventType = null;
         private JComboBox jCmbBxEventStartTimeHrs = null;
         private JComboBox jCmbBxEventStartTimeMin = null;
         private JComboBox jCmbBxEventEndTimeHrs = null;
         private JComboBox jCmbBxEventEndTimeMin = null;
        private JLabel jLblEventStartTimeColon = null;
         private JLabel jLblEventEndTimeColon = null;
         private JButton jBttnAdd = null;
         String[] calender,counselor,location,type,type1;
       //     Contructor
         public CalenderAdmin1() { 
               super();
                initialize();
          * This method initializes this
          * @return void
         private void initialize() {
                 this.setSize(750, 500);
                   this.setPreferredSize(new Dimension(600, 600));
                   this.setContentPane(getJScrollPaneContent());
                   this.setTitle("Calender Administrator");
                   this.setVisible(true);
         // Scroll Pane
         private  JScrollPane getJScrollPaneContent() {
              if (jScrollPaneContent == null) {
                   jScrollPaneContent = new JScrollPane();
                   jScrollPaneContent.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                   jScrollPaneContent.setViewportView(getJContentPane());
              return jScrollPaneContent;
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         public JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(null);
                   //jContentPane.setLayout(new GridLayout(5,0,0,0));
                   //jContentPane.setLayout(new BoxLayout(jContentPane,BoxLayout.Y_AXIS));
                   jContentPane.add(getmainPanel(),null);
                   //jContentPane.add(getofficePanel(),null);
                  jContentPane.add(getcounselorPanel(),null);
                  //jContentPane.add(geteventsPanel(),null);
                   jContentPane.add(gettimePanel(),null);
                   jContentPane.add(getrecurrencePanel(),null);
                   jContentPane.add(getbuttonsPanel(),null);
              return jContentPane;
         private JPanel getmainPanel(){
              if (mainPanel ==null){
                   mainPanel = new JPanel();
                   mainPanel.setLayout(null);
                   //jPanel1.setBorder(new javax.swing.border.TitledBorder("1"));
                   mainPanel.setBounds(new Rectangle(0, 0, 700, 85));
                   mainPanel.add(getjLblCalender(),null);
                   mainPanel.add(getjCmbBxCalender(),null);
                   mainPanel.add(getjRdBttnDay(),null);
                   mainPanel.add(getjRdBttnEvent(),null);
              return mainPanel;
         public JPanel getcounselorPanel(){
              if(counselorPanel==null){
                   counselorPanel = new JPanel();
              //jPanel2.setLayout(new BoxLayout(jPanel2,BoxLayout.Y_AXIS));
                   counselorPanel.setLayout(null);
                   //jPanel2.setBorder(new javax.swing.border.TitledBorder("2"));
                   counselorPanel.setBounds(0, 65, 700, 125);
                   counselorPanel.add(getjLblCounselor(),null);
                   counselorPanel.add(getjCmbBxCounselor(),null);
                   counselorPanel.add(getjLblLocation(),null);
                   counselorPanel.add(getjCmbBxLocation(),null);
                   counselorPanel.add(getjLblType(),null);
                   counselorPanel.add(getjCmbBxType(),null);
                   counselorPanel.add(getjLblType1(),null);
                   counselorPanel.add(getjRdBttnOffice(),null);
                   counselorPanel.add(getjRdBttnCounselor(),null);
              return counselorPanel;
         private JPanel gettimePanel(){
              if (timePanel == null){
                   timePanel=new JPanel();
                   //jPanel3.setBorder(new javax.swing.border.TitledBorder("3"));
                   timePanel.setLayout(null);
                   timePanel.setBounds(0, 170, 700, 100);
                   timePanel.add(getjLblStartDate(),null);
                   timePanel.add(getjTxtFStartDate(),null);
                   timePanel.add(getjLblStartTime(),null);
                   timePanel.add(getjCmbBxStartTimeHrs(),null);
                   timePanel.add(getjLblStartTimeColon(),null);
                   timePanel.add(getjCmbBxStartTimeMin(),null);
                   timePanel.add(getjLblEndTime(),null);
                   timePanel.add(getjLblEndTimeColon(),null);
                   timePanel.add(getjCmbBxEndTimeHrs(),null);
                   timePanel.add(getjCmbBxEndTimeMin(),null);
                   JLabel jLblC1 =  new JLabel ();
                   jLblC1.setBounds(new Rectangle(25, 70, 60, 20));
                   jLblC1.setText("new");
                   jPanel3.add(jLblC1);
                   JLabel jLblC2 =  new JLabel ();
                   jLblC2.setBounds(new Rectangle(25, 90, 60, 20));
                   jLblC2.setText("new");
                   jPanel3.add(jLblC2);
                   JLabel jLblC3 =  new JLabel ();
                   jLblC3.setBounds(new Rectangle(25, 110, 60, 20));
                   jLblC3.setText("new");
                   jPanel3.add(jLblC3);
                   JLabel jLblC4 =  new JLabel ();
                   jLblC4.setBounds(new Rectangle(25, 130, 60, 20));
                   jLblC4.setText("new");
                   jPanel3.add(jLblC4);
                   JLabel jLblC5 =  new JLabel ();
                   jLblC5.setBounds(new Rectangle(25, 150, 60, 20));
                   jLblC5.setText("new");
                   jPanel3.add(jLblC5);
                   JLabel jLblC6 =  new JLabel ();
                   jLblC6.setBounds(new Rectangle(25, 170, 60, 20));
                   jLblC6.setText("new");
                   jPanel3.add(jLblC6);
                   JLabel jLblC7 =  new JLabel ();
                   jLblC7.setBounds(new Rectangle(25, 190, 60, 20));
                   jLblC7.setText("new");
                   jPanel3.add(jLblC7);
                   //jPanel3.add(getjLblEndTime(),null);
                   //jPanel3.add(getjTxtFEndTime(),null);
              return timePanel;
         private JPanel getrecurrencePanel(){
              if (recurrencePanel == null){
                   recurrencePanel=new JPanel();
                   //jPanel4.setBorder(new javax.swing.border.TitledBorder("Reccurrence"));
                   recurrencePanel.setLayout(null);
                   recurrencePanel.setBounds(0, 240, 700, 120);
                   recurrencePanel.add(getjLblRecurrence(),null);
                   recurrencePanel.add(getjChkBxSunday(),null);
                   recurrencePanel.add(getjLblSunday(),null);
                   recurrencePanel.add(getjChkBxMonday(),null);
                   recurrencePanel.add(getjLblMonday(),null);
                   recurrencePanel.add(getjChkBxTuesday(),null);
                   recurrencePanel.add(getjLblTuesday(),null);
                   recurrencePanel.add(getjChkBxWednesday(),null);
                   recurrencePanel.add(getjLblWednesday(),null);
                   recurrencePanel.add(getjChkBxThursday(),null);
                   recurrencePanel.add(getjLblThursday(),null);
                   recurrencePanel.add(getjChkBxFriday(),null);
                   recurrencePanel.add(getjLblFriday(),null);
                   recurrencePanel.add(getjChkBxSaturday(),null);
                   recurrencePanel.add(getjLblSaturday(),null);
              //jPanel4.add(new JSeparator(), BorderLayout.CENTER);
                   recurrencePanel.add(getjLblEndDate(),null);
                   recurrencePanel.add(getjTxtFEndDate(),null);
              return recurrencePanel;
         private JPanel getbuttonsPanel(){
              if (buttonsPanel == null){
                   buttonsPanel=new JPanel();
                   //jPanel5.setBorder(new javax.swing.border.TitledBorder("5"));
                   buttonsPanel.setLayout(null);
                   buttonsPanel.setBounds(0, 360, 700, 90);
                   buttonsPanel.add(getjBtnCancel(),null);
                   buttonsPanel.add(getjBtnSave(),null);
              return buttonsPanel;
         public JPanel getofficePanel(){
              if (officePanel == null){
                   officePanel=new JPanel();
                   officePanel.setLayout(null);
                   //jPanel6.setBorder(new javax.swing.border.TitledBorder("6"));
                   officePanel.setBounds(0, 70, 700, 80);
                   officePanel.add(getjCmbBxPanelOfficeType(),null);
                   officePanel.add(getjLblPanelOfficeLocation(),null);
                   officePanel.add(getjCmbBxPanelOfficeLocation(),null);
                   officePanel.add(getjLblPanelOfficeType(),null);
              return officePanel;
         private JPanel geteventsPanel(){
              if (eventsPanel == null){
                   eventsPanel=new JPanel();
                   eventsPanel.setLayout(null);
                   //jPanel7.setBorder(new javax.swing.border.TitledBorder("7"));
                   eventsPanel.setBounds(0, 120, 700, 150);
                   eventsPanel.add(getjLblEvent(),null);
                   eventsPanel.add(getjLblEventType(),null);
                   eventsPanel.add(getjLblEventStartTime(),null);
                   eventsPanel.add(getjLblEventEndTime(),null);
                  //jPanel7.add(new JSeparator(), new Dimension(180,10));
                   eventsPanel.add(getjCmbBxEventType(),null);
                   eventsPanel.add(getjCmbBxEventStartTimeHrs(),null);
                   eventsPanel.add(getjLblEventStartTimeColon(),null);
                   eventsPanel.add(getjCmbBxEventStartTimeMin(),null);
                   eventsPanel.add(getjCmbBxEventEndTimeHrs(),null);
                   eventsPanel.add(getjLblEventEndTimeColon(),null);
                   eventsPanel.add(getjCmbBxEventEndTimeMin(),null);
                   eventsPanel.add(getjBtnAdd(),null);
                  //jPanel7.add(getjCmbBxPanel6Location(),null);
              return eventsPanel;
          * mainPanel methods to get components
         private JLabel getjLblCalender()
              if(jLblCalender==null){
              jLblCalender =  new JLabel ();
              jLblCalender.setBounds(new Rectangle(25, 25, 60, 20));
              jLblCalender.setText("Calender");
              System.out.println(jLblCalender.getBounds());
              //jLblCalender.setBounds(20, 20, 100, 16);
              return jLblCalender;
         public JComboBox getjCmbBxCalender(){
              if (jCmbBxCalender == null){
         calender = new String[] {"Office","Counselor"};
          jCmbBxCalender = new JComboBox (calender);
          jCmbBxCalender.setBounds(new Rectangle (90,25,140,20));
              return jCmbBxCalender;
         private JRadioButton getjRdBttnDay(){
               if(jRBttnDay==null){
                    jRBttnDay=new JRadioButton();
                    jRBttnDay.setBounds(new Rectangle(350,25, 60, 20));
                    jRBttnDay.setText("Day");
                    //jRBttnOffice.addItemListener( rhandler );
              return jRBttnDay;
          private JRadioButton getjRdBttnEvent(){
               if(jRBttnEvent==null){
                    jRBttnEvent=new JRadioButton();
                    jRBttnEvent.setBounds(new Rectangle(350, 50, 60, 20));
                    jRBttnEvent.setText("Event");
                    //jRBttnEvent.addItemListener( rhandler );
              return jRBttnEvent;
               * counselorPanel methods to get components
          private JLabel getjLblCounselor()
                   if(jLblCounselor==null){
                   jLblCounselor =  new JLabel ();
                   jLblCounselor.setBounds(new Rectangle(25,25,60,20));
                   jLblCounselor.setText("Counselor");
                   //jLblCalender.setBounds(0, 0, 33, 16);
                   return jLblCounselor;
              private JLabel getjLblLocation()
                   if(jLblLocation==null){
                   jLblLocation =  new JLabel ();
                   jLblLocation.setBounds(new Rectangle(25,60,60,20));
                   jLblLocation.setText("Location");
                   //jLblCalender.setBounds(0, 0, 33, 16);
                   return jLblLocation;
              private JLabel getjLblType()
                   if(jLblType==null){
                   jLblType =  new JLabel ();
                   jLblType.setBounds(new Rectangle(25,95,60,20));
                   jLblType.setText("Type");
                   //jLblCalender.setBounds(0, 0, 33, 16);
                   return jLblType;
              private JLabel getjLblType1()
                   if(jLblType1==null){
                   jLblType1 =  new JLabel ();
                   jLblType1.setBounds(new Rectangle(350, 25, 40, 20));
                   jLblType1.setText("Type  :");
                   //jLblCalender.setBounds(0, 0, 33, 16);
                   return jLblType1;
              public JComboBox getjCmbBxCounselor(){
                   if (jCmbBxCounselor == null){
              counselor = new String[] {"John","Jason","Sam"};
               jCmbBxCounselor = new JComboBox (counselor);
               jCmbBxCounselor.setBounds(new Rectangle (90,25,140,20));
                   return jCmbBxCounselor;
              public JComboBox getjCmbBxLocation(){
                   if (jCmbBxLocation == null){
                        location = new String[] {"Oakland","Sanfrancisco"};
                        jCmbBxLocation= new JComboBox(location);
                        jCmbBxLocation.setBounds(new Rectangle (90,60,140,20));
                   return jCmbBxLocation;
              public JComboBox getjCmbBxType(){
                   if (jCmbBxType == null){
              type = new String[] {"Regular","Non Regular"};
               jCmbBxType = new JComboBox (type);
               jCmbBxType.setBounds(new Rectangle (90,95,140,20));
                   return jCmbBxType;
              private JRadioButton getjRdBttnOffice(){
                    if(jRBttnOffice==null){
                         jRBttnOffice=new JRadioButton();
                         jRBttnOffice.setBounds(new Rectangle(490, 25, 60, 20));
                         jRBttnOffice.setText("Office");
                         //jRBttnOffice.addItemListener( rhandler );
                   return jRBttnOffice;
               private JRadioButton getjRdBttnCounselor(){
                    if(jRBttnCounselor==null){
                         jRBttnCounselor=new JRadioButton();
                         jRBttnCounselor.setBounds(new Rectangle(400, 25, 90, 20));
                         jRBttnCounselor.setText("Counselor");
                         //jRBttnCounselor.addItemListener( rhandler );
                   return jRBttnCounselor;
                    * timePanel methods to get components
               private JLabel getjLblStartDate()
                        if(jLblStartDate==null){
                             jLblStartDate =  new JLabel ();
                             jLblStartDate.setBounds(new Rectangle(25,25,60,20));
                             jLblStartDate.setText("Start Date ");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblStartDate;
                   private JLabel getjLblStartTime()
                        if(jLblStartTime==null){
                             jLblStartTime =  new JLabel ();
                             jLblStartTime.setBounds(new Rectangle(350,25,70,20));
                             jLblStartTime.setText("Start Time ");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblStartTime;
                   private JLabel getjLblEndTime()
                        if(jLblEndTime==null){
                             jLblEndTime =  new JLabel ();
                             jLblEndTime.setBounds(new Rectangle(350,60,70,20));
                             jLblEndTime.setText("End Time ");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblEndTime;
                   private JTextField getjTxtFStartDate() {
                        if (jTxtFStartDate == null) {
                             jTxtFStartDate = new JTextField();
                             //jTxtFRefNum.setBounds(new Rectangle(86, 51, 109, 20));
                             jTxtFStartDate.setBounds(new Rectangle(90,25,140,20));
                             jTxtFStartDate.setText("Start Date");
                        return jTxtFStartDate;
                   private JComboBox getjCmbBxStartTimeMin(){
                        if (jCmbBxStartTimeMin == null){
                   counselor = new String[] {"00","02","03","04"};
                    jCmbBxStartTimeMin = new JComboBox (counselor);
                    jCmbBxStartTimeMin.setBounds(new Rectangle (490,25,40,20));
                        return jCmbBxStartTimeMin;
                   private JComboBox getjCmbBxStartTimeHrs(){
                        if (jCmbBxStartTimeHrs == null){
                   counselor = new String[] {"00","02","03","04"};
                    jCmbBxStartTimeHrs = new JComboBox (counselor);
                    jCmbBxStartTimeHrs.setBounds(new Rectangle (425, 25,40,20));
                        return jCmbBxStartTimeHrs;
                   private JLabel getjLblEndTimeColon()
                        if(jLblEndTimeColon==null){
                             jLblEndTimeColon =  new JLabel ();
                             jLblEndTimeColon.setBounds(new Rectangle(475,60,5,20));
                             jLblEndTimeColon.setText(":");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblEndTimeColon;
                   private JLabel getjLblStartTimeColon()
                        if(jLblStartTimeColon==null){
                             jLblStartTimeColon =  new JLabel ();
                             jLblStartTimeColon.setBounds(new Rectangle(475,25,5,20));
                             jLblStartTimeColon.setText(":");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblStartTimeColon;
                   private JComboBox getjCmbBxEndTimeMin(){
                        if (jCmbBxEndTimeMin == null){
                   counselor = new String[] {"00","02","03","04"};
                    jCmbBxEndTimeMin = new JComboBox (counselor);
                    jCmbBxEndTimeMin.setBounds(new Rectangle (490,60,40,20));
                        return jCmbBxEndTimeMin;
                   private JComboBox getjCmbBxEndTimeHrs(){
                        if (jCmbBxEndTimeHrs == null){
                   counselor = new String[] {"00","02","03","04"};
                    jCmbBxEndTimeHrs = new JComboBox (counselor);
                    jCmbBxEndTimeHrs.setBounds(new Rectangle (425,60,40,20));
                        return jCmbBxEndTimeHrs;
                    * recurrencePanel methods to get components
                   private JLabel getjLblSunday()
                        if(jLblSunday==null){
                             jLblSunday =  new JLabel ();
                             jLblSunday.setBounds(new Rectangle(125, 50, 50, 20));
                             jLblSunday.setText("Sunday");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblSunday;
                   private JLabel getjLblMonday()
                        if(jLblMonday==null){
                             jLblMonday =  new JLabel ();
                             jLblMonday.setBounds(new Rectangle(205,50,50,20));
                             jLblMonday.setText("Monday");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblMonday;
                   private JLabel getjLblTuesday()
                        if(jLblTuesday==null){
                             jLblTuesday =  new JLabel ();
                             jLblTuesday.setBounds(new Rectangle(285,50,50,20));
                             jLblTuesday.setText("Tuesday");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblTuesday;
                   private JLabel getjLblWednesday()
                        if(jLblWednesday==null){
                             jLblWednesday =  new JLabel ();
                             jLblWednesday.setBounds(new Rectangle(370, 50,70,20));
                             jLblWednesday.setText("Wednesday");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblWednesday;
                   private JLabel getjLblThursday()
                        if(jLblThursday==null){
                             jLblThursday =  new JLabel ();
                             jLblThursday.setBounds(new Rectangle(475,50,60,20));
                             jLblThursday.setText("Thursday");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblThursday;
                   private JLabel getjLblFriday()
                        if(jLblFriday==null){
                             jLblFriday =  new JLabel ();
                             jLblFriday.setBounds(new Rectangle(565,50,40,20));
                             jLblFriday.setText("Friday");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblFriday;
                   private JLabel getjLblSaturday()
                        if(jLblSaturday==null){
                             jLblSaturday =  new JLabel ();
                             jLblSaturday.setBounds(new Rectangle(635,50,60,20));
                             jLblSaturday.setText("Saturday");
                        //jLblCalender.setBounds(0, 0, 33, 16);
                        return jLblSaturday;
                   private JCheckBox getjChkBxSunday() {
                        if (jChkBxSunday == null) {
                             jChkBxSunday = new JCheckBox ("Sunday",false);
                             jChkBxSunday.setBounds(new Rectangle(100,50,20,20));
                        return jChkBxSunday;
                    private JCheckBox getjChkBxMonday() {
                             if (jChkBxMonday == null) {
                                  jChkBxMonday = new JCheckBox ("Monday",false);
                                  jChkBxMonday.setBounds(new Rectangle(180,50,20,20));
                             return jChkBxMonday;
                    private JCheckBox getjChkBxTuesday() {
                             if (jChkBxTuesday == null) {
                                  jChkBxTuesday = new JCheckBox ("Tuesday",false);
                                  jChkBxTuesday.setBounds(new Rectangle(260,50,20,20));
                             return jChkBxTuesday;
                    private JCheckBox getjChkBxWednesday() {
                             if (jChkBxWednesday == null) {
                                  jChkBxWednesday = new JCheckBox ("Wedneday",false);
                                  jChkBxWednesday.setBounds(new Rectangle(345,50,20,20));
                             return jChkBxWednesday;
                    private JCheckBox getjChkBxThursday() {
                             if (jChkBxThursday == null) {
                                  jChkBxThursday = new JCheckBox ("Thursday",false);
                                  jChkBxThursday.setBounds(new Rectangle(450,50,20,20));
                             return jChkBxThursday;
                    private JCheckBox getjChkBxFriday() {
                             if (jChkBxFriday == null) {
                                  jChkBxFriday = new JCheckBox ("Friday",false);
                                  jChkBxFriday.setBounds(new Rectangle(540,50,20,20));
                             return jChkBxFriday;
                    private JCheckBox getjChkBxSaturday() {
                             if (jChkBxSaturday == null) {
                                  jChkBxSaturday = new JCheckBox ("Saturday",false);
                                  jChkBxSaturday.setBounds(new Rectangle(610,50,20,20));
                             return jChkBxSaturday;
                    private JLabel getjLblEndDate()
                             if(jLblEndDate==null){
                                  jLblEndDate =  new JLabel ();
                                  jLblEndDate.setBounds(new Rectangle(25,85,60,20));
                                  jLblEndDate.setText("End Date");
                             //jLblCalender.setBounds(0, 0, 33, 16);
                             return jLblEndDate;
                    private JTextField getjTxtFEndDate() {
                             if (jTxtFEndDate == null) {
                                  jTxtFEndDate = new JTextField();
                                  //jTxtFRefNum.setBounds(new Rectangle(86, 51, 109, 20));
                                  jTxtFEndDate.setBounds(new Rectangle(90,85,140,20));
                                  jTxtFEndDate.setText("End Date");
                             return jTxtFEndDate;
                    private JLabel getjLblRecurrence()
                             if(jLblRecurrence==null){
                                  jLblRecurrence =  new JLabel ();
                                  jLblRecurrence.setBounds(new Rectangle(25,25,80,20));
                                  jLblRecurrence.setText("Recurrence ");
                             //jLblCalender.setBounds(0, 0, 33, 16);
                             return jLblRecurrence;
                         * buttonsPanel methods to get components
                    private JButton getjBtnCancel(){
                         if(jBttnCancel==null){
                              jBttnCancel=new JButton();
                              jBttnCancel.setBounds(new Rectangle(510,25,80,20));
                              jBttnCancel.setText("Cancel");
                        return jBttnCancel;
                    private JButton getjBtnSave(){
                         if(jBttnSave==null){
                              jBttnSave=new JButton();
                              jBttnSave.setBounds(new Rectangle(600,25,80,20));
                              jBttnSave.setText("Save");
                        return jBttnSave;
                         * OfficePanel methods to get components
                    private JLabel getjLblPanelOfficeType()
                             if(jLblPanelOfficeType==null){
                                  jLblPanelOfficeType =  new JLabel ();
                                  jLblPanelOfficeType.setBounds(new Rectangle(25,25,60,20));
                                  jLblPanelOfficeType.setText("Type");
                             //jLblCalender.setBounds(0, 0, 33, 16);
                             return jLblPanelOfficeType;
                        private JLabel getjLblPanelOfficeLocation()
                             if(jLblPanelOfficeLocation==null){
                                  jLblPanelOfficeLocation =  new JLabel ();
                                  jLblPanelOfficeLocation.setBounds(new Rectangle(25,60,60,20));
                                  jLblPanelOfficeLocation.setText("Location");
                             //jLblCalender.setBounds(0, 0, 33, 16);
                             return jLblPanelOfficeLocation;
                        public JComboBox getjCmbBxPanelOfficeLocation(){
                             if (jCmbBxPanelOfficeLocation == null){
                                  String[] Officelocation = new String[] {"OakLand","San Fransisco"};
                        jCmbBxPanelOfficeLocation = new JComboBox (Officelocation);;
                        jCmbBxPanelOfficeLocation.setBounds(new Rectangle (90,60,140,20));
                             return jCmbBxPanelOfficeLocation;
                        private JComboBox getjCmbBxPanelOfficeType(){
                             if (jCmbBxPanelOfficeType == null){
                                  String [] Officetype = new String[] {"Regular","OnCall"};
                         jCmbBxPanelOfficeType = new JComboBox (Officetype);
                         jCmbBxPanelOfficeType.setBounds(new Rectangle (90,25,140,20));
                             return jCmbBxPanelOfficeType;
                         * eventsPanel methods to get components
                        private JComboBox getjCmbBxEventType(){
                             if (jCmbBxEventType == null){
                        counselor = new String[] {"John","Jason"};
                         jCmbBxEventType = new JComboBox (counselor);
                         jCmbBxEventType.setBounds(new Rectangle (120,90,130,20));
                             return jCmbBxEventType;
                        private JComboBox getjCmbBxEventStartTimeHrs(){
                             if (jCmbBxEventStartTimeHrs == null){
                        counselor = new String[] {"12","00"};
                         jCmbBxEventStartTimeHrs = new JComboBox (counselor);
                         jCmbBxEventStartTimeHrs.setBounds(new Rectangle (290,90,40,20));
                             return jCmbBxEventStartTimeHrs;
                        private JComboBox getjCmbBxEventStartTimeMin(){
                             if (jCmbBxEventStartTimeMin == null){
                        counselor = new String[] {"00","02","03","04"};
                         jCmbBxEventStartTimeMin = new JComboBox (counselor);
                         jCmbBxEventStartTimeMin.setBounds(new Rectangle (355,90,40,20));
                             return jCmbBxEventStartTimeMin;
                        private JComboBox getjCmbBxEventEndTimeHrs(){
                             if (jCmbBxEventEndTimeHrs == null){
                        counselor = new String[] {"00","02","03","04"};
                         jCmbBxEventEndTimeHrs = new JComboBox (counselor);
                         jCmbBxEventEndTimeHrs.setBounds(new Rectangle (470,90,40,20));
                             return jCmbBxEventEndTimeHrs;
                        private JComboBox getjCmbBxEventEndTimeMin(){
                             if (jCmbBxEventEndTimeMin == null){
                        counselor = new String[] {"John","Jason","Sam"};
                         jCmbBxEventEndTimeMin = new JComboBox (counselor);
                         jCmbBxEventEndTimeMin.setBounds(new Rectangle (535,90,40,20));
                             return jCmbBxEventEndTimeMin;
                        private JLabel getjLblEventType()
                             if(jLblEventType==null){
                             jLblEventType =  new JLabel ();
                             jLblEventType.setBounds(new Rectangle(150, 60,60,20));
                             jLblEventType.setText("Type");
                             //System.out.println(jLblCalender.getBounds());
                             //jLblCalender.setBounds(20, 20, 100, 16);
                             return jLblEventType;
                        private JLabel getjLblEvent()
                             if(jLblEvents==null){
                             jLblEvents =  new JLabel ();
                             jLblEvents.setBounds(new Rectangle(325, 25, 60, 20));
                             jLblEvents.setText("Events");
                             //System.out.println(jLblCalender.getBounds());
                             //jLblCalender.setBounds(20, 20, 100, 16);
                             return jLblEvents;
                        private JLabel getjLblEventStartTime()
                             if(jLblEventStartTime==null){
                             jLblEventStartTime =  new JLabel ();
                             jLblEventStartTime.setBounds(new Rectangle(310, 60,60,20));
                             jLblEventStartTime.setText("Start Time");
                             //System.out.println(jLblCalender.getBounds());
                             //jLblCalender.setBounds(20, 20, 100, 16);
                             return jLblEventStartTime;
                        private JLabel getjLblEventEndTime()
                             if(jLblEventEndTime==null){
                             jLblEventEndTime =  new JLabel ();
                             jLblEventEndTime.setBounds(new Rectangle(500, 60,60,20));
                             jLblEventEndTime.setText("End Time");
                             //System.out.println(jLblCalender.getBounds());
                             //jLblCalender.setBounds(20, 20, 100, 16);
                             return jLblEventEndTime;
                        private JLabel getjLblEventStartTimeColon()
                             if(jLblEventStartTimeColon==null){
                                  jLblEventStartTimeColon =  new JLabel ();
                                  jLblEventStartTimeColon.setBounds(new Rectangle(340,90,5,20));
                                  jLblEventStartTimeColon.setText(":");
                             //jLblCalender.setBounds(0, 0, 33, 16);
                             return jLblEventStartTimeColon;
                        private JLabel getjLblEventEndTimeColon()
                             if(jLblEventEndTimeColon==null){
                                  jLblEventEndTimeColon =  new JLabel ();
                                  jLblEventEndTimeColon.setBounds(new Rectangle(520,90,5,20));
                                  jLblEventEndTimeColon.setText(":");
                             //jLblCalender.setBounds(0, 0, 33, 16);
                             return jLblEventEndTimeColon;
                         private JButton getjBtnAdd(){
                              if(jBttnAdd==null){
                                   jBttnAdd=new JButton();
                                   jBttnAdd.setBounds(new Rectangle(25,115,80,20));
                                   jBttnAdd.setText("Add");
                             return jBttnAdd;
    //                     Action Listeners
                                  public void addCmbBoxCalenderListener (ItemListener eve){
                                  if (this.jCmbBxCalender != null){
                                       jCmbBxCalender.addItemListener(eve);
                             }Here is my controller code:
    private class JCmbBxCalenderListener implements ActionListener {
                   public void actionPerformed( ActionEvent event ){
                         try{
                              if(((JComboBox) event.getSource()).getSelectedItem().equals("Office Calender")){
                                   //calenderAdmin_View.jContentPane.revalidate();
                                   calenderAdmin_View.jContentPane.remove(calenderAdmin_View.getcounselorPanel());
                                   calenderAdmin_View.getcounselorPanel().setVisible(false);
                                       calenderAdmin_View.jContentPane.add(calenderAdmin_View.getofficePanel(),1);
                                   calenderAdmin_View.getofficePanel().setVisible(true);
                                   calenderAdmin_View.jContentPane.validate();
                              else
                                   if(((JComboBox) event.getSource()).getSelectedItem().equals("Counselor Calender"))
                                        //calenderAdmin_View.jContentPane.revalidate();
                                        calenderAdmin_View.jContentPane.remove(calenderAdmin_View.getofficePanel());
                                        calenderAdmin_View.getofficePanel().setVisible(false);
                                        calenderAdmin_View.jCo                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          

  • Problem with CardLayout

    I ve got a JFrame object and i want to put in it a JMenuBar and a CardLayout that contains two JPanel.
    1. Is it possible to do that
    3. how to do it.(I have already created my JMenuBar in my JFrame)

    Ok this is my source code.
    my problem is to insert a cardlayout it dosen't seem to work.
    Can you help me please.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.TitledBorder ;
    public class Frame1 extends javax.swing.JFrame
         Panel_Moteur jPanel1 = new Panel_Moteur();
         javax.swing.JMenuBar jMenuBar1 = new javax.swing.JMenuBar();
         javax.swing.JMenu jMenuFichier = new javax.swing.JMenu();
         javax.swing.JSeparator jMenuFichierSeparator1 = new javax.swing.JSeparator();
         javax.swing.JMenuItem jMenuFichierQuitter = new javax.swing.JMenuItem();
         javax.swing.JMenu jMenuConfiguration = new javax.swing.JMenu();
         javax.swing.JMenuItem jMenuConfigurationMoteur = new javax.swing.JMenuItem();
         javax.swing.JSeparator jMenuConfigurationSeparator1 = new javax.swing.JSeparator();
         javax.swing.JMenuItem jMenuConfigurationHoraire = new javax.swing.JMenuItem();
         javax.swing.JMenu jMenuProgrammes = new javax.swing.JMenu();
         javax.swing.JMenuItem jMenuProgrammesAjouter = new javax.swing.JMenuItem();
         javax.swing.JMenuItem jMenuProgrammesModifier = new javax.swing.JMenuItem();
         javax.swing.JMenuItem jMenuProgrammesSupprimer = new javax.swing.JMenuItem();
         javax.swing.JSeparator jMenuProgrammesSeparator1 = new javax.swing.JSeparator();
         javax.swing.JMenuItem jMenuProgrammesVisualiser = new javax.swing.JMenuItem();
         javax.swing.JMenu jMenuAcquisition = new javax.swing.JMenu();
         javax.swing.JMenuItem jMenuAcquisitionCapture = new javax.swing.JMenuItem();
         javax.swing.JMenu jMenuReconstitution = new javax.swing.JMenu();
         javax.swing.JMenuItem jMenuReconstitutionImageGlobale = new javax.swing.JMenuItem();
         JPanel cards = new JPanel();
         CardLayout cardlayout = new CardLayout() ;
         public Frame1() {
         public void initComponents() throws Exception
              cards.setSize(new java.awt.Dimension(930, 830));
              cards.setLocation(new java.awt.Point(0, 40));
    cards.setLayout(cardlayout);
              cards.add(jPanel1,"t");
              jMenuBar1.setVisible(true);
              jMenuFichier.setVisible(true);
              jMenuFichier.setText("Fichier");
              jMenuFichierSeparator1.setVisible(true);
              jMenuFichierQuitter.setVisible(true);
              jMenuFichierQuitter.setText("Quitter");
              jMenuConfiguration.setVisible(true);
              jMenuConfiguration.setText("Configuration");
              jMenuConfigurationMoteur.setVisible(true);
              jMenuConfigurationMoteur.setText("Moteur");
              jMenuConfigurationSeparator1.setVisible(true);
              jMenuConfigurationHoraire.setVisible(true);
              jMenuConfigurationHoraire.setText("Horaire");
              jMenuProgrammes.setVisible(true);
              jMenuProgrammes.setText("Programmes");
              jMenuProgrammesAjouter.setVisible(true);
              jMenuProgrammesAjouter.setText("Ajouter");
              jMenuProgrammesModifier.setVisible(true);
              jMenuProgrammesModifier.setText("Modifier");
              jMenuProgrammesSupprimer.setVisible(true);
              jMenuProgrammesSupprimer.setText("Supprimer");
              jMenuProgrammesSeparator1.setVisible(true);
              jMenuProgrammesVisualiser.setVisible(true);
              jMenuProgrammesVisualiser.setText("Visualiser");
              jMenuAcquisition.setVisible(true);
              jMenuAcquisition.setText("Acquisition");
              jMenuAcquisitionCapture.setVisible(true);
              jMenuAcquisitionCapture.setText("Capture");
              jMenuReconstitution.setVisible(true);
              jMenuReconstitution.setText("Reconstitution");
              jMenuReconstitutionImageGlobale.setVisible(true);
              jMenuReconstitutionImageGlobale.setText("Image Globale");
              setLocation(new java.awt.Point(150, 70));
              setResizable(false);
              setJMenuBar(jMenuBar1);
              getContentPane().setLayout(null);
              setTitle("ProjetAutoroot.Frame1");
              jMenuBar1.add(jMenuFichier);
              jMenuBar1.add(jMenuConfiguration);
              jMenuBar1.add(jMenuProgrammes);
              jMenuBar1.add(jMenuAcquisition);
              jMenuBar1.add(jMenuReconstitution);
              jMenuFichier.add(jMenuFichierSeparator1);
              jMenuFichier.add(jMenuFichierQuitter);
              jMenuConfiguration.add(jMenuConfigurationMoteur);
              jMenuConfiguration.add(jMenuConfigurationSeparator1);
              jMenuConfiguration.add(jMenuConfigurationHoraire);
              jMenuProgrammes.add(jMenuProgrammesAjouter);
              jMenuProgrammes.add(jMenuProgrammesModifier);
              jMenuProgrammes.add(jMenuProgrammesSupprimer);
              jMenuProgrammes.add(jMenuProgrammesSeparator1);
              jMenuProgrammes.add(jMenuProgrammesVisualiser);
              jMenuAcquisition.add(jMenuAcquisitionCapture);
              jMenuReconstitution.add(jMenuReconstitutionImageGlobale);
              getContentPane().add(cards);
              setSize(new java.awt.Dimension(941, 923));
              jMenuFichierQuitter.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        jMenuFichierQuitterActionPerformed(e);
              jMenuConfigurationMoteur.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        jMenuConfigurarionMoteurActionPerformed(e);
              addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        thisWindowClosing(e);
         private boolean mShown = false;
         public void addNotify() {
              super.addNotify();
              if (mShown)
                   return;
              // resize frame to account for menubar
              JMenuBar jMenuBar = getJMenuBar();
              if (jMenuBar != null) {
                   int jMenuBarHeight = jMenuBar.getPreferredSize().height;
                   Dimension dimension = getSize();
                   dimension.height += jMenuBarHeight;
                   setSize(dimension);
              mShown = true;
         // Close the window when the close box is clicked
         void thisWindowClosing(java.awt.event.WindowEvent e) {
              setVisible(false);
              dispose();
              System.exit(0);
         public void jMenuFichierQuitterActionPerformed(java.awt.event.ActionEvent e) {
              setVisible(false);
              dispose();
              System.exit(0);
         public void jMenuConfigurarionMoteurActionPerformed (java.awt.event.ActionEvent e)
              System.out.println("bonjour") ;
              CardLayout cl = (CardLayout)(cards.getLayout());
              cl.show(cards,"t");
         public void jRadioButton1StateChanged(javax.swing.event.ChangeEvent e) {
         public void jRadioButton2StateChanged(javax.swing.event.ChangeEvent e) {
         public void jRadioButton9StateChanged(javax.swing.event.ChangeEvent e) {
    }

  • Problems displaying deserialized components

    I'm trying to save the state of some objects which extend JComponent and JLayeredPane, and they don't all redisplay on deserializing, although they seem to be in the containment tree.
    Basically, I have a class GamePanel which extends JLayeredPane. Also classes Square and Region both of which extend JComponent and use 2D graphics for painting themselves. It seems to serialize OK (but how does one tell?). But when I deserialize, only the lower level of the GamePanel is painted. However, the higher level is populated.
    Does anyone have any idea why they're not displaying? The code is below (TestKiller and its menus are generated by NetBeans - hence the slightly odd code). There are 5 menu items (I've simplified a lot from the original so it's a bit clunky): Add Region (you can only do this once in this version), Save As which serializes to a file, Restore which deserializes from a file, Exit which is obvious and Print which outputs the containment hierarchy of GamePanel to standard output.
    If you want to try it out, fire up the program, do a File|Add to add a Region (see the dotted lines) and File|Print to see that there's a Square at level 2 and a Region at level 3. Then File|Save as... to save it. Quit the program.
    Fire it up again and do a File|Restore and a File|Print. You'll see from the output that the Square and Region are there with identical parameters to the output before, but the Region hasn't displayed its outline.
    The output's below, with java-like comments added to show what I've done:
    D:>java -jar test*
    Painting gridlayer
    // File|Add Region
    New region 1
    Selecting square
    Checking region 1
    Painting gridlayer
    Painting region 1
    //File|Print
    Printing Gamepanel components
    com.ptoye.TestSBug1.Region[Region-1,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minim
    umSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 3
    com.ptoye.TestSBug1.Square[Square-0:0,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=16777224,maximumSi
    ze=,minimumSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 2
    \\File|Save
    Saving game to bug1.ksd
    D:>java -jar test*
    Painting gridlayer
    \\File|Restore
    Restoring game bug1.ksd
    Restored
    \\File|Print - same as above but only Square is displayed
    Printing Gamepanel components
    com.ptoye.TestSBug1.Region[Region-1,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minim
    umSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 3
    com.ptoye.TestSBug1.Square[Square-0:0,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=16777224,maximumSi
    ze=,minimumSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 2
    D:>
    Please someone tell me what I'm doing wrong. As a serialization newbie it's probably something simple, but no amount of validate() and pack() makes any difference.
    The code's below - a bit long I'm afraid but it's difficult to cut it down much more and display the problem. The main class (TestKiller) was generated by NetBeans.
    * TestKiller.java
    * Created on 01 August 2006, 22:13
    package com.ptoye.TestSBug1;
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    * @author  PToye
    public class TestKiller extends javax.swing.JFrame {
      private GamePanel p;
      final String fileExtension="ksd";
       * Creates new form TestKiller
      public TestKiller() {
        initComponents();
        p=new GamePanel();
        setContentPane(p);
        p.setOpaque(true);
        setSize(p.getPreferredSize());
        pack();
      public static void showMessage(String s) {
        JOptionPane.showMessageDialog(null,s,"Error",JOptionPane.ERROR_MESSAGE);
      /** This method is called from within the constructor to
       * initialize the form.
       * WARNING: Do NOT modify this code. The content of this method is
       * always regenerated by the Form Editor.
      private void initComponents() {                         
        jMenuBar1 = new javax.swing.JMenuBar();
        jmFile = new javax.swing.JMenu();
        jmiAddRegion = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        jmiSaveAs = new javax.swing.JMenuItem();
        jmiRestore = new javax.swing.JMenuItem();
        jmiExit = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jmiPrint = new javax.swing.JMenuItem();
        FormListener formListener = new FormListener();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Restore bug");
        jmFile.setText("File");
        jmiAddRegion.setText("Add region");
        jmiAddRegion.addActionListener(formListener);
        jmFile.add(jmiAddRegion);
        jmFile.add(jSeparator2);
        jmiSaveAs.setMnemonic('s');
        jmiSaveAs.setText("Save as...");
        jmiSaveAs.addActionListener(formListener);
        jmFile.add(jmiSaveAs);
        jmiRestore.setMnemonic('r');
        jmiRestore.setText("Restore");
        jmiRestore.addActionListener(formListener);
        jmFile.add(jmiRestore);
        jmiExit.setMnemonic('x');
        jmiExit.setText("Exit");
        jmiExit.addActionListener(formListener);
        jmFile.add(jmiExit);
        jmFile.add(jSeparator1);
        jmiPrint.setText("Print");
        jmiPrint.addActionListener(formListener);
        jmFile.add(jmiPrint);
        jMenuBar1.add(jmFile);
        setJMenuBar(jMenuBar1);
        pack();
      // Code for dispatching events from components to event handlers.
      private class FormListener implements java.awt.event.ActionListener {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
          if (evt.getSource() == jmiSaveAs) {
            TestKiller.this.jmiSaveAsActionPerformed(evt);
          else if (evt.getSource() == jmiRestore) {
            TestKiller.this.jmiRestoreActionPerformed(evt);
          else if (evt.getSource() == jmiExit) {
            TestKiller.this.jmiExitActionPerformed(evt);
          else if (evt.getSource() == jmiPrint) {
            TestKiller.this.jmiPrintActionPerformed(evt);
          else if (evt.getSource() == jmiAddRegion) {
            TestKiller.this.jmiAddRegionActionPerformed(evt);
      private void jmiAddRegionActionPerformed(java.awt.event.ActionEvent evt) {                                            
        p.dummyAdd();
        jmiAddRegion.setEnabled(false);
      private void jmiPrintActionPerformed(java.awt.event.ActionEvent evt) {                                        
        p.print();
      private void jmiSaveAsActionPerformed(java.awt.event.ActionEvent evt) {                                         
        File f;
        ObjectOutputStream oos=null;
        JFileChooser jfc=new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setMultiSelectionEnabled(false);
        jfc.addChoosableFileFilter(jfc.getAcceptAllFileFilter());
        jfc.addChoosableFileFilter(new KDSFileFilter());
        jfc.showSaveDialog(this);
        f=jfc.getSelectedFile();
        if (f==null) {
          showMessage("Null file found");
        int i=f.getName().lastIndexOf(".");
        if (i==-1) {
          f=new File(f.getAbsolutePath()+"."+fileExtension);
        try {
          oos=new ObjectOutputStream(new FileOutputStream(f));
        } catch (FileNotFoundException ex) {
          showMessage("Cannot find file "+f.getName());
          return;
        } catch (IOException ex) {
          showMessage("Cannot open file "+f.getName());
          return;
        if (oos!=null) {
          System.out.println("Saving game to "+f.getName());
          try {
            oos.writeObject(p);
          } catch (IOException ex) {
            showMessage("Cannot write game to "+f.getName()+"\n"+ex.getMessage());
          } finally {
            try {
              oos.close();
            } catch (IOException ex) {
      private void jmiExitActionPerformed(java.awt.event.ActionEvent evt) {                                       
        System.exit(0);
      private void jmiRestoreActionPerformed(java.awt.event.ActionEvent evt) {                                          
        File f;
        ObjectInputStream ois=null;
        JFileChooser jfc=new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setMultiSelectionEnabled(false);
        jfc.addChoosableFileFilter(jfc.getAcceptAllFileFilter());
        jfc.addChoosableFileFilter( new KDSFileFilter());
        jfc.showOpenDialog(this);
        f=jfc.getSelectedFile();
        if (f!=null) {
          try {
            ois=new ObjectInputStream(new FileInputStream(f));
          } catch (FileNotFoundException ex) {
            showMessage("Cannot find file "+f.getName());
            return;
          } catch (IOException ex) {
            showMessage("Cannot open file "+f.getName());
            return;
          if (ois!=null) {
            System.out.println("Restoring game "+f.getName());
            try {
              p=(GamePanel) ois.readObject();
            } catch (IOException ex) {
              showMessage("Cannot read game from file "+f.getName());
            } catch (ClassNotFoundException ex) {
              showMessage("Cannot restore game - wrong object type");
            try {
              ois.close();
            } catch (IOException ex) {
            pack();
            p.validate();
            p.repaint();
            System.out.println("Restored");
      private class KDSFileFilter extends javax.swing.filechooser.FileFilter {
        public boolean accept(File f) {
          if (f.isDirectory()) {
            return true;
          String ext = null;
          String s = f.getName();
          int i = s.lastIndexOf('.');
          if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
          return (ext==null || ext.equalsIgnoreCase(fileExtension));
        public String getDescription() {
          return "Killer Su Doku games";
       * @param args the command line arguments
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            new TestKiller().setVisible(true);
      // Variables declaration - do not modify                    
      private javax.swing.JMenuBar jMenuBar1;
      private javax.swing.JSeparator jSeparator1;
      private javax.swing.JSeparator jSeparator2;
      private javax.swing.JMenu jmFile;
      private javax.swing.JMenuItem jmiAddRegion;
      private javax.swing.JMenuItem jmiExit;
      private javax.swing.JMenuItem jmiPrint;
      private javax.swing.JMenuItem jmiRestore;
      private javax.swing.JMenuItem jmiSaveAs;
      // End of variables declaration                  
    * GamePanel.java
    * Created on 10 January 2007, 18:45
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestSBug1;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.io.Serializable;
    import java.util.HashSet;
    import java.util.Set;
    import javax.swing.JLayeredPane;
    * @author PToye
    public class GamePanel extends JLayeredPane implements Serializable {
      private static final int GRID_LEVEL=2;
      private static final int REGIONS_LEVEL=3;
      private static final int THICK_WIDTH=4;
      private static final int THIN_WIDTH=1;
      static final int SQUARE_SIZE=60;
      private static final int SQUARES=1;  // test size
      static final int BIGSQUARES=SQUARES*SQUARES;
      static final int TotalSize=(SQUARES+1)*THICK_WIDTH+SQUARES*(SQUARES-1)*THIN_WIDTH+
          BIGSQUARES*SQUARE_SIZE;
      public final Color NORMAL_BACK_COLOUR=Color.WHITE;
      public final Color SELECTED_BACK_COLOUR=Color.PINK;
      int coordArray;  // used to be an array of start coords of each square
      private Region newRegion;
      private int regionId=1;
      private Square squareArray; // used to be an array
      private Region regions; // used to be a set
      /** Creates a new instance of GamePanel */
      public GamePanel() {
        super();
        regions=null;
        makeGridLayer();  //adds the white square
        setPreferredSize(new Dimension(TotalSize,TotalSize));
        setVisible(true);
        newRegion=null;
        setFocusable(true);
      public void dummyAdd() {
        setupRegion(squareArray);
        if (newRegion.checkNewRegion(1)) {
          addRegion(newRegion);
      public void addRegion(Region r) {
        if (regions==null) {
          regions=r;
          add(r,new Integer(REGIONS_LEVEL));
          r.repaint();
      void print() {
        Component[] cList=getComponents();
        System.out.println("Printing Gamepanel components");
        for (int i = 0; i < cList.length; i++) {
          Component c=cList;
    System.out.println(c.toString());
    System.out.println(" Bounds "+c.getBounds());
    System.out.println(" Layer "+getLayer(c));
    if (c instanceof Container) {
    printContainer((Container)c," ");
    void printContainer(Container c, String preString) {
    Component[] cList1=c.getComponents();
    for (int i = 0; i < cList1.length; i++) {
    Component comp=cList1[i];
    System.out.println(preString+comp.toString());
    System.out.println(preString+" Bounds "+comp.getBounds());
    if (comp instanceof Container) {
    printContainer((Container)comp,preString+" ");
    private void setupRegion(Square s) {
    if (newRegion==null) {
    newRegion=new Region(regionId++,this);
    Region r=s.getRegion();
    if (r==null) {
    newRegion.addSquare(s);
    selectSquare(s);
    s.setRegion(newRegion);
    } else {
    System.exit(1); // should not happen
    private void makeGridLayer() {
    int currentXCoord;
    int currentYCoord;
    int arrayIndex=0;
    Square sq;
    currentXCoord=THICK_WIDTH;
    currentYCoord=THICK_WIDTH;
    coordArray=currentYCoord;
    sq=new Square(0,0, NORMAL_BACK_COLOUR,this);
    add(sq,new Integer(GRID_LEVEL));
    squareArray=sq;
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    System.out.println("Painting gridlayer");
    g2.setBackground(Color.BLACK);
    g2.setColor(Color.BLACK);
    g2.fillRect(0,0,TotalSize,TotalSize);
    void selectSquare(Square s) {
    System.out.println("Selecting square");
    s.setBackColour(SELECTED_BACK_COLOUR);
    * Square.java
    * Created on 28 December 2006, 15:53
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestSBug1;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.io.Serializable;
    import javax.swing.JComponent;
    * @author PToye
    class Square extends JComponent implements Serializable {
    * X index in grid
    private int xIndex;
    * Y index in grid
    private int yIndex;
    * The square's parent grid
    private GamePanel parent;
    * Region it belongs to (or null if none)
    private Region region;
    * The background colour
    private Color backColour;
    private boolean marked;
    // public Square() {
    // System.out.println("New Square - null constructor");
    // addMouseListener(parent);
    * Create a new square
    public Square(int x, int y, Color bcol, GamePanel parent) {
    this.parent=parent;
    xIndex=x;
    yIndex=y;
    backColour=bcol;
    region=null;
    setName("Square-"+x+":"+y);
    setBounds(parent.coordArray,parent.coordArray,
    GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    setOpaque(true);
    setVisible(true);
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    // System.out.println("Painting square "+xIndex+","+yIndex+":"+getBounds());
    g2.setColor(backColour);
    g2.fillRect(0,0,GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    g2.setColor(Color.BLACK);
    public Dimension getPreferredSize() {
    return new Dimension(GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    public void setBackColour(Color backColour) {
    this.backColour = backColour;
    repaint(0,0,GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    public Region getRegion() {
    return region;
    public void setRegion(Region region) {
    this.region = region;
    * Region.java
    * Created on 28 December 2006, 15:59
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestSBug1;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.GeneralPath;
    import java.io.Serializable;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JComponent;
    * @author PToye
    * Class representing a region whose total sum is known
    public class Region extends JComponent implements Serializable {
    private static final float BORDER_WIDTH=1f;
    private static final float DASH_LENGTH=4f;
    private static final float[] dashes={DASH_LENGTH,DASH_LENGTH};
    private static final BasicStroke borderStroke=
    new BasicStroke(BORDER_WIDTH,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,
    1f,dashes,0);
    private static final int borderInset=3;
    private GamePanel parent;
    * The sum as given
    private int total;
    private String totalString;
    private int id;
    * The squares constituting the region
    private Square contents; // the square in the region
    private Square leadSquare; // top left-hand square
    private int leadXCoord,leadYCoord; // X, Y coords of lead square wrt border
    private GeneralPath border=null;
    public Region(int id, GamePanel parent) {
    super();
    this.id=id;
    this.parent=parent;
    setName("Region-"+id);
    contents=null;
    border=new GeneralPath();
    System.out.println("New region "+id);
    public void addSquare(Square s) {
    if (contents!=null) {
    contents=s;
    public boolean checkNewRegion(int tot) {
    System.out.println("Checking region "+id);
    border.moveTo(borderInset,borderInset);
    border.lineTo(GamePanel.SQUARE_SIZE-borderInset,borderInset);
    border.lineTo(GamePanel.SQUARE_SIZE-borderInset,GamePanel.SQUARE_SIZE-borderInset);
    border.lineTo(borderInset,GamePanel.SQUARE_SIZE-borderInset);
    border.lineTo(borderInset,borderInset);
    setBounds(parent.coordArray,parent.coordArray,GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    repaint();
    return true;
    public void paintComponent(Graphics g) {
    int newX, newY;
    System.out.println("Painting region "+id);
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    g2.setColor(Color.BLACK);
    g2.setStroke(borderStroke);
    g2.draw(border);

    OK, I asked the FTE team and got this reply: "Lucida Grande is CTS's fallback font for Thai.  This font on OS 10.7 and 10.6 are not supporting Thai anymore.  The version on 10.5 was supporting it." This means that it's our bug that we keep using Lucida Grande as fallback font even Apple dropped support Thai script with that font after 10.6. Unfortunately this bug was deferred from current development release (11.2) because of time constraint. If this support is critical for your business, can you open a bug in our public bugbase and ask as many vote as possible? In this way I may be able to convince internal team to fix this bug in next release.
    Thank you for your feedback!
    Hitomi

  • Problem about jtable and database

    The problem is that when i clicked the button to save the values of textfields and text area, although the table is supposed to show the new list of datas from the db, it adds the new data list to the end of the first list. I have to list one old and one new in jtable.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * DatabaseConnection.java
    * Created on 28.Aðu.2008, 11:24:52
    package databaseconnection;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableModel;
    * @author ARAGORN
    public class DatabaseConnection extends javax.swing.JFrame {
        /** Creates new form DatabaseConnection */
        public DatabaseConnection() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Students", "admin", "1837837");
                st = con.createStatement();
            } catch (Exception e) {
                System.out.println("Database Connection Error!");
            try {
                ResultSet rs = st.executeQuery("SELECT*FROM studentdata");
                while (rs.next()) {
                    Object[] rowValues = {rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),rs.getString(6),rs.getInt(7)};
                    row.addElement(rowValues);
                data = new Object[row.size()][7];
                for(int i=0;i<row.size();i++){
                    data=(Object[]) row.get(i);
    } catch (Exception e) {
    System.out.println("reading error!");
    initComponents();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jSeparator1 = new javax.swing.JSeparator();
    jLabel2 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jTextField3 = new javax.swing.JTextField();
    jTextField4 = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jLabel5 = new javax.swing.JLabel();
    jLabel6 = new javax.swing.JLabel();
    jTextField5 = new javax.swing.JTextField();
    jLabel7 = new javax.swing.JLabel();
    jTextField6 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowOpened(java.awt.event.WindowEvent evt) {
    formWindowOpened(evt);
    jTable1.setModel(new javax.swing.table.DefaultTableModel(data,heading)
    jScrollPane1.setViewportView(jTable1);
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Öðrenci Bilgileri", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
    jLabel1.setText("Öðrenci No : ");
    jLabel2.setText("Adý : ");
    jLabel3.setText("Sýnýf : ");
    jLabel4.setText("Soyad : ");
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane2.setViewportView(jTextArea1);
    jLabel5.setText("Adress : ");
    jLabel6.setText("Tel : ");
    jLabel7.setText("Þube : ");
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(22, 22, 22)
    .addComponent(jLabel1)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(364, Short.MAX_VALUE))
    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(40, 40, 40)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jLabel6)
    .addComponent(jLabel2)
    .addComponent(jLabel4)
    .addComponent(jLabel5))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
    .addComponent(jTextField4)
    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))
    .addGap(28, 28, 28)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jLabel3)
    .addComponent(jLabel7))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
    .addComponent(jTextField6, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)))
    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(49, 49, 49))
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel1)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel2)
    .addComponent(jLabel3)
    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel4)
    .addComponent(jLabel7)
    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLabel5)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel6)
    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addContainerGap())
    jButton1.setText("Kaydet");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    jButton2.setText("Temizle");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    jButton3.setText("Çýk");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton3ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE)
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addComponent(jButton1)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton3)))
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(18, 18, 18)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jButton1)
    .addComponent(jButton2)
    .addComponent(jButton3))
    .addGap(38, 38, 38))
    pack();
    }// </editor-fold>
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    System.exit(0);
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    jTextField1.setText("");
    jTextField2.setText("");
    jTextField3.setText("");
    jTextField4.setText("");
    jTextField5.setText("");
    jTextField6.setText("");
    jTextArea1.setText("");
    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
    st.executeUpdate("INSERT studentdata(Ogrenci_no,Ad,Soyad,Sinif,Sube,Adres,Tel) VALUES(" +
    Integer.parseInt(jTextField1.getText()) + ", '" +
    jTextField2.getText() + "', '" +
    jTextField4.getText() + "', " +
    Integer.parseInt(jTextField3.getText()) + ", '" +
    jTextField6.getText() + "', '" +
    jTextArea1.getText() + "', " +
    Integer.parseInt(jTextField5.getText()) +
    } catch (SQLException e) {
    System.out.println("Writing data Error!");
    try {
    ResultSet rs = st.executeQuery("SELECT * FROM studentdata");
    while (rs.next()) {
    Object[] rowValues = {rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),rs.getString(6),rs.getInt(7)};
    row.addElement(rowValues);
    data = new Object[row.size()][7];
    for(int i=0;i<row.size();i++){
    data[i]=(Object[]) row.get(i);
    } catch (Exception e) {
    System.out.println("reading error!");
    jTable1.setModel(new MyTableModel());
    jTable1.setVisible(true);
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new DatabaseConnection().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    // End of variables declaration
    Connection con;
    Statement st;
    Vector row = new Vector();
    Object[][] data;
    Object[] heading = {"Öðrenci_No","Ad","Soyad","Sýnýf","Sube","Adres","Tel"};
    class MyTableModel extends AbstractTableModel{
    public int getColumnCount(){
    return heading.length;
    public int getRowCount(){
    return data.length;
    @Override
    public String getColumnName(int column){
    return heading[column].toString();
    public Object getValueAt(int row, int column){
    return data[row][column];
    public boolean isCellEditable(){
    return false;
    @Override
    public void setValueAt(Object value, int row, int column){
    data[row][column] = value;
    fireTableCellUpdated(row, column);
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    any one to help ?

  • Problem updating JTree via RMI

    I'm programming an Instant Messenger application in Java using RMI extensively. Much like most IM applications, my IM clients display a "buddy list" window upon successful authentication with the server. I have reached a huge stumbling block at this point. My Buddylist JFrame contains a JTree that is used to display the status of the user's buddies (i.e. online, offline). I am able to populate the JTree without any problems BEFORE the JFrame is displayed by using the DefaultTreeModel's insertNodeInto() method. But the problem I'm having is that, once the Buddylist is displayed to the user, I can't successfully update the JTree to reflect changing user status. For example, let's say a user with the screename "qwerty" logs in to the server. Now "qwerty" sees his Buddylist pop up on screen. His Buddylist contains 1 user (for simplicity's sake) with screename "foo". "foo" is currently not logged into the system so "foo" is shown in the Buddylist as a child of node Offline. But right now, let's say that "foo" logs into the system. "qwerty's" Buddylist should be updated to reflect the fact that "foo" just signed in by removing "foo" as a child node of Offline and adding a new node to Online called "foo".
    I currently have this functionality implemented as an RMI callback method on the server side. When "foo" logs in, the server calls the method fireBuddyLoggedOnEvent() with "foo" as the argument. Because "qwerty" is already logged in, and both users are each other's buddy, the statement
         c.getCallback().buddySignedOn(screenname);
    will be executed on the client side. Unfortunately, even though this code is successfully executed remotely, "qwerty's" Buddylist's JTree does not update to show that "foo" is now online. My only suspicion is that this is due to the fact that the Buddylist is already visible and this somehow affects its ability to be updated (remember that I have no problem populating the tree BEFORE it's visible). However, I've weeded out this possibility by creating a test frame in which its JTree is successfully updated, but in response to an ActionEvent in response to a button click. Of course, this test case was not an RMI application and does not come with the complexities of RMI. Please help me resolve this issue as it's preventing me from proceeding with my project.
    ~BTW, sorry for the poor code formatting. I added all the code in wordpad and pasted it in here, which stripped the formatting.
    * Frame that allows the user to enter information to
    * be used to login to the server.
    public class LoginFrame extends JFrame {
         signonButton.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent e) {
                   if (!screenameTextField.getText().equals("") &&
                   !passwordTextField.getPassword().equals("")) {
                        try {
                             serverInter = (ServerInter) Naming.lookup(serverName);
                             String username = screenameTextField.getText();
                             String password = String.valueOf(passwordTextField.getPassword());
                             int connectionID = serverInter.connect(username, password);
                             System.out.println("authenticate successful");
                             dispose();
                             Buddylist buddyList = new Buddylist(username, connectionID);
                             // Registers the buddylist with the server so that
                             // the server can remotely call methods on the
                             // Buddylist.
                             serverInter.registerCallback(buddyList, connectionID);
                             return;
                             } catch (Exception e1) {
                                  JOptionPane.showMessageDialog(LoginFrame.this, e1.getMessage(),
                                            "Connection Error", JOptionPane.ERROR_MESSAGE);
                                  passwordTextField.setText("");
                                  signonButton.setEnabled(false);
                                  e1.printStackTrace();
         public static void main(String[] args) {
              new LoginFrame();
    public class Buddylist extends JFrame implements BuddylistInter {
         public Buddylist(String username, int connectionID) {
              try {
                   serverInter = (ServerInter) Naming.lookup(serverName);
                   this.username = username;
                   this.connectionID = connectionID;
                   this.setTitle(username + "'s BuddyList");
                   initialize();
                   } catch (Exception e) {
                        e.printStackTrace();
         * Method of interest. Note that this method uses a DynamicTree
         * object as included in the Sun tutorial on JTree's
         * (located at http://www.iam.ubc.ca/guides/javatut99/uiswing/components/tree.html#dynamic).
         * Don't worry too much about where the node is getting added
         * but rather, that i wish to verify that an arbitrary node
         * can successfully be inserted into the tree during this
         * remote method call
         public void buddySignedOn(String screenname) throws RemoteException {
              // should add screename at some location in the tree
              // but doesn't!
              treePanel.addObject(screename);
    * Oversimplified interface for the Buddylist that is intended
    * to be used to allow callbacks to the clientside.
    public interface BuddylistInter extends Remote {
         public void buddySignedOn(String screenname) throws RemoteException;
    * Another oversimplified interface that is to be
    * implemented by the server so that the client can
    * call remote server methods.
    public interface ServerInter extends java.rmi.Remote {
         // "Registers" the given Buddylist with this server to allow
         // remote callbacks on the Buddylist.
         public void registerCallback(Buddylist buddylist, int connectionID)
                             throws RemoteException;
    public class Server extends UnicastRemoteObject implements ServerInter {
         private Vector loggedInUsers = new Vector();
         // Note that this method assumes that a Connection object
         // representing the Buddylist with connectionID was added
         // to the loggedInUsers list during authentication.
         public void registerCallback(Buddylist buddylist, int connectionID) throws RemoteException {          
              int index = loggedInUsers.indexOf(new Connection(connectionID));
              Connection c = (Connection) loggedInUsers.get(index);
              c.setCallback(buddylist);
         // Method that's called whenever a client successfully
         // connects to this server object.
         // screename is the name of the user that successfully
         // logged in.
         private void fireBuddyLoggedOnEvent(String screenname) {
              // Examines each logged in client to determine whether
              // or not that client should be notified of screename's
              // newly logged in status.
              for (int i = 0; i < loggedInUsers.size(); i++) {
                   Connection c = (Connection) loggedInUsers.get(i);
                   if (database1.areBuddies(screenname, c.getUsername())) {
                        try {
                             // getCallback() returns a reference to
                             // the Buddylist that was registered
                             // with this server. At this point,
                             // the server attempts to notify the
                             // client that one of his "buddies" has
                             // just logged into the server.
                             c.getCallback().buddySignedOn(screenname);
                        } catch (RemoteException e) {
                             e.printStackTrace();
    }

    Ok, I deleted all .class files, recomplied, and rmic'd, and I still get the IllegalArgumentException. So I've decided to just post all the code here because I don't want to make an assumption that all the code is correct. Thanks for helping me out with this very stressful problem.
    * Created on Nov 13, 2006
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.rmi.Naming;
    import java.rmi.NotBoundException;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JPanel;
    import javax.swing.JSeparator;
    import javax.swing.SwingUtilities;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Buddylist extends JFrame implements BuddylistInter {
         private String serverName = "//Broom:" + "5001" + "/IMServer";
         private DynamicTree treePanel = null;
         private String onlineString = "Online";
         private String offlineString = "Offline";
         private DefaultMutableTreeNode onlineNode = null;
         private DefaultMutableTreeNode offlineNode = null;
         private ImageUpdater imageUpdater = null;
         private javax.swing.JPanel jContentPane = null;
         private ServerInter serverInter = null;
         private String username = null;
         // A connectionID of -1 indicates that this Buddylist
         // has not yet received a valid id from the server.
         private int connectionID = -1;
         private JMenuBar jJMenuBar = null;
         private JMenu jMenu = null;
         private JMenu jMenu1 = null;
         private JMenu jMenu2 = null;
         private JPanel imagePanel = null;
         private JSeparator jSeparator1 = null;
         public Buddylist(String username, int connectionID) {
             try {
                   serverInter = (ServerInter) Naming.lookup(serverName);
                   this.username = username;
                   this.connectionID = connectionID;
                   this.setTitle(username + "'s BuddyList");
                   imageUpdater = new ImageChooser(this);
                   initialize();
                    * This statement is causing an IllegalArgumentException
                    * to be thrown! I've tried inserting it at the beginning
                    * of the constructor and that doesn't help.
                   UnicastRemoteObject.exportObject(this);
              } catch (MalformedURLException e) {
                   e.printStackTrace();
              } catch (RemoteException e) {
                   e.printStackTrace();
              } catch (NotBoundException e) {
                   e.printStackTrace();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              this.setJMenuBar(getJJMenuBar());
              this.setPreferredSize(new java.awt.Dimension(196,466));
              this.setMinimumSize(new java.awt.Dimension(150,439));
              this.setSize(196, 466);
              this.setContentPane(getJContentPane());
              this.setLocationRelativeTo(null);
              this.setVisible(true);
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getImagePanel(), null);
                   jContentPane.add(getJSeparator1(), null);
                   jContentPane.add(getTreePanel(), null);
              return jContentPane;
         private DynamicTree getTreePanel() {
              if (treePanel == null) {
                   treePanel = new DynamicTree();
                   onlineNode = treePanel.addObject(null, onlineString);
                   offlineNode = treePanel.addObject(null, offlineString);
                   treePanel.setBounds(6, 138, 177, 196);
                   populateTree();
                   return treePanel;
              return null;
         private void populateTree() {
              try {
                   String [] buddies = serverInter.getBuddyList(this.username);
                   for (int i = 0; i < buddies.length; i++) {
                        try {
                             if (serverInter.isBuddyOnline(buddies)) {
                                  treePanel.addObject(onlineNode, buddies[i]);
                             else {
                                  treePanel.addObject(offlineNode, buddies[i]);
                        } catch (RemoteException e1) {
                             e1.printStackTrace();
              } catch (RemoteException e) {
                   e.printStackTrace();
         * This method initializes jJMenuBar     
         * @return javax.swing.JMenuBar     
         private JMenuBar getJJMenuBar() {
              if (jJMenuBar == null) {
                   jJMenuBar = new JMenuBar();
                   jJMenuBar.add(getJMenu());
                   jJMenuBar.add(getJMenu1());
                   jJMenuBar.add(getJMenu2());
              return jJMenuBar;
         * This method initializes jMenu     
         * @return javax.swing.JMenu     
         private JMenu getJMenu() {
              if (jMenu == null) {
                   jMenu = new JMenu();
                   jMenu.setText("My IM");
              return jMenu;
         * This method initializes jMenu1     
         * @return javax.swing.JMenu     
         private JMenu getJMenu1() {
              if (jMenu1 == null) {
                   jMenu1 = new JMenu();
                   jMenu1.setText("People");
              return jMenu1;
         * This method initializes jMenu2     
         * @return javax.swing.JMenu     
         private JMenu getJMenu2() {
              if (jMenu2 == null) {
                   jMenu2 = new JMenu();
                   jMenu2.setText("Help");
              return jMenu2;
         * This method initializes imagePanel     
         * @return javax.swing.JPanel     
         private JPanel getImagePanel() {
              if (imagePanel == null) {
                   imagePanel = new JPanel();
                   imagePanel.setBounds(6, 2, 176, 125);
                   try {
                        BufferedImage bi =
                             ImageIO.read(
                                       getClass().getClassLoader().getResourceAsStream("images/cute_dog.jpg"));
                        Image scaled = bi.getScaledInstance(
                                  imagePanel.getWidth(), imagePanel.getHeight(), BufferedImage.SCALE_FAST);
                        final JLabel imageLabel = new JLabel(new ImageIcon(scaled));
                        imageLabel.setToolTipText("Double click to change image");
                        imagePanel.add(imageLabel, imageLabel.getName());
                        imageLabel.addMouseListener(new java.awt.event.MouseAdapter() {
                             public void mouseClicked(java.awt.event.MouseEvent e) {
                                  if (e.getClickCount() == 2) {
                                       Image selected = imageUpdater.getSelectedImage();
                                       if (selected != null) {
                                            BufferedImage bi = (BufferedImage) selected;
                                            Image scaled = bi.getScaledInstance(
                                                      imageLabel.getWidth(), imageLabel.getHeight(), BufferedImage.SCALE_DEFAULT);
                                            imageLabel.setIcon(new ImageIcon(scaled));
                   } catch (IOException e) {
                        e.printStackTrace();
              return imagePanel;
         * This method initializes jSeparator1     
         * @return javax.swing.JSeparator     
         private JSeparator getJSeparator1() {
              if (jSeparator1 == null) {
                   jSeparator1 = new JSeparator();
                   jSeparator1.setBounds(6, 132, 176, 1);
              return jSeparator1;
         public void buddySignedOn(String screenname) throws RemoteException {
              final String temp = screenname;
              Runnable addBuddy = new Runnable() {
                   public void run() {
                        treePanel.addObject(onlineNode, temp);
              SwingUtilities.invokeLater(addBuddy);
         public void buddySignedOff(String screenname) throws RemoteException {
              // TODO Auto-generated method stub
         public boolean equals(Object o) {
              Buddylist buddylist = (Buddylist) o;
              return connectionID == buddylist.connectionID;
         public int hashCode() {
              return connectionID;
    } // @jve:decl-index=0:visual-constraint="10,11"
    * Created on Nov 4, 2006
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    public interface BuddylistInter extends Remote {
         public void buddySignedOn(String screenname) throws RemoteException;
         public void buddySignedOff(String screenname) throws RemoteException;
    * Created on Oct 14, 2006
    * Models a single endpoint of a connection between machines.
    * @author Josh Feldman
    public class Connection {
         private String username;
         private final int connectionID;
         private Buddylist callback = null;
         public Connection(String username, int connectionID) {
              this.username = username;
              this.connectionID = connectionID;
         public Connection(int connectionID) {
              this.connectionID = connectionID;
         public String getUsername() {
              return username;
         public int getConnectionID() {
              return connectionID;
         public void setCallback(Buddylist buddylist) {
              this.callback = buddylist;
         public Buddylist getCallback() {
              return callback;
         public boolean equals(Object o) {     
              Connection otherConnection = (Connection) o;
              if (otherConnection.getConnectionID() == this.connectionID) {
                   return true;
              else {
                   return false;
         public int hashCode() {
              return connectionID;
    * Created on Nov 4, 2006
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.Serializable;
    import java.util.Properties;
    public class Database implements Serializable{
         private final String regex = ";";
         private Properties db = null;
         private String dbPath = "buddies.txt";
         public Database() throws IOException {
              db = new Properties();
              File buddiesFile = new File(dbPath);
              if (!buddiesFile.canRead()) {
                   throw new IOException("Can't read database!");
              try {
                   FileInputStream fis = new FileInputStream(buddiesFile);
                   db.load(fis);
                   System.out.println("database loaded from file");
              } catch (IOException e) {
                   e.printStackTrace();
                   System.err.println("Can't load the database! Exiting program...");
                   System.exit(0);
          * called when a user adds/deletes a user from the buddylist
         public void changeBuddyList() {
              //TODO
         public boolean doesUserExist(String username) {
              System.out.println(db.getProperty(username));
              return db.getProperty(username) != null;
         public String getPassword(String username) {
              String temp = db.getProperty(username);
              String [] split = temp.split(regex);
              if (split.length == 2)
                   return split[0];
              else {
                   return null;
         public String getBuddies(String username) {
              String temp = db.getProperty(username);
              if (temp == null)
                   return null;
              String [] split = temp.split(regex);
              if (split.length != 2)
                   return null;
              else {
                   return split[1];
          * Determines whether screename1 is a buddy of screename2
          * @return
         public boolean areBuddies(String screename1, String screename2) {
              String [] buddies = getUserBuddies(screename2);
              if (buddies == null) {
                   return false;
              else {
                   for (int i = 0; i < buddies.length; i++) {
                        if (buddies.equals(screename1)) {
                             return true;
              return false;
         public String [] getUserBuddies(String username) {
              System.out.println("in db getUserBuddies: username = " + username);
              String temp = db.getProperty(username);
              if (temp == null)
                   return null;
              String [] split = temp.split(regex);
              if (split.length != 2)
                   return null;
              else {
                   return split[1].split(",");
    import java.awt.GridLayout;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    // Note that this is not my code but rather code taken
    // from java Sun tutorial
    public class DynamicTree extends JPanel {
        protected DefaultMutableTreeNode rootNode;
        protected DefaultTreeModel treeModel;
        protected JTree tree;
        public DynamicTree() {
            rootNode = new DefaultMutableTreeNode("Root Node");
            treeModel = new DefaultTreeModel(rootNode);
            treeModel.addTreeModelListener(new MyTreeModelListener());
            tree = new JTree(treeModel);
            tree.setRootVisible(false);
            tree.setEditable(false);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(false);
            JScrollPane scrollPane = new JScrollPane(tree);
            setLayout(new GridLayout(1,0));
            add(scrollPane);
        /** Remove all nodes except the root node. */
        public void clear() {
            rootNode.removeAllChildren();
            treeModel.reload();
        /** Remove the currently selected node. */
        public void removeCurrentNode() {
            TreePath currentSelection = tree.getSelectionPath();
            if (currentSelection != null) {
                DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
                             (currentSelection.getLastPathComponent());
                MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
                if (parent != null) {
                    treeModel.removeNodeFromParent(currentNode);
                    return;
        public void removeObject(DefaultMutableTreeNode child) {
             treeModel.removeNodeFromParent(child);
    //         treeModel.reload();
        /** Add child to the currently selected node. */
        public DefaultMutableTreeNode addObject(Object child) {
            DefaultMutableTreeNode parentNode = null;
            TreePath parentPath = tree.getSelectionPath();
            if (parentPath == null) {
                parentNode = rootNode;
            } else {
                parentNode = (DefaultMutableTreeNode)
                             (parentPath.getLastPathComponent());
            return addObject(parentNode, child, true);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child) {
            return addObject(parent, child, false);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child,
                                                boolean shouldBeVisible) {
            DefaultMutableTreeNode childNode =
                    new DefaultMutableTreeNode(child);
            if (parent == null) {
                parent = rootNode;
            treeModel.insertNodeInto(childNode, parent,
                                     parent.getChildCount());
            // Make sure the user can see the lovely new node.
            if (shouldBeVisible) {
                tree.scrollPathToVisible(new TreePath(childNode.getPath()));
            return childNode;
        class MyTreeModelListener implements TreeModelListener {
            public void treeNodesChanged(TreeModelEvent e) {
                DefaultMutableTreeNode node;
                node = (DefaultMutableTreeNode)
                         (e.getTreePath().getLastPathComponent());
                 * If the event lists children, then the changed
                 * node is the child of the node we've already
                 * gotten.  Otherwise, the changed node and the
                 * specified node are the same.
                try {
                    int index = e.getChildIndices()[0];
                    node = (DefaultMutableTreeNode)
                           (node.getChildAt(index));
                } catch (NullPointerException exc) {}
                System.out.println("The user has finished editing the node.");
                System.out.println("New value: " + node.getUserObject());
            public void treeNodesInserted(TreeModelEvent e) {
            public void treeNodesRemoved(TreeModelEvent e) {
            public void treeStructureChanged(TreeModelEvent e) {
        public DefaultTreeModel getModel() {
             return treeModel;
    * Created on Sep 24, 2006
    import java.awt.Frame;
    import java.awt.Image;
    import javax.swing.JComponent;
    * Generic Dialog for allowing a user to browse
    * his filesystem for an image file. Dialog
    * displays a preview of the image (if it is in fact
    * displayable).
    * @author Josh Feldman
    public class ImageChooser extends JComponent implements ImageUpdater{
         private Frame parent = null;
         public ImageChooser(Frame parent) {
              super();
              this.parent = parent;
         public Image getSelectedImage() {
              ImageChooserDialog dialog = new ImageChooserDialog(parent);
              if (dialog.showDialog() == ImageChooserDialog.OK_OPTION) {
                   return dialog.getSelectedImage();
              return null;
    }  //  @jve:decl-index=0:visual-constraint="10,10"
    * Created on Sep 24, 2006
    import java.awt.Frame;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JDialog;
    import javax.swing.ImageIcon;
    import javax.swing.JFileChooser;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    * Class that displays a dialog that allows a user
    * to browse his/her filesystem for an image file
    * for selection.
    * @author Josh Feldman
    public class ImageChooserDialog extends JDialog {
         private Frame parent = null;
         private JFileChooser fileChooser = new JFileChooser();
         private int option;
         public final static int OK_OPTION = 1;
         public final static int CANCEL_OPTION = 2;
         private Image selectedImage = null;
         private javax.swing.JPanel jContentPane = null;
         private JPanel previewPanel = null;
         private JLabel jLabel = null;
         private JTextField filenameTextField = null;
         private JButton browseButton = null;
         private JButton cancelButton = null;
         private JButton okButton = null;
         private JLabel previewLabel = null;
          * This is the default constructor
         public ImageChooserDialog(Frame parent) {
              super();
              this.parent = parent;
              this.setTitle("Select Image");
              initialize();
         public ImageChooserDialog(Frame parent, String title) {
              super();
              this.parent = parent;
              this.setTitle(title);
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setModal(true);
              this.setSize(377, 246);
              this.setContentPane(getJContentPane());
              this.setVisible(false);
              this.setLocationRelativeTo(parent);
              this.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        selectedImage = null;
                        option = CANCEL_OPTION;
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   jLabel = new JLabel();
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   jLabel.setBounds(87, 192, 58, 10);
                   jLabel.setText("Preview");
                   jContentPane.add(getPreviewPanel(), null);
                   jContentPane.add(jLabel, null);
                   jContentPane.add(getFilenameTextField(), null);
                   jContentPane.add(getBrowseButton(), null);
                   jContentPane.add(getCancelButton(), null);
                   jContentPane.add(getOkButton(), null);
              return jContentPane;
          * This method initializes previewPanel     
          * @return javax.swing.JPanel     
         private JPanel getPreviewPanel() {
              if (previewPanel == null) {
                   previewPanel = new JPanel();
                   previewLabel = new JLabel();
                   previewPanel.setLayout(null);
                   previewPanel.setLocation(25, 62);
                   previewPanel.setSize(172, 125);
                   previewPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
                   previewLabel.setText("");
                   previewLabel.setLocation(2, 2);
                   previewLabel.setSize(172, 125);
                   previewPanel.add(previewLabel, null);
              return previewPanel;
          * This method initializes jTextField     
          * @return javax.swing.JTextField
         private JTextField getFilenameTextField() {
              if (filenameTextField == null) {
                   filenameTextField = new JTextField();
                   filenameTextField.setBounds(26, 17, 212, 23);
                   filenameTextField.setEditable(false);
              return filenameTextField;
          * This method initializes jButton     
          * @return javax.swing.JButton     
         private JButton getBrowseButton() {
              if (browseButton == null) {
                   browseButton = new JButton();
                   browseButton.setBounds(254, 18, 102, 21);
                   browseButton.setText("Browse");
                   browseButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) { 
                             ImageFilter imageFilter = new ImageFilter();
                             fileChooser.setFileFilter(imageFilter);
                             int value = fileChooser.showOpenDialog(ImageChooserDialog.this);
                             if (value == JFileChooser.APPROVE_OPTION) {
                                  File selected = fileChooser.getSelectedFile();
                                  if (selected.canRead()) {
                                       try {
                                            BufferedImage bi = ImageIO.read(selected);
                                            selectedImage = bi;
                                            Image scaled = bi.getScaledInstance(
                                                      previewPanel.getWidth(), previewPanel.getHeight(), BufferedImage.SCALE_FAST);
                                            ImageIcon imageIcon = new ImageIcon(scaled);
                                            previewLabel.setIcon(imageIcon);
                                            filenameTextField.setText(selected.getAbsolutePath());
                                       } catch (IOException e1) {
                                            previewLabel.setText("Preview unavailable...");
                                            selectedImage = null;
                                            e1.printStackTrace();
              return browseButton;
          * This method initializes jButton1     
          * @return javax.swing.JButton     
         private JButton getCancelButton() {
              if (cancelButton == null) {
                   cancelButton = new JButton();
                   cancelButton.setBounds(254, 122, 100, 24);
                   cancelButton.setText("Cancel");
                   cancelButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             selectedImage = null;
                             option = CANCEL_OPTION;
                             ImageChooserDialog.this.dispose();
              return cancelButton;
          * This method initializes jButton2     
          * @return javax.swing.JButton     
         private JButton getOkButton() {
              if (okButton == null) {
                   okButton = new JButton();
                   okButton.setBounds(256, 159, 97, 24);
                   okButton.setText("OK");
                   okButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             option = OK_OPTION;
                             ImageChooserDialog.this.dispose();
              return okButton;
          * Displays this chooser dialog.
          * @return - The user selected option
          *                (i.e. OK_OPTION, CANCEL_OPTION)
         public int showDialog() {
              this.setVisible(true);
              return option;
          * Returns the image chosen by the user.
          * @return
         public Image getSelectedImage() {
              return selectedImage;
    import java.io.File;
    import javax.swing.filechooser.FileFilter;
    public class ImageFilter extends FileFilter {
        //Accept all directories and all gif, jpg, tiff, or png files.
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            String extension = Utils.getExtension(f);
            if (extension != null) {
                if (extension.equals(Utils.tiff) ||
                    extension.equals(Utils.tif) ||
                    extension.equals(Utils.gif) ||
                    extension.equals(Utils.jpeg) ||
                    extension.equals(Utils.jpg) ||
                    extension.equals(Utils.png)) {
                        return true;
                } else {
                    return false;
            return false;
        //The description of this filter
        public String getDescription() {
            return "Just Images";
    * Created on Sep 24, 2006
    import java.awt.Image;
    * Contract that specifies how a class can update
    * the view in its graphical display.
    * @author Josh Feldman
    public interface ImageUpdater {
         public Image getSelectedImage();
    * Created on Nov 4, 2006
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.KeyEvent;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.rmi.Naming;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    public class LoginFrame extends JFrame {
         private String serverName = "//Broom:5001/IMServer";
         private ServerInter serverInter = null;
         // The icon to be used when this frame is minimized
         private Image icon;
         // The main image to be displayed on this frame
         private Image robotImage;
         private javax.swing.JPanel jContentPane = null;
         private JPanel imagePanel = null;
         private JLabel screenameLabel = null;
         private JTextField screenameTextField = null;
         private JPanel jPanel1 = null;
         private JLabel passwordLabel = null;
         private JPasswordField passwordTextField = null;
         private JButton signonButton = null;
         private JButton helpButton = null;
          * This is the default constructor
         public LoginFrame() {
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              this.setResizable(false);
              this.setSize(210, 368);
              this.setContentPane(getJContentPane());
              this.setTitle("Sign On");
              try {
                   this.setIconImage(ImageIO.read(new File("images/robby3.jpg")));
              } catch (IOException e) {
                   e.printStackTrace();
              this.setLocationRelativeTo(null);
              this.setVisible(true);
          * This method initializes jPanel     
          * @return javax.swing.JPanel     
         private JPanel getImagePanel() {
              if (imagePanel == null) {
                   imagePanel = new JPanel();
                   imagePanel.setBounds(7, 7, 190, 159);
                   imagePanel.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.gray,0));
                   try {
                        BufferedImage bi =
                             ImageIO.read(
                                       getClass().getClassLoader().getResourceAsStream("images/robby_big.bmp"));
                        Image scaled = bi.getScaledInstance(190, 169, BufferedImage.SCALE_FAST);
                        JLabel robotLabel = new JLabel(
                                  new ImageIcon(scaled));
                        imagePanel.add(robotLabel);
                   } catch (IOException e) {
                        e.printStackTrace();
              return imagePanel;
          * This method initializes jTextField     
          * @return javax.swing.JTextField     
         private JTextField getScreenameTextField() {
              if (screenameTextField == null) {
                   screenameTextField = new JTextField();
                   screenameTextField.setBounds(22, 208, 168, 20);
                   screenameTextField.addKeyListener(new java.awt.event.KeyAdapter() {  
                        public void keyTyped(java.awt.event.KeyEvent e) {
                             if (!isAllowedCharacter(e.getKeyChar())) {
                                  e.consume();
                                  Toolkit.getDefaultToolkit().beep();
                        public void keyPressed(java.awt.event.KeyEvent e) {
                             int keycode = e.getKeyCode();
                             if(keycode == KeyEvent.VK_ENTER && signonButton.isEnabled()) {
                                  signonButton.doClick();
                                  passwordTextField.setText("");
                             else if (keycode == KeyEvent.VK_ESCAPE) {
                                  dispose();
                                  System.exit(0);
                        public void keyReleased(java.awt.event.KeyEvent e) {
                             String screename = screenameTextField.getText();
                             char [] password = passwordTextField.getPassword();
                             if (screename.equals("") ||
                                       password.length <= 0) {
                                  signonButton.setEnabled(false);
                             else if (!screename.equals("") &&
                                       password.length > 0) {
                                  signonButton.setEnabled(true);
                             clearPasswordArray(password);
              return screenameTextField;
          * This method initializes jPanel1     
          * @return javax.swing.JPanel     
         private JPanel getJPanel1() {
              if (jPanel1 == null) {
                   jPanel1 = new JPanel();
                   jPanel1.setBounds(8, 173, 188, 1);
                   jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.gray,5));
              return jPanel1;
          * This method initializes jPasswordField     
          * @return javax.swing.JPasswordField     
         private JPasswordField getPasswordTextField() {
              if (passwordTextField == null) {
                   passwordTextField = new JPasswordField();
                   passwordTextField.setBounds(20, 259, 170, 20);
                   passwordTextField.addKeyListener(new java.awt.event.KeyAdapter() {
                        public void keyTyped(java.awt.event.KeyEvent e) {
                             if (!isAllowedCharacter(e.getKeyChar())) {
                                  e.consume();
                                  Toolkit.getDefaultToolkit().beep();
                        public void keyPressed(java.awt.event.KeyEvent e) {
                             int keycode = e.getKeyCode();
                             if(keycode == KeyEvent.VK_ENTER && signonButton.isEnabled()) {
                                  signonButton.doClick();
                                  passwordTextField.setText("");
                             else if (keycode == KeyEvent.VK_ESCAPE) {
                                  dispose();
                                  System.exit(0);
                        public void keyReleased(java.awt.event.KeyEvent e) {
                             String screename = screenameTextField.getText();
                             char [] password = passwordTextField.getPassword();
                             if (screename.equals("") ||
                                       password.length <= 0) {
                                  signonButton.setEnabled(false);
                             else if (!screename.equals("") &&
                                       password.length > 0) {
                                  signonButton.setEnabled(true);
                             clearPasswordArray(password);
              return passwordTextField;
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   passwordLabel = new JLabel();
                   screenameLabel = new JLabel();
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   screenameLabel.setBounds(22, 182, 132, 20);
                   screenameLabel.setText("Screename");
                   screenameLabel.setEnabled(true);
                   screenameLabel.setFont(new java.awt.Font("Century Gothic", java.awt.Font.BOLD, 12));
                   passwordLabel.setBounds(21, 238, 135, 17);
                   passwordLabel.setText("Password");
                   jContentPane.add(getImagePanel(), null);
                   jContentPane.add(screenameLabel, null);
                   jContentPane.add(getScreenameTextField(), null);
                   jContentPane.add(getJPanel1(), null);
                   jCon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

  • Disabling selection of JSeparator in a JComboBox

    Does anyone know how to disable the selection of a JSeparator in a JComboBox?
    I'm using JRE 1.1.8.

    The BlockComboBox example doesn't allow the selection of the separator, however there is no way to move past the separator by using the arrow keys of the keyboard.
    I've tried to add a key listener, but for some reason the code never gets executed when hitting a key.
    Is there a problem with using key listeners with a JComboBox?

  • Problem in updating jtextarea

    My requirement is, client has to sent string messages and server has to receive these messages and display it in jtextarea. In my code sending and receiving are done properly, but the problem is the jtextarea is not updated, it goes blank.
    I have attached the client and server files, can anyone solve my problem?
    Thanks in advance.
    //server file
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MessageCenter extends javax.swing.JFrame {
        public MessageCenter() {
            initComponents();
        private void initComponents() {
            jLabel1 = new JLabel();
            jScrollPane1 = new JScrollPane();
            jTextArea1 = new JTextArea();
            jPanel1 = new JPanel();
            jLabel5 = new JLabel();
            jLabel3 = new JLabel();
            jButton1 = new JButton();
            jButton2 = new JButton();
            jLabel2 = new JLabel();
            jLabel4 = new JLabel();
            menuBar = new JMenuBar();
            fileMenu = new JMenu();
            Start = new JMenuItem();
            jSeparator1 = new JSeparator();
            Stop = new JMenuItem();
            jSeparator2 = new JSeparator();
            Exit = new JMenuItem();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Message Center");
            setMaximizedBounds(new java.awt.Rectangle(0, 0, 560, 700));
            setBounds(0,0,600,700);
            setName("");
            jLabel1.setBackground(new java.awt.Color(255, 255, 255));
            jLabel1.setFont(new java.awt.Font("Georgia", 1, 24));
            jLabel1.setForeground(new java.awt.Color(34, 44, 106));
            jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
            jLabel1.setText("Message Center");
            jLabel1.setIconTextGap(0);
            getContentPane().add(jLabel1, java.awt.BorderLayout.NORTH);
            jTextArea1.setColumns(20);
            jTextArea1.setFont(new java.awt.Font("Book Antiqua", 0, 12));
            jTextArea1.setLineWrap(true);
            jTextArea1.setRows(25);
            jTextArea1.setBorder(null);
            jScrollPane1.setViewportView(jTextArea1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            jPanel1.setLayout(new java.awt.GridLayout(1, 6, 10, 5));
            jPanel1.add(jLabel5);
            jPanel1.add(jLabel3);
            jButton1.setText("Start");
            jPanel1.add(jButton1);
            jButton2.setText("Stop");
            jPanel1.add(jButton2);
            jPanel1.add(jLabel2);
            jPanel1.add(jLabel4);
            getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
            fileMenu.setText("File");
            Start.setText("Start");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    System.out.println("hello");
                    StartActionPerformed(evt);
            fileMenu.add(Start);
            fileMenu.add(jSeparator1);
            Stop.setText("Stop");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    StopActionPerformed(evt);
            fileMenu.add(Stop);
            fileMenu.add(jSeparator2);
            Exit.setText("Exit");
            fileMenu.add(Exit);
            menuBar.add(fileMenu);
            setJMenuBar(menuBar);
            pack();
    private void StartActionPerformed(java.awt.event.ActionEvent evt)  {
              try{
                        Server t=new Server(jTextArea1);
                        t.listenSocket();
              catch(Exception e)
              e.printStackTrace();
        private void StopActionPerformed(java.awt.event.ActionEvent evt) {
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MessageCenter().setVisible(true);
        private JMenuItem Exit;
        private JMenuItem Start;
        private JMenuItem Stop;
        private JMenu fileMenu;
        private JButton jButton1;
        private JButton jButton2;
        private JLabel jLabel1;
        private JLabel jLabel2;
        private JLabel jLabel3;
        private JLabel jLabel4;
        private JLabel jLabel5;
        private JPanel jPanel1;
        private JScrollPane jScrollPane1;
        private JSeparator jSeparator1;
        private JSeparator jSeparator2;
        public JTextArea jTextArea1;
        private JMenuBar menuBar;
    class ClientThread implements Runnable {
      private Socket client;
      JTextArea jt;
      ClientThread(Socket client,JTextArea jt) {
       this.client = client;
       this.jt=jt;
      public void run(){
        try{
               //DataInputStream dis= new DataInputStream(client.getInputStream());
                DataInputStream dis= new DataInputStream(new BufferedInputStream(client.getInputStream()));
               System.out.println("client connected");
               //BufferedReader dis = new BufferedReader(new InputStreamReader(s.getInputStream()));
                   String msg=null;
                   byte msg1[]=new byte[200];
                while(true)
                   try{
                   if(dis.available()>0)
                   dis.readFully(msg1,0,dis.available());
                 //  System.out.println("Msg is ==> "+new String(msg1));
                   new PrinterThread(jt,new String(msg1)).start();
                   msg1=new byte[200];
                   Thread.sleep(1000);
                      }catch (Exception e) {
                         System.out.println("Exception  ");
             } catch (IOException e) {
                         System.out.println("Exception occurred");
    class Server {
              JTextArea jt;
              public Server(JTextArea jt)
                   this.jt=jt;
              public void listenSocket() throws Exception
              ServerSocket ss=null;
              try{
              ss=new ServerSocket(8000);
              System.out.println("Server started");
             catch (IOException e) {
                         System.out.println("Exception");
                         System.exit(-1);
             while(true){
               ClientThread w;
               try{
            w = new ClientThread(ss.accept(),jt);
            Thread t = new Thread(w);
            t.start();
                catch (IOException e) {
            System.out.println("Accept failed: 8000");
           public static void main(String args[])throws Exception {
              /*Server t=new Server();
              t.listenSocket();*/
         class PrinterThread extends Thread
                public PrinterThread(JTextArea jt1,String msg)
                 jTextArea1 = jt1;
                 this.msg=msg;
                 System.out.println("PrinterThread constructor ");
                public void run()
                 try
                    Date today;
                    SimpleDateFormat formatter;
                    String output;
                     String pattern="dd.MM.yyyy '@' H:mm";
                    formatter = new SimpleDateFormat(pattern);
                    today = new Date();
                    output = formatter.format(today);
                        System.out.println(" "+output+"  "+msg+" \n");
                          jTextArea1.append(" "+output+"  "+msg+" \n");
                          jTextArea1.updateUI();
                             jTextArea1.revalidate();
    //                      JOptionPane.showMessageDialog(null,"hi");
                          //System.out.println("Get text "+jTextArea1.getText());
                 catch (Exception exception) {}
                private JComboBox combo;
                private JTextArea jTextArea1;
                String msg=null;
    //client.java
    import java.net.*;
    import java.io.*;
    import java.io.File;
    public class client {
           public static void main(String args[]) {
                   try {
                           Socket ss=new Socket(InetAddress.getLocalHost(),8000);
                           DataOutputStream dos=new DataOutputStream(ss.getOutputStream());
                           for(int i=1;i<100;i++){
                              if((i%2)==0)
                            dos.writeBytes("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,3233");
                              else
                            dos.writeBytes("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42");
                           Thread.sleep(5000);
                   catch(Exception e) {
                   e.printStackTrace();
                   System.out.println(" ");
    }

    You need to run your Server in a separate Thread.
    Right now its running in the GUI Event Thread.I created new thread for my server, now it's updating jtextarea.
    Thank you very much.

  • Problems with sound convertion example

    Hi
    Below is my code for a soundconverter (or atleast the beginning of one). By now i have only gotten to the sound convertion example in the java tutorials.
    I keep getting this error:
    Error: failure attempting to read /home/carsten/Desktop/1-welcome.wav!
    I have given the file a chmod 777 permission.
    im on linux, but i guess that shouldnt matter.
    Hope you can help me out
    the problems are in the convertFile method
    Thanks
    Carsten
    * SoundConverterGUI.java
    * Created on 23. april 2007, 13:05
    package soundconverter;
    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.AudioFileFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.UnsupportedAudioFileException;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileNameExtensionFilter;
    * @author  carsten
    public class SoundConverterGUI extends javax.swing.JFrame {
        /** Creates new form SoundConverterGUI */
        public SoundConverterGUI() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            loadFileBtn = new javax.swing.JButton();
            loadFileLabel = new javax.swing.JLabel();
            loadFileField = new javax.swing.JTextField();
            fileFormatLabel = new javax.swing.JLabel();
            fileFormatCombo = new javax.swing.JComboBox();
            convertBtn = new javax.swing.JButton();
            seperator = new javax.swing.JSeparator();
            jSeparator1 = new javax.swing.JSeparator();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setResizable(false);
            loadFileBtn.setText("Browse");
            loadFileBtn.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    chooseFile(evt);
            loadFileLabel.setText("File to convert:");
            fileFormatLabel.setText("File format to convert to:");
            fileFormatCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "AIFF" }));
            convertBtn.setText("Convert");
            convertBtn.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    convertFile(evt);
            jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(loadFileLabel)
                                .addComponent(seperator, javax.swing.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(loadFileField, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                            .addComponent(fileFormatCombo, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(fileFormatLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 343, Short.MAX_VALUE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(convertBtn, 0, 0, Short.MAX_VALUE)
                                        .addComponent(loadFileBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(310, 310, 310)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 11, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(loadFileLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(loadFileField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(loadFileBtn))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(fileFormatLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(fileFormatCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(convertBtn))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(seperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        private void convertFile(java.awt.event.ActionEvent evt) {                            
            //The format to be converted from
            AudioFileFormat inFileFormat;
            try {
                outFile = new File(inFile.getParent()+"/"+
                        inFile.getName().substring(0, inFile.getName().lastIndexOf("."))+"."+
                        fileFormatCombo.getSelectedItem());
                System.out.println(outFile);
            } catch (NullPointerException ex) {
                System.out.println("Error: one of the parameters is null!");
                return;
            try {
                // query file type
                inFileFormat = AudioSystem.getAudioFileFormat(inFile);
                System.out.println(AudioSystem.getAudioFileFormat(inFile));
                if (inFileFormat.getType() != AudioFileFormat.Type.AIFF) {
                    // inFile is not AIFF, so let's try to convert it.
                    AudioInputStream inFileAIS =
                            AudioSystem.getAudioInputStream(inFile);
                    inFileAIS.reset(); // rewind
                    if (AudioSystem.isFileTypeSupported(
                            AudioFileFormat.Type.AIFF, inFileAIS)) {
                        // inFileAIS can be converted to AIFF.
                        // so write the AudioInputStream to the
                        // output file.
                        AudioSystem.write(inFileAIS,
                                AudioFileFormat.Type.AIFF, outFile);
                        System.out.println("Successfully made AIFF file, "
                                + outFile.getPath() + ", from "
                                + inFileFormat.getType() + " file, " +
                                inFile.getPath() + ".");
                        inFileAIS.close();
                        return; // All done now
                    } else
                        System.out.println("Warning: AIFF conversion of "
                                + inFile.getPath()
                                + " is not currently supported by AudioSystem.");
                } else
                    System.out.println("Input file " + inFile.getPath() +
                            " is AIFF." + " Conversion is unnecessary.");
            } catch (UnsupportedAudioFileException e) {
                System.out.println("Error: " + inFile.getPath()
                + " is not a supported audio file type!");
                return;
            } catch (IOException e) {
                System.out.println("Error: failure attempting to read "
                        + inFile.getPath() + "!");
                return;
        private void chooseFile(java.awt.event.ActionEvent evt) {                           
            //Melder fejl hvis man fortryder
            //Lav en check om man har valgt en fil
            FileNameExtensionFilter fileFilter = new FileNameExtensionFilter(
                    "Allowed file formats", "wav");
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(fileFilter);
            int returnVal = fileChooser.showOpenDialog(this);
            inFile = fileChooser.getSelectedFile();
            loadFileField.setText(inFile.getName());
        // Variables declaration - do not modify                    
        private javax.swing.JButton convertBtn;
        private javax.swing.JComboBox fileFormatCombo;
        private javax.swing.JLabel fileFormatLabel;
        private javax.swing.JSeparator jSeparator1;
        private javax.swing.JButton loadFileBtn;
        private javax.swing.JTextField loadFileField;
        private javax.swing.JLabel loadFileLabel;
        private javax.swing.JSeparator seperator;
        // End of variables declaration                  
        //Fields
        private File inFile;
        private File outFile;
    }

    In case looking it up didn't help you as much:
    catch(Exception ex) {
      ex.printStackTrace();
    }is lots better than printing some message. It's like going to the doctor and telling him "body part xyz hurts with a stinging pain whenever I do the following..." instead of saying "Doc, there's something wrong".

  • Problem in repainting jtextarea

    My requirement is, client has to sent string messages and server has to receive these messages and display it in jtextarea. In my code sending and receiving are done properly, but the problem is the jtextarea is not updated, it goes blank.
    I have attached the client and server files, can anyone solve my problem?
    Thanks in advance.
    //server file
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MessageCenter extends javax.swing.JFrame {
        public MessageCenter() {
            initComponents();
        private void initComponents() {
            jLabel1 = new JLabel();
            jScrollPane1 = new JScrollPane();
            jTextArea1 = new JTextArea();
            jPanel1 = new JPanel();
            jLabel5 = new JLabel();
            jLabel3 = new JLabel();
            jButton1 = new JButton();
            jButton2 = new JButton();
            jLabel2 = new JLabel();
            jLabel4 = new JLabel();
            menuBar = new JMenuBar();
            fileMenu = new JMenu();
            Start = new JMenuItem();
            jSeparator1 = new JSeparator();
            Stop = new JMenuItem();
            jSeparator2 = new JSeparator();
            Exit = new JMenuItem();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Message Center");
            setMaximizedBounds(new java.awt.Rectangle(0, 0, 560, 700));
            setBounds(0,0,600,700);
            setName("");
            jLabel1.setBackground(new java.awt.Color(255, 255, 255));
            jLabel1.setFont(new java.awt.Font("Georgia", 1, 24));
            jLabel1.setForeground(new java.awt.Color(34, 44, 106));
            jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
            jLabel1.setText("Message Center");
            jLabel1.setIconTextGap(0);
            getContentPane().add(jLabel1, java.awt.BorderLayout.NORTH);
            jTextArea1.setColumns(20);
            jTextArea1.setFont(new java.awt.Font("Book Antiqua", 0, 12));
            jTextArea1.setLineWrap(true);
            jTextArea1.setRows(25);
            jTextArea1.setBorder(null);
            jScrollPane1.setViewportView(jTextArea1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            jPanel1.setLayout(new java.awt.GridLayout(1, 6, 10, 5));
            jPanel1.add(jLabel5);
            jPanel1.add(jLabel3);
            jButton1.setText("Start");
            jPanel1.add(jButton1);
            jButton2.setText("Stop");
            jPanel1.add(jButton2);
            jPanel1.add(jLabel2);
            jPanel1.add(jLabel4);
            getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
            fileMenu.setText("File");
            Start.setText("Start");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    System.out.println("hello");
                    StartActionPerformed(evt);
            fileMenu.add(Start);
            fileMenu.add(jSeparator1);
            Stop.setText("Stop");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    StopActionPerformed(evt);
            fileMenu.add(Stop);
            fileMenu.add(jSeparator2);
            Exit.setText("Exit");
            fileMenu.add(Exit);
            menuBar.add(fileMenu);
            setJMenuBar(menuBar);
            pack();
    private void StartActionPerformed(java.awt.event.ActionEvent evt)  {
              try{
                        Server t=new Server(jTextArea1);
                        t.listenSocket();
              catch(Exception e)
              e.printStackTrace();
        private void StopActionPerformed(java.awt.event.ActionEvent evt) {
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MessageCenter().setVisible(true);
        private JMenuItem Exit;
        private JMenuItem Start;
        private JMenuItem Stop;
        private JMenu fileMenu;
        private JButton jButton1;
        private JButton jButton2;
        private JLabel jLabel1;
        private JLabel jLabel2;
        private JLabel jLabel3;
        private JLabel jLabel4;
        private JLabel jLabel5;
        private JPanel jPanel1;
        private JScrollPane jScrollPane1;
        private JSeparator jSeparator1;
        private JSeparator jSeparator2;
        public JTextArea jTextArea1;
        private JMenuBar menuBar;
    class ClientThread implements Runnable {
      private Socket client;
      JTextArea jt;
      ClientThread(Socket client,JTextArea jt) {
       this.client = client;
       this.jt=jt;
      public void run(){
        try{
               //DataInputStream dis= new DataInputStream(client.getInputStream());
                DataInputStream dis= new DataInputStream(new BufferedInputStream(client.getInputStream()));
               System.out.println("client connected");
               //BufferedReader dis = new BufferedReader(new InputStreamReader(s.getInputStream()));
                   String msg=null;
                   byte msg1[]=new byte[200];
                while(true)
                   try{
                   if(dis.available()>0)
                   dis.readFully(msg1,0,dis.available());
                 //  System.out.println("Msg is ==> "+new String(msg1));
                   new PrinterThread(jt,new String(msg1)).start();
                   msg1=new byte[200];
                   Thread.sleep(1000);
                      }catch (Exception e) {
                         System.out.println("Exception  ");
             } catch (IOException e) {
                         System.out.println("Exception occurred");
    class Server {
              JTextArea jt;
              public Server(JTextArea jt)
                   this.jt=jt;
              public void listenSocket() throws Exception
              ServerSocket ss=null;
              try{
              ss=new ServerSocket(8000);
              System.out.println("Server started");
             catch (IOException e) {
                         System.out.println("Exception");
                         System.exit(-1);
             while(true){
               ClientThread w;
               try{
            w = new ClientThread(ss.accept(),jt);
            Thread t = new Thread(w);
            t.start();
                catch (IOException e) {
            System.out.println("Accept failed: 8000");
           public static void main(String args[])throws Exception {
              /*Server t=new Server();
              t.listenSocket();*/
         class PrinterThread extends Thread
                public PrinterThread(JTextArea jt1,String msg)
                 jTextArea1 = jt1;
                 this.msg=msg;
                 System.out.println("PrinterThread constructor ");
                public void run()
                 try
                    Date today;
                    SimpleDateFormat formatter;
                    String output;
                     String pattern="dd.MM.yyyy '@' H:mm";
                    formatter = new SimpleDateFormat(pattern);
                    today = new Date();
                    output = formatter.format(today);
                        System.out.println(" "+output+"  "+msg+" \n");
                          jTextArea1.append(" "+output+"  "+msg+" \n");
                          jTextArea1.updateUI();
                             jTextArea1.revalidate();
    //                      JOptionPane.showMessageDialog(null,"hi");
                          //System.out.println("Get text "+jTextArea1.getText());
                 catch (Exception exception) {}
                private JComboBox combo;
                private JTextArea jTextArea1;
                String msg=null;
    //client.java
    import java.net.*;
    import java.io.*;
    import java.io.File;
    public class client {
           public static void main(String args[]) {
                   try {
                           Socket ss=new Socket(InetAddress.getLocalHost(),8000);
                           DataOutputStream dos=new DataOutputStream(ss.getOutputStream());
                           for(int i=1;i<100;i++){
                              if((i%2)==0)
                            dos.writeBytes("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,3233");
                              else
                            dos.writeBytes("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42");
                           Thread.sleep(5000);
                   catch(Exception e) {
                   e.printStackTrace();
                   System.out.println(" ");
    }

    You need to run your Server in a separate Thread.
    Right now its running in the GUI Event Thread.I created new thread for my server, now it's updating jtextarea.
    Thank you very much.

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • J2ME problem with threads

    Hi all,
    I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
    Below you can find the code
    import java.lang.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class intervals extends MIDlet implements CommandListener
    public Display ekran;
    private SweepCanvas sweeper;
    private Form rundy;
    private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
    private long czas,x;
    private Command exitCommand;
    private Command addRound;
    private Command delRound;
    private Command start;
    private TextField repeat;
    private Form odliczanie;
    private Alert ostrz;
    Licznik thread;
    String test;
    StringItem test1;
    int parz,i,j,k;
    static int l;
    int ilrund;
    int ilpowt;
    Item sec;
    long sec1;
    public intervals()
        rundy = new Form("Interwa&#322;y sportowe");
        exitCommand = new Command("Wyj&#347;cie", Command.EXIT, 2);
        addRound = new Command("Dodaj","Dodaj rund&#281;", Command.ITEM,1);
        delRound = new Command("Usu&#324;","Usu&#324; ostatni&#261; rund&#281;", Command.ITEM,1);
        start = new Command("Start", Command.ITEM,1);
        odliczanie = new Form("Odliczanie");
        TextField dodaj(TextField kolej)
            kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
            if(rundy.size()==0)
                rundy.insert(rundy.size(),kolej);
                else
                    rundy.insert(rundy.size()-1, kolej);
            return kolej;
        void odliczanie(TextField round)
            monitor m=new monitor();
            k=Integer.parseInt(round.getString());
            ekran.setCurrent(odliczanie);
            thread=new Licznik(k,odliczanie);
            thread.start();
            ekran.setCurrent(rundy);
    public void startApp()// throws MIDletStateChangeException
        rundy.deleteAll();
        repeat = new TextField("Podaj ilo&#347;&#263; powtórze&#324;",null,1,TextField.NUMERIC);
        rundy.addCommand(addRound);
        rundy.addCommand(exitCommand);
        rundy.setCommandListener(this);
        Canvas obrazek = new MyCanvas();
        ekran = Display.getDisplay(this);
        ekran.setCurrent(obrazek);
        czas=System.currentTimeMillis();
        while (System.currentTimeMillis()<czas+1000)
            continue;
        ekran.setCurrent(rundy);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
        notifyDestroyed();
    public void commandAction(Command c, Displayable s)
        if (c == exitCommand)
            destroyApp(false);
            notifyDestroyed();
        else if(c==addRound)
            if(rundy.size()==0)//Sprawdzenie ilo&#347;ci elementów w celu poprawnego wy&#347;wietlania liczby rund w formie
                parz=1;
                else
                parz=rundy.size();
            switch(parz)
                case 1:
                    round0=dodaj(round0);break;
                case 2:
                    round1=dodaj(round1);break;
                case 3:
                   round2= dodaj(round2);break;
                case 4:
                    round3=dodaj(round3);break;
                case 5:
                    round4=dodaj(round4);break;
                default:
                    ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
                    ostrz.setTimeout(3000);
                    ekran.setCurrent(ostrz);
            if(rundy.size()==1)
                rundy.append(repeat);
                rundy.addCommand(start);
            rundy.addCommand(delRound);
        else if(c==delRound)
            if(rundy.size()!=0)
                rundy.delete(rundy.size()-2);
                if (rundy.size()==1)
                    rundy.deleteAll();
                if(rundy.size()==0)
                    rundy.removeCommand(delRound);
                    rundy.removeCommand(start);
        else if(c==start)
            ilrund=rundy.size()-1;
            if(this.repeat.size()>0)
                ilpowt=Integer.parseInt(this.repeat.getString());
            ekran = Display.getDisplay(this);
            for (i=1; i<=ilpowt;i++)
                odliczanie= new Form("Odliczanie");
                 for (j=0;j<ilrund;j++)
                    switch(j)
                         case 0:
                             odliczanie(round0);
                             break;
                         case 1:
                             odliczanie(round1);
                             break;
                         case 2:
                             odliczanie(round2);
                             break;
                         case 3:
                             odliczanie(round3);
                             break;
                         case 4:
                             odliczanie(round4);
                             break;
                         case 5:
                             odliczanie(round5);
                             break;
                         case 6:
                             odliczanie(round6);
                             break;
                         case 7:
                             odliczanie(round7);
                             break;
                         case 8:
                             odliczanie(round8);
                             break;
    class Licznik extends Thread
        int czas1,k;
        Form forma;
        monitor m;
        public Licznik(int k,Form formap)
            czas1=k;
            forma=formap;
        public synchronized void run()
            while(czas1>0)
                forma.deleteAll();
                forma.append("Czas pozosta&#322;y (s): "+czas1);
                try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
                czas1--;
            if(czas1<=0)
                m.put();
        }and monitor class
    public class monitor
    boolean busy=false;
    synchronized void get()
        if(!busy)
            try
                wait();
            }catch(InterruptedException e){e.printStackTrace();}
        notify();
    synchronized void put()
        if(busy)
            try
            wait();
            }catch(InterruptedException e){e.printStackTrace();}
        busy=true;
        notify();
    }Can anybody help me with this?

    Groovemaker,
    Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
    If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
    Daniel

  • Problem with threads within applet

    Hello,
    I got an applet, inside this applet I have a singleton, inside this singleton I have a thread.
    this thread is running in endless loop.
    he is doing something and go to sleep on and on.
    the problem is,
    when I refresh my IE6 browser I see more than 1 thread.
    for debug matter, I did the following things:
    inside the thread, sysout every time he goes to sleep.
    sysout in the singleton constructor.
    sysout in the singleton destructor.
    the output goes like this:
    when refresh the page, the singleton constructor loading but not every refresh, sometimes I see the constructor output and sometimes I dont.
    The thread inside the singleton is giving me the same output, sometime I see more than one thread at a time and sometimes I dont.
    The destructor never works (no output there).
    I don't understand what is going on.
    someone can please shed some light?
    thanks.
    btw. I am working with JRE 1.1
    this is very old and big applet and I can't convert it to something new.

    Ooops. sorry!
    I did.
         public void start() {
         public void stop() {
         public void destroy() {
              try {
                   resetAll();
                   Configuration.closeConnection();
                   QuoteItem.closeConnection();
              } finally {
                   try {
                        super.finalize();
                   } catch (Throwable e) {
                        e.printStackTrace();
         }

Maybe you are looking for

  • Mail problems after upgrading to Leopard 10.5.6

    To day I upgraded my daughter's MacBook to Leopard 10.5.6 (from about 10.3 ?) During the install the only problem was at the very end, the configuration wizard failed to make connection with the internet because Airport had lost the password for my w

  • How to connect Apple TV (2g) HDMI to HDTV with only component video input.

    Trying to connect Apple TV (2g) HDMI to HDTV with only component video input.  Can I use a simple cable or do I need a converter box/plug? Is the HDMI signal coming from ATV encrypted or HDCP enabled? The TV is HD, but only has a component input and

  • Problem with Photoshop CS6 Extended upgrade

    I have been using CS6 on both my desktop MacPro and my laptop Macbbok Pro. In the last few days, whenever I open photoshop on my desktop, it is the EXTENDED version and indicates that I am in a trial period for the next 30 days. I never purchased or

  • How to switch from Trial version of CC apps to Full version purchased for me.

    I recently joined a new company.  First day on the job, I downloaded trial versions of InDesign, Illustrator and Photoshop only to find out that the company had purchased a subscription for Creative Cloud for me. How do I get off the trial versions a

  • Is the Intel i5 considered an old processor

    Hi, I'm ready to buy an iMac with a Quad-Core Intel Core i5 (I don't go with the i7 because I'm in short budget) but I was wondering if this processor is already old and somehow will be replaced soon.  The reason for this question is because I don't