java - 单击java中的菜单项时如何更改形状和颜色

标签 java swing colors awt paintcomponent

我无法更改特定形状的颜色。但是当用户单击某个菜单项时,它会成功更改为另一种形状。现在的问题是我想不出一种解决方案来解决这个问题。谁可以帮我这个事?非常感谢帮助。谢谢。

    @Override
    public void paintComponent(Graphics shapes)
    {
        super.paintComponent(shapes);
        switch(colorNo)
        {
            case 0 : color = Color.RED;break;
            case 1 : color = Color.BLUE;break;
            case 2 : color = Color.MAGENTA;break;
        }
        switch(numbers)
        {
            case 0 : circle(shapes);break;
            case 1 : rectangle(shapes);break;
            case 2 : square(shapes);break;
            case 3 : triangle(shapes);break;
        }  
    }

    public void circle(Graphics shapes)
    {
        shapes.setColor(color);
        shapes.fillOval(250,100, 100, 100);
    }


    @Override
    public void actionPerformed(ActionEvent click) {
        if(click.getSource() == circle){
            numbers = 0;
            repaint();
        }else if(click.getSource() == square){
            numbers = 1; repaint();
        }else if(click.getSource() == rectangle){
            numbers = 2; repaint();
        }else if(click.getSource() == triangle){
            numbers = 3; repaint();
        }
        if(click.getSource() == red){
            colorNo = 0; repaint();
        }

    }

最佳答案

简单——在你的paintComponent方法中,在你的父类的paintComponent调用之后,在你设置形状的switch语句之前,设置Graphics对象的颜色,在与设置形状的方式相同。当然,您必须为每个颜色菜单项添加一个监听器才能使其工作。

如果您使用 AbstractActions 而不是让所有内容共享同一个 ActionListener,那么会更加更容易、更干净。例如,这段代码并不完全符合您想要做的事情,但它可以给您一些想法。

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

import javax.swing.*;


public class MyShapes extends JPanel {
    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    private JMenuBar menuBar = new JMenuBar();
    private Color color = Color.WHITE;

    public MyShapes() {
        JMenu colorMenu = new JMenu("Color");
        colorMenu.add(new JMenuItem(new ColorAction("Black", Color.BLACK)));
        colorMenu.add(new JMenuItem(new ColorAction("White", Color.WHITE)));
        colorMenu.add(new JMenuItem(new ColorAction("Red", Color.RED)));
        colorMenu.add(new JMenuItem(new ColorAction("Blue", Color.BLUE)));
        colorMenu.add(new JMenuItem(new ColorAction("Green", Color.GREEN)));
        menuBar.add(colorMenu);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(color);
        g.fillRect(0, 0, getWidth(), getHeight());
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    public JMenuBar getMenuBar() {
        return menuBar;
    }

    private class ColorAction extends AbstractAction {
        private Color actionColor;

        public ColorAction(String name, Color color) {
            super(name);
            this.actionColor = color;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            color = actionColor;
            repaint();
        }
    }

    private static void createAndShowGui() {
        MyShapes mainPanel = new MyShapes();

        JFrame frame = new JFrame("MyShapes");
        frame.setJMenuBar(mainPanel.getMenuBar());
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

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

请注意,您可以用相同的方式绘制形状 - 通过在菜单项的操作的 actionPerformed 方法中填充变量。只是这一次变量是 DrawShape 接口(interface)类型,并将其用于其方法,这里是public void draw(Graphics g)。这种类型的程序设计模式称为 Command Pattern 。例如:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class MyShapes extends JPanel {
    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    private JMenuBar menuBar = new JMenuBar();
    private Color color = null;
    public DrawShape drawShape = null;

    public MyShapes() {
        // create and fill colorMenu
        JMenu colorMenu = new JMenu("Color");
        colorMenu.add(new JMenuItem(new ColorAction("Black", Color.BLACK)));
        colorMenu.add(new JMenuItem(new ColorAction("White", Color.WHITE)));
        colorMenu.add(new JMenuItem(new ColorAction("Red", Color.RED)));
        colorMenu.add(new JMenuItem(new ColorAction("Blue", Color.BLUE)));
        colorMenu.add(new JMenuItem(new ColorAction("Green", Color.GREEN)));

        // create and fill shapeMenu
        JMenu shapeMenu = new JMenu("Shape");
        shapeMenu.add(new JMenuItem(new DrawShapeAction("Square", new DrawShape() {

            @Override
            public void draw(Graphics g) {
                int x = getWidth() / 4;
                int y = getHeight() / 4;
                int width = getWidth() / 2;
                int height = getHeight() / 2;
                g.fillRect(x, y, width, height);
            }
        })));
        shapeMenu.add(new JMenuItem(new DrawShapeAction("Circle", new DrawShape() {

            @Override
            public void draw(Graphics g) {
                int x = getWidth() / 4;
                int y = getHeight() / 4;
                int width = getWidth() / 2;
                int height = getHeight() / 2;
                g.fillOval(x, y, width, height);
            }
        })));
        shapeMenu.add(new JMenuItem(new DrawShapeAction("Triangle", new DrawShape() {

            @Override
            public void draw(Graphics g) {
                int[] x = new int[3];
                int[] y = new int[3];
                x[0] = getWidth() / 4;
                x[1] = getWidth() / 2;
                x[2] = 3 * getWidth() / 4;
                y[0] = 3 * getHeight() / 4;
                y[1] = getHeight() / 4;
                y[2] = y[0];
                Polygon polygon = new Polygon(x, y, 3);
                g.fillPolygon(polygon);
            }
        })));

        // add both JMenus to the JMenuBar
        menuBar.add(colorMenu);
        menuBar.add(shapeMenu);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // if either color or drawShape are not set, exit this method and draw nothing
        if (color == null || drawShape == null) {
            return;
        }

        // to smooth out the edges
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // set color and call drawShape's draw method
        g.setColor(color);
        drawShape.draw(g);
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    public JMenuBar getMenuBar() {
        return menuBar;
    }

    private class ColorAction extends AbstractAction {
        private Color actionColor;

        public ColorAction(String name, Color color) {
            super(name);
            this.actionColor = color;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            MyShapes.this.color = actionColor;
            repaint();
        }
    }

    private class DrawShapeAction extends AbstractAction {
        private DrawShape actionDrawShape;

        public DrawShapeAction(String name, DrawShape drawShape) {
            super(name);
            this.actionDrawShape = drawShape;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            MyShapes.this.drawShape = actionDrawShape;
            repaint();
        }
    }

    private interface DrawShape {
        void draw(Graphics g);
    }

    private static void createAndShowGui() {
        MyShapes mainPanel = new MyShapes();

        JFrame frame = new JFrame("MyShapes");
        frame.setJMenuBar(mainPanel.getMenuBar());
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

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

关于java - 单击java中的菜单项时如何更改形状和颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35019623/

相关文章:

Java:String intern() 和 StringPool 究竟是如何工作的?

java - Jcombobox,当选择某个项目时,显示一个值

android - 如何获取android TextView的默认文本颜色?

javascript - 如何生成特定颜色的随机阴影列表? (例如随机的橙色阴影)

c++ - 颜色转移 : What's wrong with my code in OpenCV C++

java - 如何在三星手机上安装 Java ME 应用程序?

java - Hibernate 和存储过程

java - TestNG - 在测试类之间共享状态

swing - Jframe 窗口无法使用我的可执行 jar 打开

java - 如何将重复背景图像设置为 JPanel?