将JLabel放在Java中的另一个类的JScrollPane上

时间:2014-08-14 21:01:51

标签: java swing jlabel

我正在制作家谱,这是我的问题。我有屏幕NewFamilyTree.javaNewPerson.java

NewFamilyTree.java:

public class NewFamilyTree {
...
 private void initialize() {
    frame = new JFrame();
    frame.setTitle("New family tree");
    frame.setBounds(100, 100, 906, 569);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
...
    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);

    JScrollPane scrollPane = new JScrollPane();
    tabbedPane.addTab("Tree", null, scrollPane, null);

    panel_1 = new JPanel();
    scrollPane.setViewportView(panel_1);
    panel_1.setLayout(new MigLayout("", "[][][][][][][][]", "[][][][][][]"));

NewPerson.java:

public class NewPerson{

...

buttonAdd = new JButton("Add");
        buttonAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                String names = textFieldNames.getText();
                String dateBirth = textFieldDateOfBirth.getText();
                String bio = textAreaBio.getText();

                Data newData = new Data(names, dateBirth, bio, fileID);

               //code that puts new label on scrollpane from NewFamilyTree.java
            }
        });
        buttonAdd.setBackground(new Color(30, 144, 255));
        frame.getContentPane().add(buttonAdd, "cell 2 6,grow");
    }

我需要在new JLabel的{​​{1}}上按下按钮添加,从而class NewPerson添加JScrollPane。希望有人可以提供帮助,我搜索了很多,无法帮助自己。

编辑:在@mjr的答案之后。

我在NewFamilytree.java中添加了public JPanel panel_1;。在NewFamilyTree执行的操作中,我添加了:

Add

没有错误,但是 - 按 add 按钮后没有任何反应。我还添加了JLabel lblHomer = new JLabel("Homer"); lblHomer.setIcon(new ImageIcon("C:\\Users\\Tinmar\\Desktop\\HomerSimpson3.gif")); panel_1.add(lblHomer, "cell 7 5"); NewPerson EXTENDS NewFamilyTree

3 个答案:

