Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我需要能够覆盖图片和面板(一个数学公式)_Java_Swing - Fatal编程技术网

Java 我需要能够覆盖图片和面板(一个数学公式)

Java 我需要能够覆盖图片和面板(一个数学公式),java,swing,Java,Swing,我使用这个类使图像具有不同的状态。起初,图像是深灰色的(所以你看不见)。我希望图像是可点击的,一旦点击一个数学方程将出现。一旦方程得到解答,就会出现完整的图像。另外,我还有另一个类,它将图像分割成不同的部分。所以基本上所有这些独立的部分都继承了这个方法。这是一幅被分割成不同图像的图片(比如说4幅图像,这意味着4道数学题)。我该怎么做呢。我尝试了多种方法(我没有包括在这里面,因为它看起来像一个老鼠窝),但都没有成功。我已经尝试实现了mouseListener和overlylayout,但没有成功

我使用这个类使图像具有不同的状态。起初,图像是深灰色的(所以你看不见)。我希望图像是可点击的,一旦点击一个数学方程将出现。一旦方程得到解答,就会出现完整的图像。另外,我还有另一个类,它将图像分割成不同的部分。所以基本上所有这些独立的部分都继承了这个方法。这是一幅被分割成不同图像的图片(比如说4幅图像,这意味着4道数学题)。我该怎么做呢。我尝试了多种方法(我没有包括在这里面,因为它看起来像一个老鼠窝),但都没有成功。我已经尝试实现了
mouseListener
overlylayout
,但没有成功

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 * Makes the image have different states
 */
public class GPanel extends JPanel {
    private Image img;
    private boolean answered;
    private boolean working;
    private int w;
    private int h;
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public GPanel(Image img) {
        this.img = img;
        w = img.getWidth(this);
        h = img.getHeight(this);
        setPreferredSize(new Dimension(w, h));
        answered = false;
        working = false;
    }

    public void setAnswered() {
        answered = true;
    }

    public boolean getAnswered() {
        return answered;
    }

    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        if (!answered) {
            if (working){
                System.out.println("Run third");
                g2.setColor(Color.lightGray);
                g2.fillRect(0, 0, w, h);
                g2.setPaint(Color.yellow);
                g2.setFont(new Font("Sans-serif", Font.BOLD, 20));
                g2.drawString("Testing, one, two, three.", w/3, h/2);
                ((JFrame)SwingUtilities.getRoot(this)).setTitle("Testing, one, two, three.");
            }
            else{
                System.out.println("Run first");
                g2.setColor(Color.darkGray);
                g2.fillRect(0, 0, w, h);
            }
            working = !working;  // toggles on and off
        } else {
            System.out.println("Run second");
            g2.drawImage(img, 0, 0, this);
            ((JFrame)SwingUtilities.getRoot(this)).setTitle("Testing GPanel");
        }
        answered = !answered; // toggles on and off 
    }
}

如果您只需要交换图像,那么最简单的方法就是将图像显示为JLabel中的图像图标。要交换JLabel的图标,只需在JLabel上调用
setIcon(newIcon)
。例如,假设我们在一个图标列表(
ArrayList
)中有四个图像,这个ArrayList变量被称为Icons,假设您的程序有一个名为iconIndex的int变量,它保存当前显示图像的索引号,那么通过增加索引变量来交换图像很简单,并使用它来获取列表中的下一个图标。比如:

iconIndex++;   // increment the index variable
iconIndex %= icons.size();  // if larger than size of list, set to 0
Icon icon = icons.get(iconIndex); // get icon from list
imageLabel.setIcon(icon); // set the JLabel's icon with it
这个代码可能在一个MouseListener中,一个添加到JLabel中,然后您就完成了。请注意,逻辑代码在MouseListener中。因此,如果用户在切换图像之前必须执行任何其他操作,则会在同一鼠标侦听器中检查图像

例如:

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

