使用构造函数初始化变量

时间:2013-08-11 22:16:54

标签: java swing

我有两个类,第一个是我的主类,第二个是我的编辑框架类。

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)在它的构造函数中给出oldName,在编辑之后,当我点击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为null?

更新

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而不是null。

2 个答案:

答案 0 :(得分:4)

Java对象有点像真实对象。而new就是它的名字所暗示的:它创造了一个新的对象。我们举一个简单的例子:

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

box1是一个装满糖果的盒子。 box2是一个不同的框,不包含任何内容,因为只有box1填充了糖果。

在您的代码中,updateGUI的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。

答案 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();
            }
        });
    }
}