答案 0 :(得分:3)

  1. NewPerson不需要从NewFamilyTree扩展,它不会向该类添加任何功能
  2. 不要在JFrame中使用NewPerson,而应考虑使用模式JDialog。有关详细信息,请参阅How to Make Dialogs
  3. 限制类之间组件的暴露。 NewFamilyTree没有理由能够访问NewPerson使用的“窗口”。 NewPerson没有理由为NewFamilyTree
  4. 添加任何内容
  5. 不要将重量较重的组件(如java.awt.Button)与轻质组件混合使用,这可能导致问题无法解决......
  6. 你需要改变你对事物的看法。不要试图NewPerson更新NewFamilyTree的用户界面,而是NewPerson从用户收集详细信息并将此信息传回NewFamilyTree,以便它可以使用它...

    例如......

    JButton newPersonButton = new JButton("New Person");
    newPersonButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Data data = NewPerson.createPerson(frame);
            if (data != null) {
                JLabel lblHomer = new JLabel(data.names);
                panel_1.add(lblHomer, "cell 7 5");
                panel_1.revalidate();
            }
        }
    });
    

    这基本上使用了static方法createPerson,该方法会传回Data的实例(如果用户取消了操作,则返回nullNewFamilyTree然后可以使用。它将代码分离,因为NewPerson并不依赖NewFamilyTreeNewFamilyTree维持控制的任何内容。这清楚地定义了两个类之间的责任区域,这也意味着可以从任何地方调用NewPerson ......

    createPerson方法看起来像是......

    public static Data createPerson(Component comp) {
        NewPerson newPerson = new NewPerson();
        Window win = SwingUtilities.getWindowAncestor(comp);
        JDialog dialog = null;
        if (win instanceof Frame) {
            dialog = new JDialog((Frame) win, "New person", true);
        } else if (win instanceof Dialog) {
            dialog = new JDialog((Dialog) win, "New person", true);
        } else {
            dialog = new JDialog((Frame) null, "New person", true);
        }
        newPerson.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Object source = e.getSource();
                if (source instanceof Component) {
                    Window win = SwingUtilities.getWindowAncestor((Component) source);
                    win.dispose();
                }
            }
        });
        dialog.add(newPerson);
        dialog.setVisible(true);
    
        return newPerson.getData();
    }
    

    它基本上创建JDialog的实例,向用户显示它并等待NewPerson类触发ActionEvent,它用于处理对话框。然后它会询问NewPerson的实例数据......

    因为有一大堆我没有谈过的功能,这里有一个完全可运行的例子......

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dialog;
    import java.awt.EventQueue;
    import java.awt.Frame;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    
    import net.miginfocom.swing.MigLayout;
    
    public class NewFamilyTree {
    
        private JFrame frame;
        private JPanel panel_1;
        private JScrollPane scrollPane;
        private JTabbedPane tabbedPane;
    
        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        NewFamilyTree window = new NewFamilyTree();
                        window.frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
    
            });
        }
    
        /**
         * Create the application.
         */
        public NewFamilyTree() {
            initialize();
        }
    
        /**
         * Initialize the contents of the frame.
         */
        private void initialize() {
            frame = new JFrame();
            frame.setTitle("New family tree");
            frame.getContentPane().setBackground(new Color(135, 206, 250));
            frame.setBounds(100, 100, 906, 569);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JPanel panel = new JPanel();
            panel.setBackground(new Color(30, 144, 255));
            frame.getContentPane().add(panel, BorderLayout.EAST);
            panel.setLayout(new MigLayout("", "[]", "[][][][][][][][]"));
    
            JButton newPersonButton = new JButton("New Person");
            newPersonButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    Data data = NewPerson.createPerson(frame);
                    if (data != null) {
                        JLabel lblHomer = new JLabel(data.names);
    //                    lblHomer.setIcon(new ImageIcon("C:\\Users\\Tinmar\\Desktop\\HomerSimpson3.gif"));
                        panel_1.add(lblHomer, "cell 7 5");
                        panel_1.revalidate();
                    }
                }
            });
            panel.add(newPersonButton, "cell 0 5");
    
            JButton btnNewButton_1 = new JButton("New button");
            panel.add(btnNewButton_1, "cell 0 6");
    
            tabbedPane = new JTabbedPane(JTabbedPane.TOP);
            frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
    
            scrollPane = new JScrollPane();
            tabbedPane.addTab("Tree", null, scrollPane, null);
    
            panel_1 = new JPanel();
            scrollPane.setViewportView(panel_1);
            panel_1.setLayout(new MigLayout("", "[][][][][][][][]", "[][][][][][]"));
    
    //        JLabel lblHomer = new JLabel("Homer");
    //        lblHomer.setIcon(new ImageIcon("C:\\Users\\Tinmar\\Desktop\\HomerSimpson3.gif"));
    //        panel_1.add(lblHomer, "cell 7 5");
            JScrollPane scrollPane_1 = new JScrollPane();
            tabbedPane.addTab("Info", null, scrollPane_1, null);
    
            frame.repaint();
    
        }
    //
    //    /**
    //     * Launch the application.
    //     */
    //    public static void main(String[] args) {
    //        EventQueue.invokeLater(new Runnable() {
    //            public void run() {
    //                try {
    //                    NewPerson window = new NewPerson();
    //                    window.frame.setVisible(true);
    //                } catch (Exception e) {
    //                    e.printStackTrace();
    //                }
    //            }
    //        });
    //    }
    
        public static class NewPerson extends JPanel {
    
            private JTextField textFieldNames;
            private JButton selectPictureButton;
            private JLabel labelDateOfBirth;
            private JTextField textFieldDateOfBirth;
            private JLabel labelShortBio;
            private JTextArea textAreaBio;
            private JLabel labelSelectPicture;
            private JButton buttonAdd;
            private String fileID;
    
            private Data data;
    
            /**
             * Create the application.
             */
            private NewPerson() {
                initialize();
            }
    
            public static Data createPerson(Component comp) {
                NewPerson newPerson = new NewPerson();
                Window win = SwingUtilities.getWindowAncestor(comp);
                JDialog dialog = null;
                if (win instanceof Frame) {
                    dialog = new JDialog((Frame) win, "New person", true);
                } else if (win instanceof Dialog) {
                    dialog = new JDialog((Dialog) win, "New person", true);
                } else {
                    dialog = new JDialog((Frame) null, "New person", true);
                }
                newPerson.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Object source = e.getSource();
                        if (source instanceof Component) {
                            Window win = SwingUtilities.getWindowAncestor((Component) source);
                            win.dispose();
                        }
                    }
                });
                dialog.add(newPerson);
                dialog.pack();
                dialog.setLocationRelativeTo(comp);
                dialog.setVisible(true);
    
                return newPerson.getData();
            }
    
            public void addActionListener(ActionListener listener) {
                listenerList.add(ActionListener.class, listener);
            }
    
            protected void fireActionPerformed() {
                ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
                if (listeners != null && listeners.length > 0) {
                    ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "created");
                    for (ActionListener listener : listeners) {
                        listener.actionPerformed(evt);
                    }
                }
            }
    
            public Data getData() {
                return data;
            }
    
            /**
             * Initialize the contents of the frame.
             */
            private void initialize() {
                setBackground(new Color(135, 206, 250));
                setLayout(new MigLayout("", "[][][grow]", "[][][][grow][][][]"));
    
                JLabel labelNames = new JLabel("Name and Surname:");
                add(labelNames, "cell 1 1,alignx trailing");
    
                textFieldNames = new JTextField();
                add(textFieldNames, "cell 2 1,growx");
                textFieldNames.setColumns(10);
    
                labelDateOfBirth = new JLabel("Date of birth:");
                add(labelDateOfBirth, "cell 1 2,alignx center,aligny center");
    
                textFieldDateOfBirth = new JTextField();
                add(textFieldDateOfBirth, "cell 2 2,growx");
                textFieldDateOfBirth.setColumns(10);
    
                labelShortBio = new JLabel("Bio:");
                add(labelShortBio, "cell 1 3,alignx center,aligny center");
    
                textAreaBio = new JTextArea();
                add(textAreaBio, "cell 2 3,grow");
    
                labelSelectPicture = new JLabel("Select picture:");
                add(labelSelectPicture, "cell 1 4,alignx center,aligny center");
    
                selectPictureButton = new JButton("...");
                selectPictureButton.setBackground(new Color(30, 144, 255));
                selectPictureButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent arg0) {
    
                        JFileChooser chooser = new JFileChooser(new File(System.getProperty("user.home") + "\\Desktop"));
    
                        chooser.setDialogTitle("Select Location");
                        chooser.setFileSelectionMode(JFileChooser.APPROVE_OPTION);
                        chooser.setAcceptAllFileFilterUsed(false);
    
                        if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                            fileID = chooser.getSelectedFile().getPath();
                            // txtField.setText(fileID);
                        }
    
                    }
                });
                add(selectPictureButton, "cell 2 4");
    
                buttonAdd = new JButton("Add");
                buttonAdd.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent arg0) {
    
                        String names = textFieldNames.getText();
                        String dateBirth = textFieldDateOfBirth.getText();
                        String bio = textAreaBio.getText();
    
                        data = new Data(names, dateBirth, bio, fileID);
                        fireActionPerformed();
                    }
                });
                buttonAdd.setBackground(new Color(30, 144, 255));
                add(buttonAdd, "cell 2 6,grow");
            }
    
        }
    
        public static class Data {
    
            private final String names;
            private final String dateBirth;
            private final String bio;
            private final String fileID;
    
            private Data(String names, String dateBirth, String bio, String fileID) {
                this.names = names;
                this.dateBirth = dateBirth;
                this.bio = bio;
                this.fileID = fileID;
            }
    
        }
    
    }
    
    • 不要依赖static来跨类提供功能。如果您必须从其他类中获取某些内容,请将其作为参考传递。 static不是你的朋友,你应该小心并警惕它的使用
    • 不要在没有充分理由的情况下公开课程的字段,依靠interface s来允许课程提供或获取信息。这限制了其他类可以做的事情。
    • 分离并隔离责任
    • 查看How to Use Trees

