JScrollPane没有按预期工作,为什么?

时间:2015-11-25 09:14:56

标签: java swing jscrollpane

通过向else-if逻辑添加6个分支来编辑动作侦听器。每 branch会比较actionCommand和6个子菜单项:Metal,Motif, 窗口,永远,永远,和所需。

一个。每个外观和感觉子菜单项将使用try-catch语句进行设置 适当的外观和感觉,如果这样显示错误消息 没有完成。

湾每个Scroll Bars子菜单项将设置水平和垂直滚动 禁止政策到适当的价值。

℃。已经创建的任何组件都需要更新。这个 可以通过调用SwingUtilities.updateComponentTreeUI方法来完成,将对要更新的组件的引用作为参数传递。具体来说,您需要添加一行

SwingUtilities.updateComponentTreeUIgetContentPane());

到刚刚添加到逻辑结构的每个分支。

我的代码就是这个......它崩溃了,我完全陷入了原因。任何帮助表示赞赏。

package src.javaapplication5;


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class NoteTaker extends JFrame {
    //constants for set up of note taking area

    public static final int WIDTH = 600;
    public static final int HEIGHT = 300;
    public static final int LINES = 13;
    public static final int CHAR_PER_LINE = 45;

    //objects in GUI
    private JTextArea theText;      //area to take notes
    private JMenuBar mBar;  //horizontal menu bar
    private JPanel textPanel;   //panel to hold scrolling text area 
    private JMenu notesMenu;    //vertical menu with choices for notes

    //****THESE ITEMS ARE NOT YET USED.  YOU WILL BE CREATING THEM IN THIS LAB
    private JMenu viewMenu; //vertical menu with choices for views  
    private JMenu lafMenu;  //vertical menu with look and feel
    private JMenu sbMenu;   //vertical menu with scroll bar option
    private JScrollPane scrolledText;   //scroll bars   

    //default notes
    private String note1 = "No Note 1.";
    private String note2 = "No Note 2.";

    /**
     * constructor
     */
    public NoteTaker() {
        //create a closeable JFrame with a specific size
        super("Note Taker");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //get contentPane and set layout of the window
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());

        //creates the vertical menus 
        createNotes();
        createViews();

        //creates horizontal menu bar and 
        //adds vertical menus to it
        mBar = new JMenuBar();
        mBar.add(notesMenu);
        mBar.add(viewMenu);
        //****ADD THE viewMenu TO THE MENU BAR HERE
        setJMenuBar(mBar);

        //creates a panel to take notes on
        textPanel = new JPanel();
        textPanel.setBackground(Color.blue);
        JTextArea theText = new JTextArea(LINES, CHAR_PER_LINE);
        theText.setBackground(Color.white);

        JScrollPane scrolledText = new JScrollPane(theText);

        //****CREATE A JScrollPane OBJECT HERE CALLED scrolledText
        //****AND PASS IN theText, THEN 
        //****CHANGE THE LINE BELOW BY PASSING IN scrolledText
        textPanel.add(scrolledText);

        contentPane.add(textPanel, BorderLayout.CENTER);
    }

    /**
     * creates vertical menu associated with Notes menu item on menu bar
     */
    public void createNotes() {
        notesMenu = new JMenu("Notes");
        JMenuItem item;

        item = new JMenuItem("Save Note 1");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);

        item = new JMenuItem("Save Note 2");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);

        item = new JMenuItem("Open Note 1");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);

        item = new JMenuItem("Open Note 2");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);

        item = new JMenuItem("Clear");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);

        item = new JMenuItem("Exit");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);
    }

    /**
     * creates vertical menu associated with Views menu item on the menu bar
     */
    public void createViews() {

        viewMenu = new JMenu("Views");
        viewMenu.setMnemonic(KeyEvent.VK_V);

        createLookAndFeel();
        createScrollBars();

        lafMenu.addActionListener(new MenuListener());
        sbMenu.addActionListener(new MenuListener());

        viewMenu.add(lafMenu);
        viewMenu.add(sbMenu);

    }

    /**
     * creates the look and feel submenu
     */
    public void createLookAndFeel() {

        lafMenu = new JMenu("Look and Feel");
        lafMenu.setMnemonic(KeyEvent.VK_L);

        JMenuItem metalItem;
        JMenuItem motifItem;
        JMenuItem windowsItem;

        metalItem = new JMenuItem("Metal");
        metalItem.addActionListener(new MenuListener());

        motifItem = new JMenuItem("Motif");
        motifItem.addActionListener(new MenuListener());

        windowsItem = new JMenuItem("Windows");
        windowsItem.addActionListener(new MenuListener());

        lafMenu.add(metalItem);
        lafMenu.add(motifItem);
        lafMenu.add(windowsItem);

    }

    /**
     * creates the scroll bars submenu
     */
    public void createScrollBars() {

        sbMenu = new JMenu("Scroll Bars");
        sbMenu.setMnemonic(KeyEvent.VK_S);

        JMenuItem neverItem;
        JMenuItem alwaysItem;
        JMenuItem asneededItem;

        neverItem = new JMenuItem("Never");
        neverItem.addActionListener(new MenuListener());

        alwaysItem = new JMenuItem("Always");
        alwaysItem.addActionListener(new MenuListener());

        asneededItem = new JMenuItem("As Needed");
        asneededItem.addActionListener(new MenuListener());

        sbMenu.add(neverItem);
        sbMenu.add(alwaysItem);
        sbMenu.add(asneededItem);

    }

    private class MenuListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            String actionCommand = e.getActionCommand();
            if (actionCommand.equals("Save Note 1")) {
                note1 = theText.getText();
            } else if (actionCommand.equals("Save Note 2")) {
                note2 = theText.getText();
            } else if (actionCommand.equals("Clear")) {
                theText.setText("");
            } else if (actionCommand.equals("Open Note 1")) {
                theText.setText(note1);
            } else if (actionCommand.equals("Open Note 2")) {
                theText.setText(note2);
            } else if (actionCommand.equals("Exit")) {
                System.exit(0);
            } else if (actionCommand.equals("Metal")) {
                try {
                    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                    SwingUtilities.updateComponentTreeUI(getContentPane());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Error setting "
                            + "the look and feel");
                    System.exit(0);
                }
            } else if (actionCommand.equals("Motif")) {
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                    SwingUtilities.updateComponentTreeUI(getContentPane());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Error setting "
                            + "the look and feel");
                    System.exit(0);
                }

            } else if (actionCommand.equals("Windows")) {
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                    SwingUtilities.updateComponentTreeUI(getContentPane());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Error setting "
                            + "the look and feel");
                    System.exit(0);
                }

            } else if (actionCommand.equals("Never")) {
                scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                SwingUtilities.updateComponentTreeUI(getContentPane());
                scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
                SwingUtilities.updateComponentTreeUI(getContentPane());
            } else if (actionCommand.equals("Always")) {
                scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
                SwingUtilities.updateComponentTreeUI(getContentPane());
                scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                SwingUtilities.updateComponentTreeUI(getContentPane());
            } else if (actionCommand.equals("As Needed")) {
                scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                SwingUtilities.updateComponentTreeUI(getContentPane());
                scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
                SwingUtilities.updateComponentTreeUI(getContentPane());
            } //****ADD 6 BRANCHES TO THE ELSE-IF STRUCTURE
            //****TO ALLOW ACTION TO BE PERFORMED FOR EACH
            //****MENU ITEM YOU HAVE CREATED
            else {
                theText.setText("Error in memo interface");
            }
        }
    }

    public static void main(String[] args) {
        NoteTaker gui = new NoteTaker();
        gui.setVisible(true);
    }
}

