简体   繁体   English

如何获得我的MenuItems来从单独的类中调用方法?

[英]How do I get my MenuItems to call a method from a separate class?

I currently have a project with three different classes. 我目前有一个包含三个不同班级的项目。 I have a driver class (main), a GUI panel with all the button listeners and gui components in and then a third class with the methods the Graphics Panel abides to. 我有一个驱动程序类(主类),一个包含所有按钮侦听器和gui组件的GUI面板,然后有一个带有Graphics Panel遵循的方法的第三类。

I'm wondering how I would go about getting my JMenuItem "new" to call upon the clear method from my GraphicsPanel class. 我想知道如何使JMenuItem为“ new”以从GraphicsPanel类中调用clear方法。

Main Method: 主要方法:

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class guiDriver {

    public static void main(String[] args) {


    JFrame frame = new JFrame("Pen Simulator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        GUIPanel panel = new GUIPanel();
        frame.add(panel);
        // there is a method to set minimum size
        frame.setMinimumSize(new Dimension(600, 400));

        JMenuBar menuBar = new JMenuBar();

        // File Menu
        JMenu fileMenu = new JMenu("File");
        JMenu helpMenu = new JMenu("Help");
        menuBar.add(fileMenu);
        menuBar.add(helpMenu);

        JMenuItem item1 = new JMenuItem("New");

        JMenuItem item2 = new JMenuItem("Load");

        JMenuItem item3 = new JMenuItem("Save");

        JMenuItem item4 = new JMenuItem("Exit");

        fileMenu.add(item1);
        fileMenu.add(item2);
        fileMenu.add(item3);
        fileMenu.add(item4);

        // Help Menu

        JMenuItem about = new JMenuItem("About");
        helpMenu.add(about);

        frame.setJMenuBar(menuBar); // setting the Frames menubar as the newly
                                    // created menubar
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

}

GUIPANEL: GUIPANEL:

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

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class GUIPanel extends JPanel {

    private JTextField userCommand;
    private JLabel instruction1;
    private JButton instruct, clear;
    private GraphicsPanel graphics;
    private int penX, penY, angle;
    private int currentDirection = 0;

    private boolean penIsUp = false;
    private Color penColour;

    public GUIPanel() {

        graphics = new GraphicsPanel();

        setLayout(new BorderLayout());

        // SOUTH PANEL CONSTRUCTOR
        JPanel command = new JPanel();
        command.setLayout(new BoxLayout(command, BoxLayout.LINE_AXIS));
        instruction1 = new JLabel("Enter Command:");

        // BUTTO
        instruct = new JButton("Execute");
        instruct.addActionListener(new ButtonListener());
        clear = new JButton("Clear Graphics");

        // TEXT FIELD
        userCommand = new JTextField(10);

        command.add(instruction1);
        command.add(Box.createRigidArea(new Dimension(4, 0)));
        command.add(userCommand);
        command.add(Box.createRigidArea(new Dimension(2, 0)));
        command.add(instruct);
        command.add(Box.createRigidArea(new Dimension(2, 0)));
        command.add(clear);

        add(command, BorderLayout.SOUTH);
        add(graphics, BorderLayout.CENTER);

        init();

    }

    public void init() {

        penX = graphics.getWidth() / 2;
        penY = graphics.getHeight() / 2;
    }

    public void moveForward() {

        String command = userCommand.getText().toLowerCase();
        int distance = Integer.parseInt(command.replace("forward ", ""));

        userCommand.setText("");

        if (penIsUp == false) {
            if (currentDirection == 0) {
                graphics.drawLine(penColour, penX, penY, penX, (penY - distance));
                penY = penY - distance;
            }
            if (currentDirection == 1) {
                graphics.drawLine(penColour, penX, penY, penX + distance, penY);
                penX = penX + distance;
            }
            if (currentDirection == 2) {
                graphics.drawLine(penColour, penX, penY, penX, (penY + distance));
                penY = penY + distance;
            }
            if (currentDirection == 3) {
                graphics.drawLine(penColour, penX, penY, penX - distance, penY);
                penX = penX - distance;
            }
            graphics.repaint();

        } else if (penIsUp == true) {
            penY = penY - distance;

        }
    }

    public void moveBackward() {

        String command = userCommand.getText().toLowerCase();
        int distance = Integer.parseInt(command.replace("backward ", ""));

        userCommand.setText("");

        if (penIsUp == false) {
            graphics.drawLine(penColour, penX, penY, penX, (penY + distance));
            graphics.repaint();
            penY = penY + distance;

        } else if (penIsUp == true) {
            penX = penX + distance;
        }

    }

    public void penUp() {
        penIsUp = true;
        userCommand.setText("");
    }

    public void penDown() {
        penIsUp = false;
        userCommand.setText("");
    }

    class ButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (userCommand.getText().equalsIgnoreCase("something")) {

                System.out.println("you typed something");
                userCommand.setText("");
            }

            else if (userCommand.getText().equalsIgnoreCase("turnleft")) {
                currentDirection = currentDirection - 1;
                if (currentDirection == -1) {
                    currentDirection = 3;
                }
                userCommand.setText("");

            }

            else if (userCommand.getText().equalsIgnoreCase("turnright")) {
                currentDirection = currentDirection + 1;
                if (currentDirection == 4) {
                    currentDirection = 0;
                }
                userCommand.setText("");
            }

            else if (userCommand.getText().startsWith("forward ")) {

                try {
                    moveForward();

                } catch (NumberFormatException e1) {
                    System.out.println("Invalid command");
                }
            }

            else if (userCommand.getText().startsWith("backward ")) {

                try {
                    moveBackward();
                }

                catch (NumberFormatException e1) {
                    System.out.println("Invalid command");
                }
            }

            else if (userCommand.getText().equalsIgnoreCase("black")) {

                penColour = Color.BLACK;
                userCommand.setText("");
            }

            else if (userCommand.getText().equalsIgnoreCase("green")) {

                penColour = Color.GREEN;
                userCommand.setText("");

            }

            else if (userCommand.getText().equalsIgnoreCase("red")) {

                penColour = Color.RED;
                userCommand.setText("");
            }

            else if (userCommand.getText().equalsIgnoreCase("reset")) {

                graphics.clear();
                penX = 0;
                penY = 0;
                userCommand.setText("");
                graphics.repaint();

            }

            else if (userCommand.getText().equalsIgnoreCase("penUp")) {
                penUp();
                userCommand.setText("");
            }

            else if (userCommand.getText().equalsIgnoreCase("penDown")) {
                penDown();
                userCommand.setText("");
            }

        }
    }
}