答案 1 :(得分:1)

当您向NewPerson添加按钮时,可以在NewPerson中访问NewFamilyTree的frame,如果您要添加标签,则必须在NewPerson中访问scrollPane那个班。因此,使用scrollPane执行相同的操作就像使用frame一样,以便能够在NewPerson中使用它。

答案 2 :(得分:0)

我假设JScrollPane和addButton在不同的框架中......虽然它们确实可以在相同的框架中工作。 基本上,您需要为JScrollPane和JPanel提供getter,以便可以从NewPerson类访问它们。 在buttonAdd的动作侦听器中,如果标签不在面板当前大小的脚上,则需要增加面板的首选大小。当面板的首选大小大于JScrollPane的视图大小时,滚动条将自动出现。

请参阅以下代码: NewFamilyTree.jva:

package dva.test001;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;

public class NewFamilyTree {
    private JFrame frame;
    private JScrollPane scrollPane;
    private JPanel panel;

    public NewFamilyTree() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setTitle("New family tree");
        frame.setBounds(100, 100, 906, 569);
        frame.setLayout(new BorderLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
        panel = new JPanel();
        panel.setPreferredSize(new Dimension(700, 300));
        panel.setLayout(null);
        scrollPane = new JScrollPane(panel);
        tabbedPane.addTab("Tree", null, scrollPane, null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        NewFamilyTree ft = new NewFamilyTree();
        NewPerson np = new NewPerson(ft);
    }

    public JFrame getFrame() {
        return frame;
    }

    public JScrollPane getScrollPane() {
        return scrollPane;
    }

    public JPanel getPanel() {
        return panel;
    }
}

NewPerson.java:

package dva.test001;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class NewPerson {
    private NewFamilyTree familyTree;
    private static final int labelHeight = 30;

    public NewPerson(NewFamilyTree familyTree) {
        this.familyTree = familyTree;
        init();
    }

    public void init() {
        JFrame frame = new JFrame();
        frame.setTitle("New Person");
        frame.setBounds(100, 500, 906, 100);

        JButton buttonAdd = new JButton("Add");
        buttonAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                String names = "names"; //textFieldNames.getText();
                String dateBirth = "date"; //textFieldDateOfBirth.getText();
                String bio = "bio"; //textAreaBio.getText();

                //Data newData = new Data(names, dateBirth, bio, fileID);

               //code that puts new label on scrollpane from NewFamilyTree.java
                JLabel lbl = new JLabel(names);
                int top = familyTree.getPanel().getComponentCount() * labelHeight;
                if(top + labelHeight > familyTree.getPanel().getHeight()) {
                    familyTree.getPanel().setPreferredSize(new Dimension(familyTree.getPanel().getWidth(), top + labelHeight));
                    familyTree.getScrollPane().revalidate();
                }
                familyTree.getPanel().add(lbl);
                lbl.setBounds(10, top, 100, labelHeight);
            }
        });
        buttonAdd.setBackground(new Color(30, 144, 255));
        frame.getContentPane().add(buttonAdd);
        frame.setVisible(true);
    }
}