3 个答案:

答案 0 :(得分:2)

很多问题,请将您的代码与

进行比较
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.EmptyBorder;

public class NoteTaker {
    //constants for set up of note taking area

    public static final int WIDTH = 600;
    public static final int HEIGHT = 300;
    public static final int LINES = 13;
    public static final int CHAR_PER_LINE = 45;
    //
    private JFrame frame = new JFrame("Note Taker");

    //objects in GUI
    private JTextArea theText;      //area to take notes
    private JMenuBar mBar;  //horizontal menu bar
    private JPanel textPanel;   //panel to hold scrolling text area 
    private JMenu notesMenu;    //vertical menu with choices for notes

    //****THESE ITEMS ARE NOT YET USED.  YOU WILL BE CREATING THEM IN THIS LAB
    private JMenu viewMenu; //vertical menu with choices for views  
    private JMenu lafMenu;  //vertical menu with look and feel
    private JMenu sbMenu;   //vertical menu with scroll bar option
    private JScrollPane scrolledText;   //scroll bars   

    //default notes
    private String note1 = "No Note 1.";
    private String note2 = "No Note 2.";

    /**
     * constructor
     */
    public NoteTaker() {
        //create a closeable JFrame with a specific size
        //setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //get contentPane and set layout of the window
        //Container contentPane = frame;
        //contentPane.setLayout(new BorderLayout());
        //creates the vertical menus 
        createNotes();
        createViews();

        //creates horizontal menu bar and 
        //adds vertical menus to it
        mBar = new JMenuBar();
        mBar.add(notesMenu);
        mBar.add(viewMenu);
        //****ADD THE viewMenu TO THE MENU BAR HERE
        frame.setJMenuBar(mBar);

        //creates a panel to take notes on
        textPanel = new JPanel(new BorderLayout());
        textPanel.setBackground(Color.blue);
        textPanel.setBorder(new EmptyBorder(5,5,5,5));
        /*JTextArea*/ theText = new JTextArea(LINES, CHAR_PER_LINE);
        theText.setBackground(Color.white);

        /*JScrollPane*/ scrolledText = new JScrollPane(theText);

        //****CREATE A JScrollPane OBJECT HERE CALLED scrolledText
        //****AND PASS IN theText, THEN 
        //****CHANGE THE LINE BELOW BY PASSING IN scrolledText
        textPanel.add(scrolledText);

        frame.add(textPanel/*, BorderLayout.CENTER*/);
        frame.pack();
        frame.setVisible(true);
    }

