2013-08-11 11 views
4

У меня есть два класса: сначала мой основной класс и второй класс в моем классе рамки редактирования.Инициализировать переменную с помощью конструктора

public class RecordTableGUI extends JFrame implements ActionListener { 
    String newName; 
    public RecordTableGUI(String newReceivedName) { 
     newName = newReceivedName; 
     System.out.println("new name in new constructor : " + newName); //prints new name correctly 
    } 
    public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == editButton) { 
      Object oldName = table.getValueAt(table.getSelectedRow(), 1); 
      System.out.println("old name: " + oldName); // prints old name correctly 

      this.setVisible(false); 
      new UpdateGUI(String.valueOf(oldName)); 
      System.out.println("new name in problem area: " + newName); // why null? 
     } 
    } 
} 

Мой второй класс (UpdateGUI) дает Старое_имя в это конструктор и после редактирования его, когда я нажимаю на okButton, это отправить NEWNAME к моему первому классу.

Мой второй класс:

public class UpdateGUI extends JFrame implements ActionListener { 
String oldName, newName; 
    public UpdateGUI(String oldname) { 
    oldName = oldname; 
.... 
} 
public void actionPerformed(ActionEvent e) { 
    if (e.getSource() == okButton) { 
    newName = tf.getText();  //tf is JTextfield 
    new RecordTableGUI(newName); 
    this.setVisible(false); 
    } 
} 

Моя проблема заключается в том, что почему NEWNAME равна нулю?

Update:

public class RecordTableGUI extends JFrame implements ActionListener { 
    public RecordTableGUI(String newReceivedName) { 
    setNewName(newReceivedName); 
} 
     public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == editButton) { 
      Object oldName = table.getValueAt(table.getSelectedRow(), 1); 
     System.out.println("old name: " + oldName); 

     RecordTableGUI recordObject = new RecordTableGUI(); 
     UpdateGUIDialog updDialog = new UpdateGUIDialog(String.valueOf(oldName), recordObject); 
     } 

    } 

UpdateGUIDialog Класс:

public class UpdateGUIDialog extends JDialog implements ActionListener { 
    RecordTableGUI recordtablegui; 
    public UpdateGUIDialog(String old, RecordTableGUI recordGUI) { 
    oldName = old; 
    recordtablegui = recordGUI; 
} 
    @Override 
public void actionPerformed(ActionEvent e) { 
    if (e.getSource() == okButton) { 
    newName = tf.getText(); 
    recordtablegui.setNewName(newName); 
    this.dispose(); 

} 
} 
} 

Выход:

old name:james  //prints correctly 
new name: null  //prints null 
new name in set method: rrr  //prints correctly 

Мне нужно напечатать rrr вместо нуль.

+0

сообщение соответствующий код вашего второго класса. И уважайте соглашения об именах Java. Классы начинаются с буквы верхнего регистра. –

+0

@JBNizet Добавить второй класс – Sajad

+0

@JBNizet Я думаю, что моему конструктору второго класса тоже нужно подождать, пока действие 'okButton' не будет начато' newName' – Sajad

ответ

4

Объекты Java несколько похожи на реальные объекты. И new делает то, что предлагает его название: он создает новый объект. Давайте рассмотрим простой пример:

Box box1 = new Box(); 
Box box2 = new Box(); 
box1.fillWithCandies(candies); 

box1 является ящик, наполненный конфетами. box2 - это другая коробка, в которой ничего нет, потому что только box1 был заполнен конфетами.

В вашем коде updateGUI's actionPerformed() метод создает новый объект RecordTableGUI с новым именем. Это ничего не изменит к первому.

Если вы хотите updateGUI изменить существующий объект RecordTableGUI, он должен иметь ссылку на этот объект:

public class updateGUI extends JFrame implements ActionListener { 

    private RecordTableGUI recordTableGUIToUpdateWhenOKIsClicked; 

    public updateGUI(RecordTableGUI recordTableGUIToUpdateWhenOKIsClicked, ...) { 
     this.recordTableGUIToUpdateWhenOKIsClicked = 
      recordTableGUIToUpdateWhenOKIsClicked; 
     ... 
    } 

