如何让我的MenuItems从单独的类中调用方法?

时间:2016-04-12 14:01:24

标签: java swing oop user-interface

我目前有一个包含三个不同类的项目。我有一个驱动程序类(main),一个GUI面板,其中包含所有按钮侦听器和gui组件,然后是第三个类,其中包含Graphics Panel所遵循的方法。

我想知道如何让我的JMenuItem“new”来调用我的GraphicsPanel类中的clear方法。

主要方法:

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:

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:

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

}   

在可能的情况下,我还希望能够添加一个滚动条,这样当我的绘图超出图形面板时,它会创建一个滚动条,但添加一个滚动条似乎不适合。

感谢任何帮助和指导。

编辑:

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

        }

    });

1 个答案:

答案 0 :(得分:1)

添加ActionListener(或使用lambda表达式,如果您使用的是Java 8或更高版本)到新按钮,然后调用clear()方法。

除此之外,您不应该覆盖paint(),而应覆盖paintComponent()

要使JScrollPane正常工作,您需要设置面板​​的首选尺寸,方法是在内容大小发生变化时调用setPreferredSize(),或者重写getPreferredSize()。此外,您需要让JScrollPane重新计算在更改面板首选尺寸后是否需要滚动条,因此您需要在首选尺寸更改后调用面板上的revalidate()