简体   繁体   English

如何在Java Swing中在屏幕上切换形状?

[英]How can I toggle shapes on and off screen in Java Swing?

Okay so I am trying to build a program using swing in which I have to to be able to draw an oval and rectangle in the bottom right corner of the screen. 好的,所以我试图使用秋千构建一个程序,其中必须能够在屏幕的右下角绘制一个椭圆形和矩形。 I am currently trying to use a prior program in which the program starts and stops a square using JToggleSwitch. 我目前正在尝试使用以前的程序,其中该程序使用JToggleSwitch启动和停止正方形。 My Question is How can i get a shape to toggle on and off the screen since it needs a parameter "Graphics g". 我的问题是,由于它需要参数“ Graphics g”,我如何才能获得在屏幕上切换的形状。 Here is my PaintPanel code so far. 到目前为止,这是我的PaintPanel代码。

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

public class PaintPanel extends JPanel
{
    private static Color[] colors =
        { Color.RED, Color.BLACK, Color.PINK, Color.ORANGE };
    private int colorNumber = 0;

    private int shape = 0;

    private int x = 0;
    private int y = 0;

    private int width = 100;
    private int height = 100;

    private int dx = 2;
    private int dy = 2;

    private String displayString = "hello";

    private boolean isStarted = true;

    public void update()
    {
        if (isStarted) 
        {
            x += dx;
            y += dy;
        }
        //dx ++;
        //dy ++;

        if (y + height > getHeight())
        {
            dy = -Math.abs(dy);
            shape++;
            colorNumber = (colorNumber+1)%colors.length;
        }
        else if (y < 0)
        {
            dy = Math.abs(dy);
            shape++;
            colorNumber = (colorNumber+1)%colors.length;
        }

        if (x + width > getWidth())
        {
            dx = -Math.abs(dx);
            shape++;
            colorNumber = (colorNumber+1)%colors.length;
        }
        else if (x < 0)
        {
            dx = Math.abs(dx);
            shape++;
            colorNumber = (colorNumber+1)%colors.length;
        }

    }

    public void changeColor()
    {
        colorNumber = (colorNumber+1) % colors.length;
    }

    public void startStop()
    {
        //if (isStarted == true) isStarted = false;
        //else isStarted = true;

        isStarted = !isStarted;
    }

    public void setDisplayText(String dt)
    {
        displayString = dt;
    }
    public void paintRectangle(Graphics g)
    {

        int w = getWidth();
        int h = getHeight();
        g.setColor(Color.PINK);
        g.fillRect(w/2, h/2, w/2, h/2);
        //g.setColor(Color.CYAN);
        //g.fillOval((5*w)/8, (5*h)/8, w/4, h/4);


    }


    public void paintComponent(Graphics g)
    {



        int w = getWidth();
        int h = getHeight();
        g.setColor(colors[colorNumber]);
        if (shape % 2 == 0) //g.fillOval(x, y, width, height);
        /*else*/ g.fillRect(x,y, width, height);


        int textx = x+width/2;
        int texty = y+height/2;

        FontMetrics fm = g.getFontMetrics();
        int texth = fm.getHeight();
        int textw = fm.stringWidth(displayString);

        textx -= textw/2;
        texty += texth/2;
        texty -= 5;     

        g.setColor(colors[(colorNumber+1)%colors.length]);
        g.drawString(displayString, textx, texty);
    }

}

And here is the actual code that creates the window and panel. 这是创建窗口和面板的实际代码。 This is my main class. 这是我的主班。

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

public class GuiTest extends JFrame 
    implements ActionListener
{
    private Timer frameTimer;
    private JToggleButton name;
    private JToggleButton ovalButton;
    private JToggleButton rectangle;
    //private JTextField theText;
    private PaintPanel paintPanel;

    public GuiTest()
    {
        setTitle("Servando Hernandez");
        setSize(500,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new GridLayout(1,3));

        name = new JToggleButton("Name");
        name.addActionListener(this);

        ovalButton = new JToggleButton("Oval");
        ovalButton.addActionListener(this);

        rectangle = new JToggleButton("Rectangle");
        rectangle.addActionListener(this);

        //theText = new JTextField("HI");
        //theText.addActionListener(this);


        topPanel.add(name);
        topPanel.add(ovalButton);
        topPanel.add(rectangle);
        //topPanel.add(theText);

        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(topPanel, BorderLayout.SOUTH);

        paintPanel = new PaintPanel();
        contentPane.add(paintPanel, BorderLayout.CENTER);

        frameTimer = new Timer(50, this);
        frameTimer.start();
    }

    public void actionPerformed(ActionEvent e)
    {
        //System.out.println("Action performed");
        if (e.getSource() == name)      
        {
            paintPanel.changeColor();
        }
        else if (e.getSource() == frameTimer)
        {
            paintPanel.update();
        }
        else if (e.getSource() == ovalButton)
        {
            //System.out.println("start/stop");
            paintPanel.startStop();
        }
        else if (e.getSource() == rectangle)
        {

        }
        /*else if (e.getSource() == theText)
        {
            String text = e.getActionCommand();
            paintPanel.setDisplayText(text);
            //System.out.println(text);
        }
        */
        repaint();
    }

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

    }
}

You could... 你可以...

Maintain a List of Shape s which are to be painted, adding or removing them as needed. 维护要绘制的Shape List ,根据需要添加或删除它们。 You would then loop through the list in the paintComponent method, painting what ever was in the List and simply calling repaint when you want the component updated 然后,您可以在paintComponent方法中遍历列表,绘制List并在需要更新组件时简单地调用repaint

You could... 你可以...

Have a series of boolean (or other types of) flags which dictates which shapes are to be painted. 具有一系列boolean (或其他类型的)标志,这些标志指示要绘制的形状。 This kind of fixes what shapes are available to be painted and doesn't really allow you to control the z-order of the shapes 这种类型的修复可以绘制哪些形状,并且实际上不允许您控制形状的z顺序

You should... 你应该...

Be calling super.paintComponent before you do any custom painting, otherwise you are likely to produce unwanted paint artifacts each time the component is painted. 在进行任何自定义绘制之前,请先调用super.paintComponent ,否则每次绘制该组件时,您可能会生成不需要的绘制工件。 Remember, painting is destructive and when paintComponent is called, you should completely repaint the current state of the component 请记住,绘画是破坏性的,当调用paintComponent时,您应该完全重新绘制组件的当前状态。

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

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