    public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == okButton) { 
      newName = tf.getText(); 
      this.recordTableGUIToUpdateWhenOKIsClicked.setNewName(newName); 
     } 
    } 
} 

Вы должны практиковать с более простыми примерами перед использованием Swing. Вы также должны соблюдать соглашения об именах Java. И класс updateGui должен быть JDialog, а не JFrame.

+0

Ну, теперь как должен выглядеть метод 'RecordPableform()' RecordTableGUI'? Мое значение - инструкция после этого: 'this.setVisible (false);' – Sajad

+0

Я пытаюсь: RecordTableGUI recordObject = new RecordTableGUI(); 'then: ' updateGUI updateObject = new updateGUI (String.valueOf (oldName), recordObject); ', Но все же null в консоли – Sajad

+0

@Sajjad: Если вы этого еще не сделали, вам необходимо реализовать ** все ** рекомендаций JB Nizet, включая использование * модального * JDialog, а не JFrame для окна UpdateGui. Это ключ. Если у вас по-прежнему возникают проблемы после этого, вы захотите создать и опубликовать [sscce] (http://sscce.org), чтобы мы могли увидеть и испытать для себя проблему. 1+ к этому ответу. –

1

, например (no reason, don't bother with costructors, getter ...., Swing JComponents are designated to be reusable)

enter image description here

.

enter image description here

.

enter image description here

из кода

import java.awt.BorderLayout; 
import java.awt.Component; 
import java.awt.Dimension; 
import java.awt.Point; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.event.ListSelectionEvent; 
import javax.swing.event.ListSelectionListener; 
import javax.swing.table.*; 

public class TableCheckBox { 

    private static final long serialVersionUID = 1L; 
    private JTable table; 
    private JFrame frame = new JFrame("Popup Table Editor"); 
    // I'm reinvent the wheel see code for Popup Table Editor by @camickr 
    private JDialog dialog = new JDialog(frame, "Edit Table data", true); 
    private JPanel panel = new JPanel(); 
    private JLabel TypeLabel, CompanyLabel, SharesLabel, PriceLabel, BooleanLabel; 
    private JTextField TypeTextField, CompanyTextField; 
    private JFormattedTextField SharesTextField, PriceTextField; 
    private JCheckBox BooleanCheckBox; 
    private JButton saveButton = new JButton("Save changed to JTable"); 
    private Point location; 
    private Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"}; 
    private Object[][] data = { 
     {"Buy", "IBM", new Integer(1000), new Double(80.50), false}, 
     {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true}, 
     {"Sell", "Apple", new Integer(3000), new Double(7.35), true}, 
     {"Buy", "Nortel", new Integer(4000), new Double(20.00), false} 
    }; 
    private DefaultTableModel model = new DefaultTableModel(data, columnNames) { 
     private static final long serialVersionUID = 1L; 

     @Override 
     public Class getColumnClass(int column) { 
      return getValueAt(0, column).getClass(); 
     } 
    }; 

    public TableCheckBox() { 
     table = new JTable(model); 
     table.setPreferredScrollableViewportSize(table.getPreferredSize()); 
     table.getSelectionModel().setSelectionMode(
       ListSelectionModel.SINGLE_SELECTION); 
     table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { 
      @Override 
      public void valueChanged(ListSelectionEvent e) { 
       if (!e.getValueIsAdjusting()) { 
        System.out.println(table.getSelectedColumn()); 
        System.out.println(table.getSelectedRow()); 
       } 
      } 
     }); 
     JScrollPane scrollPane = new JScrollPane(table); 
     createPopupMenu(); 
     createDialog(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(scrollPane); 
     frame.pack(); 
     frame.setLocation(150, 150); 
     frame.setVisible(true); 
    } 

    private void createPopupMenu() { 
     JPopupMenu popup = new JPopupMenu(); 
     JMenuItem myMenuItem1 = new JMenuItem("Edit Table Data"); 
     myMenuItem1.addActionListener(showingDialog()); 
     popup.add(myMenuItem1); 
     MouseListener popupListener = new PopupListener(popup); 
     table.addMouseListener(popupListener); 
    } 

    private void createDialog() { 
     /* 
     laid to private JPanel panel = new JPanel(); change layout to GBC, SprigLayout 

     valid for follows JComponents 

     private JLabel TypeLabel, CompanyLabel, SharesLabel, PriceLabel, BooleanLabel; 
     private JTextField TypeTextField, CompanyTextField; 
     private JFormattedTextField SharesTextField, PriceTextField; 
     private JCheckBox BooleanCheckBox; 
     private JButton saveButton = new JButton("Save changed to JTable"); 
     */ 
     saveButton.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       //table.setValueAt(JTextField.getText, rowFromListSelectionLIstener, 
       //ColumnFromListSelectionListener + plusMinusCitibus) 
       //table.setValueAt(JFormattedTextField. getValue 
       //or(((Number) textField2.getValue()).doubleValue());, 
       //rowFromListSelectionLIstener, ColumnFromListSelectionListener + plusMinusCitibus) 
       hideDialog();//last code line 
      } 
     }); 
     dialog.add(saveButton, BorderLayout.SOUTH); 
     dialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); 
     dialog.addWindowListener(new WindowAdapter() { 
      @Override 
      public void windowClosing(WindowEvent e) { 
       hideDialog(); 
      } 
     }); 
     dialog.setPreferredSize(new Dimension(400, 300));// remove this code line 
     dialog.pack(); 
    } 

    private Action showingDialog() { 
     return new AbstractAction("Show Dialog") { 
      private static final long serialVersionUID = 1L; 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       System.out.println("dialog.setVisible(true)"); 
       // 
       // copy value from JTable/XxxTableModel to JComponents placed in JPanel 
       // 
       dialog.setVisible(false); 
       //location = frame.getLocationOnScreen(); 
       int x = location.x - 10; 
       int y = location.y + 50; 
       dialog.setLocation(x, y); 
       Runnable doRun = new Runnable() { 
        @Override 
        public void run() { 
         //dialog.setLocationRelativeTo(frame); 
         dialog.setVisible(true); 
        } 
       }; 
       SwingUtilities.invokeLater(doRun); 
      } 
     }; 
    } 

    private void hideDialog() { 
     System.out.println("dialog.setVisible(false)"); 
     /* 
     reset value for 
     private JTextField TypeTextField, CompanyTextField; 
     private JFormattedTextField SharesTextField, PriceTextField; 

     then after to call dialog.setVisible(false); 
     */ 
     dialog.setVisible(false);//last code line 
    } 

    private class PopupListener extends MouseAdapter { 

     private JPopupMenu popup; 

     PopupListener(JPopupMenu popupMenu) { 
      popup = popupMenu; 
     } 

     @Override 
     public void mousePressed(MouseEvent e) { 
      maybeShowPopup(e); 
     } 

     @Override 
     public void mouseReleased(MouseEvent e) { 
      if (table.getSelectedRow() != -1) { 
       maybeShowPopup(e); 
      } 
     } 

     private void maybeShowPopup(MouseEvent e) { 
      if (e.isPopupTrigger()) { 
       int row = table.rowAtPoint(e.getPoint());// get row that pointer is over     
       if (table.isRowSelected(row)) {// if pointer is over a selected row, show popup 
        Component comp = e.getComponent(); 
        location = comp.getLocationOnScreen(); 
        popup.show(e.getComponent(), e.getX(), e.getY()); 
       } 
      } 
     } 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       TableCheckBox frame = new TableCheckBox(); 
      } 
     }); 
    } 
} 
+0

Я запустил ваш код. В вашем коде ячейки можно редактировать только двойным щелчком? – Sajad

+0

Можете ли вы сказать мне, где моя ошибка в моем коде, что я получил «null» для нового имени? – Sajad

+0

'Я запустил ваш код. В вашем коде ячейки можно редактировать только двойным щелчком? --- --- да, по умолчанию и довольно хорошо для Compound JComponents (JComboBox, JSpinner, но я думаю, что это полезно для JTextArea ei) в качестве TableCellEditor , вы можете изменить, установить это значение [XxxEditor.setClickCountToStart] (http://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultCellEditor.html#setClickCountToStart%28int%29) – mKorbel

Смежные вопросы