简体   繁体   English

JAVA。 JFrame中的背景图片,drawString,JButton和JComboBox

[英]JAVA. Background image, drawString, JButton and JComboBox in a JFrame

I'm new at working with JFrames. 我是使用JFrames的新手。 So I dont really know how to draw/paint/display everything in a JFrame. 所以我真的不知道如何在JFrame中绘制/绘制/显示所有内容。 Im working on a memory game. 我正在做一个记忆游戏。 Currently im working at the first form, this form must display a background image, a welcome text, a dropdown list with the amount of cards for the memory game and a button which should start the game. 当前在第一种形式上起作用,该形式必须显示背景图像,欢迎文本,带有内存游戏卡数量的下拉列表以及应启动游戏的按钮。 I succesfully displayed the background image and the welcome text. 我成功显示了背景图片和欢迎文本。 After adding the JButton and combobox my form got messed up (I only see a blue background). 添加JButton和combobox之后,我的表单变得混乱了(我只看到一个蓝色背景)。 I have no idea what im doing wrong, also I dont know how I can place the button and dropdown on the right x and y position. 我不知道我在做什么错,我也不知道如何将按钮和下拉菜单放在正确的x和y位置。 I want to place the dropdown box under the welcome text and the button to the right of the dropdownbox. 我想将下拉框放置在欢迎文本和下拉框右侧的按钮下面。

This is my code: 这是我的代码:

Main: 主要:

package Memory;

public class Main {

    public static Memory memory;

    public static void main(String[] args) {
    memory = new Memory();
    }
}

Renderer: 渲染器:

package Memory;

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

public class Renderer extends JPanel {

    private static final long serialVersionUID = 1L;

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Memory.backImage = new ImageIcon("Memory/memoryGame.jpg");
        Main.memory.repaint(g);

    }
}

Memory: 记忆:

package Memory;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.*;
import javax.imageio.*;
import java.awt.FlowLayout;



public class Memory implements ActionListener {

    public String[] amountOfCards = {"8","16","32"};

    private JButton startButton;

    public Renderer renderer;

    public static ImageIcon backImage;
    public boolean screen1;

    public static final int WORLD_WIDTH=1250, WORLD_HEIGHT=800;

    public Memory() { 

    JComboBox comboBox = new JComboBox(amountOfCards);
    comboBox.setSelectedIndex(1);
    startButton = new JButton("Start game");


    JFrame jframe = new JFrame();
    Timer timer = new Timer(20,this);
    renderer = new Renderer();

    jframe.add(renderer);
    jframe.setTitle("Memory game");
    jframe.setSize(WORLD_WIDTH,WORLD_HEIGHT);
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jframe.setResizable(false);jframe.add(startButton);
    jframe.add(comboBox);
    jframe.setVisible(true);

    screen1=true;

    timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

    renderer.repaint();

    }

    public void repaint(Graphics g) {

        //welcome screen
        if(screen1) {
            BufferedImage scaledImage = getScaledImage();
            g.drawImage(scaledImage, 0, 0, null);

            g.setColor(new Color(150, 196, 100));
            g.setFont(new Font("TimesRoman", Font.PLAIN, 75));
            g.drawString("MEMORY GAME", WORLD_WIDTH / 2 - 275, 100);

            g.setFont(new Font("TimesRoman", Font.PLAIN, 25));
            g.drawString("Please select the amount of cards u want to play with and start the game!", WORLD_WIDTH / 2 -400, 200);


        }

    }

    public BufferedImage getScaledImage() {
        BufferedImage image = new BufferedImage(WORLD_WIDTH,WORLD_HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = (Graphics2D) image.createGraphics();
        g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
        g2d.drawImage(backImage.getImage(), 0, 0,WORLD_WIDTH,WORLD_HEIGHT, null);

        return image;
    }

}

Alright, multiple errors in a first view of your code 好吧,在您的代码的第一个视图中出现多个错误

  1. public static Memory memory; : That line, having static and being a public member of class will harm you a lot ! :那条路线,保持static并成为班上的public成员会对您造成很大伤害! Why? 为什么? Because your memory variable is the same for all the instances you create, because it's a "Class variable" not an "instance variable", and being public is going against the convention and security reasons. 因为您创建的所有实例的memory变量都是相同的,所以它是“类变量”而不是“实例变量”,并且public是违反约定和安全性的原因。 For reference see: What does the 'static' keyword do in a class? 作为参考,请参见: “ static”关键字在类中做什么? and Why use getters and setters? 为什么使用吸气剂和吸气剂?

  2. From the above point, static is not a "magic cross method / class" word that allows you to use variables through classes or with main and other methods... and thus this line public static ImageIcon backImage; 从上面的观点来看, static不是一个“魔术交叉方法/类”一词,它使您可以通过类或与main和其他方法一起使用变量。因此,这行public static ImageIcon backImage; and this one: Memory.backImage = new ImageIcon("Memory/memoryGame.jpg"); 而这个: Memory.backImage = new ImageIcon("Memory/memoryGame.jpg"); shouldn't exist. 不应该存在。 And the same for this one: Main.memory.repaint(g); 与此相同: Main.memory.repaint(g);

  3. That being said, you should NEVER NEVER NEVER EVER!!! 话虽如此,你永远永远永远永远不要!!! override repaint() method, all of that code should be into the paintComponent(...) mehtod! 覆盖repaint()方法,所有这些代码都应该放入paintComponent(...)方法中!

  4. Also it is wise to treat images as embedded resources, because, once you export your program as a JAR file, they will become embedded resources, it's better to treat them like if they already were, here you can find information about how to change your program accordingly. 将图像视为嵌入式资源也是明智的,因为一旦将程序导出为JAR文件,它们就会成为嵌入式资源,最好像对待它们一样对待它们, 在这里您可以找到有关如何更改自己的信息。相应地进行编程。

Try and set your ImageIcon BackImage from public static, to public. 尝试将ImageIcon BackImage从public static设置为public。 Also, try and write the jframe.setVisible(true); 另外,尝试编写jframe.setVisible(true);。 command after timer.start() timer.start()之后的命令

note that setting your JFrame to visible, before completing every initialisation, might lead to unwanted behaviour of your program. 请注意 ,在完成每次初始化之前,将JFrame设置为可见可能会导致程序不必要的行为。

To set the position of your button on the screen, after adding your JButton to your JFrame, you can use: startButton.setLocation(x,y); 要在屏幕上设置按钮的位置,请在将JButton添加到JFrame之后,可以使用: startButton.setLocation(x,y);

After you play a little bit with the coordinates of your window, you'll get the spot you want for your JButton. 在使用窗口坐标稍作调整后,您将获得想要的JButton位置。 Keep in mind that (0,0) is usually the upper left corner of your JFrame. 请记住,(0,0)通常是JFrame的左上角。

Be careful when using static variables in your program. 在程序中使用静态变量时要小心。 There seems to be no reason in setting your Memory class, your width and height variables as static. 似乎没有理由将您的Memory类,宽度和高度变量设置为静态。

For more information regarding this, check out this post: Why are static variables considered evil? 有关此的更多信息,请查看这篇文章: 为什么静态变量被认为是邪恶的?

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

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