Initialize variable with constructor

后端 未结 2 756
你的背包
你的背包 2020-12-06 20:41

I have two class, first is my main class, and second class in my edit frame class.

public class RecordTableGUI extends JFrame implements ActionListener {
            


        
相关标签:
2条回答
  • 2020-12-06 20:53

    for example (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

    from code

    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 讨论(0)
  • 2020-12-06 21:08

    Java objects are somewhatlike real objects. And new does what its name suggests: it creates a new object. Let's take a simple example:

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

    box1 is a box filled with candies. box2 is a different box, which doesn't contain anything, because only box1 has been filled with candies.

    In your code, updateGUI's actionPerformed() method creates a new RecordTableGUI object, with the new name. That won't change anything to the first one.

    If you want updateGUI to modify the existing RecordTableGUI object, it needs to have a reference to this object:

    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);
            }
        }
    }
    

    You should practice with simpler examples before using Swing. You should also respect the Java naming conventions. And the updateGui class should be a JDialog, not a JFrame.

    0 讨论(0)
提交回复
热议问题