    /**
     * creates vertical menu associated with Notes menu item on menu bar
     */
    public void createNotes() {
        notesMenu = new JMenu("Notes");
        JMenuItem item;

        item = new JMenuItem("Save Note 1");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);

        item = new JMenuItem("Save Note 2");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);

        item = new JMenuItem("Open Note 1");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);

        item = new JMenuItem("Open Note 2");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);

        item = new JMenuItem("Clear");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);

        item = new JMenuItem("Exit");
        item.addActionListener(new MenuListener());
        notesMenu.add(item);
    }

    /**
     * creates vertical menu associated with Views menu item on the menu bar
     */
    public void createViews() {

        viewMenu = new JMenu("Views");
        viewMenu.setMnemonic(KeyEvent.VK_V);

        createLookAndFeel();
        createScrollBars();

        lafMenu.addActionListener(new MenuListener());
        sbMenu.addActionListener(new MenuListener());

        viewMenu.add(lafMenu);
        viewMenu.add(sbMenu);

    }

    /**
     * creates the look and feel submenu
     */
    public void createLookAndFeel() {

        lafMenu = new JMenu("Look and Feel");
        lafMenu.setMnemonic(KeyEvent.VK_L);

        JMenuItem metalItem;
        JMenuItem motifItem;
        JMenuItem windowsItem;

        metalItem = new JMenuItem("Metal");
        metalItem.addActionListener(new MenuListener());

        motifItem = new JMenuItem("Motif");
        motifItem.addActionListener(new MenuListener());

        windowsItem = new JMenuItem("Windows");
        windowsItem.addActionListener(new MenuListener());

        lafMenu.add(metalItem);
        lafMenu.add(motifItem);
        lafMenu.add(windowsItem);

    }

    /**
     * creates the scroll bars submenu
     */
    public void createScrollBars() {

        sbMenu = new JMenu("Scroll Bars");
        sbMenu.setMnemonic(KeyEvent.VK_S);

        JMenuItem neverItem;
        JMenuItem alwaysItem;
        JMenuItem asneededItem;

        neverItem = new JMenuItem("Never");
        neverItem.addActionListener(new MenuListener());

        alwaysItem = new JMenuItem("Always");
        alwaysItem.addActionListener(new MenuListener());

        asneededItem = new JMenuItem("As Needed");
        asneededItem.addActionListener(new MenuListener());

        sbMenu.add(neverItem);
        sbMenu.add(alwaysItem);
        sbMenu.add(asneededItem);

    }

    private class MenuListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            String actionCommand = e.getActionCommand();
            if (actionCommand.equals("Save Note 1")) {
                note1 = theText.getText();
            } else if (actionCommand.equals("Save Note 2")) {
                note2 = theText.getText();
            } else if (actionCommand.equals("Clear")) {
                theText.setText("");
            } else if (actionCommand.equals("Open Note 1")) {
                theText.setText(note1);
            } else if (actionCommand.equals("Open Note 2")) {
                theText.setText(note2);
            } else if (actionCommand.equals("Exit")) {
                System.exit(0);
            } else if (actionCommand.equals("Metal")) {
                try {
                    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                    SwingUtilities.updateComponentTreeUI(frame);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Error setting "
                            + "the look and feel");
                    System.exit(0);
                }
            } else if (actionCommand.equals("Motif")) {
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                    SwingUtilities.updateComponentTreeUI(frame);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Error setting "
                            + "the look and feel");
                    System.exit(0);
                }

            } else if (actionCommand.equals("Windows")) {
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                    SwingUtilities.updateComponentTreeUI(frame);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Error setting "
                            + "the look and feel");
                    System.exit(0);
                }

            } else if (actionCommand.equals("Never")) {
                //SwingUtilities.updateComponentTreeUI(frame);
                scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
                //SwingUtilities.updateComponentTreeUI(frame);
            } else if (actionCommand.equals("Always")) {
                //SwingUtilities.updateComponentTreeUI(frame);
                scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
                scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                //SwingUtilities.updateComponentTreeUI(frame);
            } else if (actionCommand.equals("As Needed")) {
                //SwingUtilities.updateComponentTreeUI(frame);
                scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
                //SwingUtilities.updateComponentTreeUI(frame);
            } //****ADD 6 BRANCHES TO THE ELSE-IF STRUCTURE
            //****TO ALLOW ACTION TO BE PERFORMED FOR EACH
            //****MENU ITEM YOU HAVE CREATED
            else {
                theText.setText("Error in memo interface");
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                NoteTaker gui = new NoteTaker();
            }
        });
    }
}