GraphicsPanel: GraphicsPanel:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;


@SuppressWarnings("serial")
public class GraphicsPanel extends JPanel {

    /**
     * The default BG colour of the image.
     */
    private final static Color BACKGROUND_COL = Color.DARK_GRAY;

    /**
     * The underlying image used for drawing. This is required so any previous
     * drawing activity is persistent on the panel.
     */
    private BufferedImage image;

    public GraphicsPanel() {

        Dimension resolution = Toolkit.getDefaultToolkit().getScreenSize();

        int width = (int) resolution.getWidth(); // casting the screen width to
                                                    // integer
        int height = (int) resolution.getHeight(); // casting the scren height
                                                    // to integer

        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // Set max size of the panel, so that is matches the max size of the
        // image.
        setMaximumSize(new Dimension(image.getWidth(), image.getHeight()));

        clear();

    }

    public void drawLine(Color color, int x1, int y1, int x2, int y2) {

        Graphics g = image.getGraphics();
        g.setColor(color);
        g.translate(getWidth() / 2, getHeight() / 2);

        g.drawLine(x1, y1, x2, y2);
    }

    /**
     * Clears the image contents.
     */
    public void clear() {

        Graphics g = image.getGraphics();

        g.setColor(BACKGROUND_COL);

        g.fillRect(0, 0, image.getWidth(), image.getHeight());

    }

    @Override
    public void paint(Graphics g) {

        // render the image on the panel.
        g.drawImage(image, 0, 0, null);
    }

}   

Where possible I would also like to be able to add a scroller so that when my drawing goes outside of the graphicspanel it creates a scroller however adding a scroller didn't seem to work for that. 在可能的情况下,我还希望能够添加一个滚动条,以便当我的图形超出图形面板时,它会创建一个滚动条,但是添加滚动条似乎并没有用。

Any help and direction appreciated. 任何帮助和指导表示赞赏。

Edit: 编辑:

    item1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            clear();

        }

    });

Add an ActionListener (or use a lambda expression if you are on Java 8 or newer) to your new-button and there call the clear() method. 在您的new-button中添加一个ActionListener (或者,如果您使用的是Java 8或更高版本,则使用lambda表达式),然后调用clear()方法。

Besides that, you should not override paint() but paintComponent() . 除此之外,您不应覆盖paint()而应覆盖paintComponent()

And to get the JScrollPane working correctly, you need to set the preferred size of your panel, either by calling setPreferredSize() if the content sizes changes, or maybe by overriding getPreferredSize() . 为了使JScrollPane正常工作,您需要设置面板​​的首选大小,如果内容大小发生更改,可以通过调用setPreferredSize() ,或者可以通过重写getPreferredSize() Furthermore you need to get the JScrollPane to recalculate whether scrollbars are necessary after the preferred size of your panel changed, thus you have to call revalidate() on your panel after the preferred size changed. 此外,您需要获取JScrollPane来重新计算在更改面板的首选大小之后是否需要滚动条,因此,在更改了首选大小之后,必须在面板上调用revalidate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM