添加时移除图像的组件

Posted

技术标签:

【中文标题】添加时移除图像的组件【英文标题】:Component removing images when added 【发布时间】:2014-02-25 12:04:26 【问题描述】:

我目前在使用 JFrame 和图像时遇到问题。该程序使用 Applet,然后将其添加到不同类的 JFrame 中,因此它可以作为 Applet 或应用程序运行。目前,该框架仅包含少量图像,并且没有组件。我最近尝试使用绝对定位(LayoutManger 为空)添加一个 JTextField,它工作正常,除了所有图像都被删除,只剩下一个 JTextField。为什么会这样?我该如何解决?我的代码发布在下面。谢谢!

主类(创建小程序和图像):

package net.xenix.src;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JComponent;
import javax.swing.Timer;

public class XenixMain extends JApplet implements ActionListener

private static final long serialVersionUID = 1L;

private static int pixelSize = 2;

public static Dimension size = new Dimension(1600, 900);
public static Dimension pixel = new Dimension(size.width / pixelSize, size.height /         pixelSize);

public static String name = "Xenix";

public static final int WIDTH = 1600;
public static final int HEIGHT = 900;

//Finding player Windows name
static String username = System.getProperty("user.name");

public static int secondsCount = 0;

//Shortcut to image directory
public static String imagePath = "C:\\Users\\" + username + "\\Desktop\\Xenix Dev\\Xenix\\resources\\graphics\\";

private static PaintSurface canvas;

public static ImageIcon XenixBackgroundIcon = new ImageIcon(imagePath + "XenixBackground.png");
public static Image XenixBackground = XenixBackgroundIcon.getImage();

public static ImageIcon XenixLogoIcon = new ImageIcon(imagePath + "XenixLogo.png");
public static Image XenixLogo = XenixLogoIcon.getImage();

public static ImageIcon HeartContainerFullIcon = new ImageIcon(imagePath + "HeartContainerFull.png");
public static Image HeartContainerFull = HeartContainerFullIcon.getImage();

public static ImageIcon HeartContainer9Icon = new ImageIcon(imagePath + "HeartContainer9.png");
public static Image HeartContainer9 = HeartContainer9Icon.getImage();

public static ImageIcon HeartContainer8Icon = new ImageIcon(imagePath + "HeartContainer8.png");
public static Image HeartContainer8 = HeartContainer8Icon.getImage();

public static ImageIcon HeartContainer7Icon = new ImageIcon(imagePath + "HeartContainer7.png");
public static Image HeartContainer7 = HeartContainer7Icon.getImage();

public static ImageIcon HeartContainer6Icon = new ImageIcon(imagePath + "HeartContainer6.png");
public static Image HeartContainer6 = HeartContainer6Icon.getImage();

public static ImageIcon HeartContainer5Icon = new ImageIcon(imagePath + "HeartContainer5.png");
public static Image HeartContainer5 = HeartContainer5Icon.getImage();

public static ImageIcon HeartContainer4Icon = new ImageIcon(imagePath + "HeartContainer4.png");
public static Image HeartContainer4 = HeartContainer4Icon.getImage();

public static ImageIcon HeartContainer3Icon = new ImageIcon(imagePath + "HeartContainer3.png");
public static Image HeartContainer3 = HeartContainer3Icon.getImage();

public static ImageIcon HeartContainer2Icon = new ImageIcon(imagePath + "HeartContainer2.png");
public static Image HeartContainer2 = HeartContainer2Icon.getImage();

public static ImageIcon HeartContainer1Icon = new ImageIcon(imagePath + "HeartContainer1.png");
public static Image HeartContainer1 = HeartContainer1Icon.getImage();

public static ImageIcon HeartContainerDepletedIcon = new ImageIcon(imagePath + "HeartContainerDepleted.png");
public static Image HeartContainerDepleted = HeartContainerDepletedIcon.getImage();

public static ImageIcon HealthTextIcon = new ImageIcon(imagePath + "HealthText.png");
public static Image HealthText = HealthTextIcon.getImage();

public static ImageIcon ForwardSlashIcon = new ImageIcon(imagePath + "ForwardSlash.png");
public static Image ForwardSlash = ForwardSlashIcon.getImage();

public Timer timer = new Timer(1000, this);

public void start()

    timer.setInitialDelay(0);
    timer.start(); 


public void stop()

    timer.stop();


public void actionPerformed(ActionEvent e)

    secondsCount++;

    System.out.println(secondsCount);


public void init()

    this.setSize(WIDTH, HEIGHT);
    canvas = new PaintSurface();
    this.add(canvas, BorderLayout.CENTER);

    ScheduledThreadPoolExecutor executor = 
        new ScheduledThreadPoolExecutor(3);
    executor.scheduleAtFixedRate(
        new AnimationThread(this), 
        0L, 20L, TimeUnit.MILLISECONDS);



class AnimationThread implements Runnable   

JApplet c;

public AnimationThread(JApplet c)


    this.c = c;


public void run()

    c.repaint();



class PaintSurface extends JComponent

private static final long serialVersionUID = 1L;

public void paint(Graphics g)

    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(
        RenderingHints.KEY_ANTIALIASING, 
        RenderingHints.VALUE_ANTIALIAS_ON);

    Shape screenDisplay = new Rectangle2D.Float(
            450, 175, 700, 500);

        g2.setColor(Color.DARK_GRAY);
        g2.fill(screenDisplay);

    /*
     * START TITLE SCREEN CREATION
     */

    if(XenixMain.secondsCount > 0)
    
        g.drawImage(XenixMain.XenixLogo, 500, 500, this);
    


    g.drawImage(XenixMain.XenixBackground, 0, 0, this);


    /*
     * END TITLE SCREEN CREATION
     */
    
 

JFrame 类(创建 JFrame 并添加小程序):

package net.xenix.src ;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class XenixApplicationWindow extends JFrame

private static final long serialVersionUID = 1L;

static XenixMain xenix = new XenixMain();

static ImageIcon xenixIcon = new ImageIcon(XenixMain.imagePath + "XenixIcon.png");

public static void main(String[] args)

    new XenixApplicationWindow();


public XenixApplicationWindow()

    JFrame frame = new JFrame();
    JTextField userInput = new JTextField(15);
    JPanel panel1 = new JPanel(null);
    frame.add(xenix);
    frame.setSize(1600, 900);
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setResizable(true);
    frame.setIconImage(xenixIcon.getImage());
    userInput.setBounds(0, 0, 120, 10);
    panel1.add(userInput);
    frame.add(panel1);

    frame.setContentPane(panel1);

    frame.setLocationRelativeTo(null);
    frame.setTitle("Xenix");

    xenix.init();
    xenix.start();

    frame.setVisible(true);


【问题讨论】:

JApplet 很可能是不透明的,另一个问题是你混合了重量级和重量级的组件,这会出现 z 顺序问题。更好的解决方案是将应用程序逻辑与容器分离,这样您就可以简单地在***容器之间移动它......您还应该知道小程序具有非常严格的权限,这意味着它不太可能拥有访问权限到本地驱动器 "..我最近尝试使用绝对定位添加 JTextField(LayoutManger 为空),它工作正常,除了所有图像都被删除了" 你有一个奇怪的定义'工作正常'。 好吧,我之前使用过绝对定位,没有任何问题。直到最近才发生这种情况。不确定这是我的班级设置还是什么。我认为这与定位无关。 提示:1) 添加@MadProgrammer(或任何人 - @ 很重要)以通知他们有新评论。 2) 尝试在两台或多台机器上、在可调整大小的 GUI 中的 2 个或更多 PLAF 中测试您的“工作正常”空布局。 3) 不要向皈依者传道。 (布局规则)。 4) 为了尽快获得更好的帮助,请发帖Minimal Complete Tested and Readable Example (MCTRE)。 @MadProgrammer,你能编辑我的代码并告诉我你的意思吗?我在理解上有困难,一个直观的例子真的很有帮助。 【参考方案1】:

看看这个例子,看看这是否有帮助。有关上述主题的一些信息,请参阅link。如果还有不清楚的地方,请告诉我。

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

public class BackgroundExample 

    private JTextField tField;
    private JButton button;

    private CustomPanel contentPane;

    private void displayGUI() 
        JFrame frame = new JFrame("Background Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        contentPane = new CustomPanel();
        contentPane.setLayout(new GridBagLayout());

        JPanel componentPanel = new JPanel();
        componentPanel.setOpaque(false);
        tField = new JTextField("Nothing to display yet...", 20);
        button = new JButton("Click me not!");
        componentPanel.add(tField);
        componentPanel.add(button);

        contentPane.add(componentPanel);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    

    public static void main(String[] args) 
        Runnable runnable = new Runnable() 
            @Override
            public void run() 
                new BackgroundExample().displayGUI();
            
        ;
        EventQueue.invokeLater(runnable);
    


class CustomPanel extends JPanel 

    private BufferedImage bImage;

    public CustomPanel() 
        try 
            bImage = ImageIO.read(new URL("http://i.imgur.com/fHiBMwI.jpg"));
         catch (IOException ioe) 
            ioe.printStackTrace();
        
    

    @Override
    public Dimension getPreferredSize() 
        return (bImage != null ? new Dimension(
            bImage.getWidth(), bImage.getHeight()) : new Dimension(400, 400));
    

    @Override
    protected void paintComponent(Graphics g) 
        super.paintComponent(g);
        g.drawImage(bImage, 0, 0, this);
    

【讨论】:

@NicholasCreech : 你是最欢迎和保持微笑 :-) 只是要记住一点,以前程序访问图像的方式,如果程序转移到其他计算机,而不是图像必须放在桌面上指定的上述位置,但在此示例中,当您创建 jar 文件时,不会发生这种情况。

以上是关于添加时移除图像的组件的主要内容,如果未能解决你的问题,请参考以下文章

在外面点击时移除视图

在 UITableView 中滚动时移除 UIView

在框架外点击时移除视图

Jetpack 之 LiveData

遍历 NodeList 时移除 DOM 节点

android EditText,单击另一个对象时移除焦点