答案 1 :(得分:1)

您收到异常,因为scrollText为空。

创建scrollText时,它将在构造函数中创建为局部变量。

JScrollPane scrolledText = new JScrollPane(theText);

它也被声明为一个字段,但由于它也在构造函数中声明为局部变量,因此该字段永远不会被初始化。

相反,只需:

scrolledText = new JScrollPane(theText);

答案 2 :(得分:1)

您的代码:

else if (actionCommand.equals("Never")) {
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            SwingUtilities.updateComponentTreeUI(getContentPane());
            scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
            SwingUtilities.updateComponentTreeUI(getContentPane());
        } else if (actionCommand.equals("Always")) {
            scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            SwingUtilities.updateComponentTreeUI(getContentPane());
            scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            SwingUtilities.updateComponentTreeUI(getContentPane());
        } else if (actionCommand.equals("As Needed")) {
            scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            SwingUtilities.updateComponentTreeUI(getContentPane());
            scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
            SwingUtilities.updateComponentTreeUI(getContentPane());
        }

我的代码:

else if (actionCommand.equals("Never")) {
            scrolledText.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            SwingUtilities.updateComponentTreeUI(getContentPane());
            scrolledText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
            SwingUtilities.updateComponentTreeUI(getContentPane());
        } 
        else if (actionCommand.equals("Always")) {
            scrolledText.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            SwingUtilities.updateComponentTreeUI(getContentPane());
            scrolledText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            SwingUtilities.updateComponentTreeUI(getContentPane());
        } 
        else if (actionCommand.equals("As Needed")) {
            scrolledText.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            SwingUtilities.updateComponentTreeUI(getContentPane());
            scrolledText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
            SwingUtilities.updateComponentTreeUI(getContentPane());
        }