@SuppressWarnings("serial")
public class DifferentImages extends JPanel {
    private static final int IMG_W = 400;
    private static final int IMG_H = IMG_W;
    private static final Font TEXT_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 40);
    private JLabel imageLabel = new JLabel();
    private List<Icon> icons = new ArrayList<>();
    private int iconIndex = 0;

    public DifferentImages() {
        // create images and icons
        Icon icon = getIcon(Color.DARK_GRAY, Color.LIGHT_GRAY, "First Image");        
        icons.add(icon);
        icon = getIcon(Color.BLUE, new Color(137, 207, 240), "Second Image");
        icons.add(icon);
        icon = getIcon(Color.RED, Color.PINK, "Third Image");
        icons.add(icon);
        icon = getIcon(Color.YELLOW, Color.ORANGE, "Fourth Image");
        icons.add(icon);        

        imageLabel.setIcon(icons.get(iconIndex));        
        add(imageLabel);

        imageLabel.addMouseListener(new MyMouse());
    }

    // MouseListener that is added to JLabel
    private class MyMouse extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            // code here to check if it is OK to swap images
            // and if so, then swap them:
            iconIndex++;   // increment the index variable
            iconIndex %= icons.size();  // if larger than size of list, set to 0
            Icon icon = icons.get(iconIndex); // get icon from list
            imageLabel.setIcon(icon); // set the JLabel's icon with it
        }
    }

    // just creates an image icon for demo purposes, one with color and text
    private Icon getIcon(Color bg, Color fb, String text) {
        BufferedImage img = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = img.createGraphics();
        g2.setColor(bg); // first a dark image
        g2.fillRect(0, 0, IMG_W, IMG_H);
        g2.setColor(fb);
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setFont(TEXT_FONT);
        FontMetrics fontMetrics = g2.getFontMetrics(TEXT_FONT);
        int textWidth = fontMetrics.stringWidth(text);
        int x = (IMG_W - textWidth) / 2;
        int y = (IMG_H) / 2;
        g2.drawString(text, x, y);
        g2.dispose();
        Icon icon = new ImageIcon(img);
        return icon;
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("DifferentImages");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DifferentImages());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
导入java.awt.Color;
导入java.awt.Font;
导入java.awt.FontMetrics;
导入java.awt.Graphics2D;
导入java.awt.RenderingHints;
导入java.awt.event.MouseAdapter;
导入java.awt.event.MouseEvent;
导入java.awt.image.buffereImage;
导入java.util.ArrayList;
导入java.util.List;
导入javax.swing.*;
@抑制警告(“串行”)
公共类差异估计扩展了JPanel{
专用静态最终int IMG_W=400;
专用静态最终int IMG_H=IMG_W;
私有静态最终字体文本\u Font=新字体(Font.SANS\u SERIF,Font.BOLD,40);
私有JLabel imageLabel=新的JLabel();
私有列表图标=新的ArrayList();
私有整数指数=0;
公共差异(){
//创建图像和图标
Icon Icon=getIcon(Color.DARK_GRAY,Color.LIGHT_GRAY,“第一张图像”);
图标。添加(图标);
icon=getIcon(Color.BLUE,新颜色(137、207、240),“第二个图像”);
图标。添加(图标);
icon=getIcon(Color.RED、Color.PINK,“第三幅图像”);
图标。添加(图标);
icon=getIcon(Color.YELLOW,Color.ORANGE,“第四幅图像”);
图标。添加(图标);
imageLabel.setIcon(icons.get(iconIndex));
添加(图像标签);
addMouseListener(新的MyMouse());
}
//添加到JLabel的鼠标侦听器
私有类MyMouse扩展了MouseAdapter{
@凌驾
公共无效鼠标按下(MouseEvent e){
//在此处编写代码以检查是否可以交换图像
//如果是,则交换:
iconIndex++;//递增索引变量
iconIndex%=icons.size();//如果大于列表的大小,则设置为0
Icon Icon=icons.get(iconIndex);//从列表中获取图标
imageLabel.setIcon(icon);//使用它设置JLabel的图标
}
}
//只需创建一个用于演示目的的图像图标,一个带有颜色和文本的图标
私有图标getIcon(彩色背景、彩色fb、字符串文本){
BuffereImage img=新的BuffereImage(img_W,img_H,buffereImage.TYPE_INT_ARGB);
Graphics2D g2=img.createGraphics();
g2.setColor(bg);//首先是一个暗图像
g2.fillRect(0,0,IMG_W,IMG_H);
g2.setColor(fb);
g2.setRenderingHint(RenderingHits.KEY\u TEXT\u ANTIALIAS,RenderingHits.VALUE\u TEXT\u ANTIALIAS\u ON);
g2.设置字体(文本字体);
FontMetrics FontMetrics=g2.getFontMetrics(文本字体);
int textWidth=fontMetrics.stringWidth(文本);
int x=(IMG_W-textWidth)/2;
int y=(IMG_H)/2;
g2.抽绳(文本,x,y);
g2.dispose();
图标图标=新图像图标(img);
返回图标;
}
私有静态void createAndShowGui(){
JFrame=新的JFrame(“差异化”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(新的DifferentImages());
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
公共静态void main(字符串[]args){
调用器(()->createAndShowGui());
}
}

您的paintComponent方法中有更改对象状态的代码,这是您想要避免的,因为您永远无法完全控制何时或是否调用此方法。相反,更改别处的逻辑以响应您需要侦听的任何事件,调用“重新绘制”,然后仅使用paintComponent来显示这些状态更改的视觉结果。@HovercraftFullOfEels您指的是它显示“打开和关闭”的位置吗我的逻辑是使方法返回工作状态,并回答正确和错误。因此,删除当前的
应答=!回答;//打开和关闭
工作=!工作;//切换开关
,但我只是不知道如何让鼠标听筒工作。而且也不知道在这个
GPanel
类中我的数学方程面板添加到哪里。不,我不需要交换图像。基本上,用户选择一个图像,一旦选择,该图像将被分割成不同的部分。在每个单独的部分下都有一个用户必须回答的数学方程。首先,图像是