且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JPanel图像背景与其他JPanel重叠

更新时间:2023-12-05 08:17:10

因此,我正在尝试编写您的代码的正面和反面...

So, I'm trying to make heads and tails of your code...

首先我们有...

public JPanel fundo() {
    JPanel bg = new JPanel(new BorderLayout());
    try {
        Image backgroundImage = ImageIO.read(new File("C:/ceu.png"));
        setContentPane(new JPanel(new BorderLayout()) {
            @Override
            public void paintComponent(Graphics g) {
                g.drawImage(backgroundImage, 0, 0, null);
            }
        });
    } catch (IOException e) {
        System.out.println(e);
    }
    return bg;
}

在表面上看起来还不错,但是当我们仔细观察时,我注意到从方法返回的面板不是用作contentPane的面板!?

which on surface looks okay, but when we take a closer look at I notice that the panel which is been returned from the method IS NOT the panel which is been applied as the contentPane!?

但是在您的criarGUI中,您将使用fundo方法返回的面板并将其添加到另一个框架中……但是您只是在该框架中添加了一个空白面板.

But in your criarGUI you take the panel returned by the fundo method and add it to another frame ... but you're just adding a blank panel to the frame.

所以出于某种原因,您要从demo类中获取内容,然后尝试将其添加到其他框架中...为什么这个问题应该真正回答,因为这令人担忧...

So for some reason you're taking content from the demo class and trying to add it to a different frame...why is a question that should really be answered, because that's kind of worrying...

另一个问题是,您不断拨打painelCadastro ...

Another problem is, you keep calling painelCadastro...

demo.painelCadastro().setOpaque(false);
frame.add(demo.painelCadastro());

,但是每次调用painelCadastro都会创建一个新的JPanel,因此更改其opaque状态无效.作为第二次调用它,您将获得JPanel的全新实例.

but painelCadastro creates a new JPanel each time you call it, so changing its opaque state has no effect, as the second time you call it, you're getting a brand new instance of JPanel

解决方案??让您的方法缓存其操作的结果(又称延迟加载),并始终返回相同的JPanel实例(最初创建的实例)或维护对返回的组件的引用.另外,请确保您适当地命名方法,以使它们对它们的作用有更多的了解.在您的情况下,makePainelCadastrocreatePainelCadastro可能更合适

The solution?? Either have your methods cache the result (AKA lazy loading) of their operations and always return the same instance of JPanel (which the initially created) or maintain a reference to the component which is returned. Also, make sure you name your methods appropriately so they give more of an idea of what they do. In your case makePainelCadastro or createPainelCadastro might be more appropriate

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.imageio.ImageIO;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.MaskFormatter;

public class Testing {

    public static void main(String[] args) {
        new Testing();
    }

    public Testing() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setContentPane(new Background());
                    JPanel painelCadastro = painelCadastro();
                    painelCadastro.setOpaque(false);
                    frame.add(painelCadastro);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public JPanel painelCadastro() {
        JPanel telaAtual = new JPanel();
        JTextField nome, telefone, aniversario, email;
        String definicao;
        JLabel lugarnome, lugartelefone, lugaraniversario, lugaremail;
        JTextArea endereço;

        telaAtual.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        //c.anchor = GridBagConstraints.WEST;
        //c.ipadx = 2;
        //c.ipady = 3;
        //c.gridheight = GridBagConstraints.REMAINDER;  
        //c.gridwidth = GridBagConstraints.REMAINDER;  

        lugarnome = new JLabel("Nome");
        c.weightx = 1; // percentual de tamanho em relação aos demais
        c.gridwidth = 1; //tamanho do compontente em celulas HORIZONTAL
        c.gridheight = 1; //tamanho do compontente em celulas VERTICAL
        c.gridx = 0; //localização da celula na coluna
        c.gridy = 0; //localização da celula na linha
        //c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(10, 10, 0, 0);
        telaAtual.add(lugarnome, c);

        nome = new JTextField("Digite seu nome aqui");
        definicao = "nome";
        c.weightx = 1; // percentual de tamanho em relação aos demais
        c.gridwidth = 7; //tamanho do compontente em celulas HORIZONTAL
        c.gridx = 1; //localização da celula na linha
        c.gridy = 0; //localização da celula na coluna
        //c.fill = GridBagConstraints.HORIZONTAL;
//      limpaCaixaTexto(nome, definicao);
        telaAtual.add(nome, c);

        lugartelefone = new JLabel("Telefone");
        c.weightx = 1; // percentual de tamanho em relação aos demais
        c.gridx = 0; //localização da celula na linha
        c.gridy = 1; //localização da celula na coluna
        c.fill = GridBagConstraints.NONE;
        telaAtual.add(lugartelefone, c);

        telefone = new JTextField("Digite seu telefone aqui");
        definicao = "telefone";
        c.weightx = 2; // percentual de tamanho em relação aos demais
        c.gridx = 1; //localização da celula na linha
        c.gridy = 1; //localização da celula na coluna
        c.fill = GridBagConstraints.HORIZONTAL;
//      limpaCaixaTexto(telefone, definicao);
        telaAtual.add(telefone, c);

        lugaremail = new JLabel("Email");
        c.weightx = 1; // percentual de tamanho em relação aos demais
        c.gridx = 0; //localização da celula na linha
        c.gridy = 2; //localização da celula na coluna
        c.fill = GridBagConstraints.NONE;
        telaAtual.add(lugaremail, c);

        email = new JTextField("Digite seu e-mail aqui");
        definicao = "e-mail";
        c.weightx = 2; // percentual de tamanho em relação aos demais
        c.gridx = 1; //localização da celula na linha
        c.gridy = 2; //localização da celula na coluna
        c.fill = GridBagConstraints.HORIZONTAL;
//      limpaCaixaTexto(email, definicao);
        telaAtual.add(email, c);

        //--------- INICIO CAMPO DATA -------------
        lugaraniversario = new JLabel("Data de Nascimento");
        c.weightx = 1; // percentual de tamanho em relação aos demais
        c.gridx = 0; //localização da celula na linha
        c.gridy = 3; //localização da celula na coluna
        c.fill = GridBagConstraints.NONE;
        telaAtual.add(lugaraniversario, c);

        //JFormattedTextField dataAniversario = new JFormattedTextField(DateFormat.getDateInstance(DateFormat.MEDIUM));
        //GregorianCalendar data = new GregorianCalendar();
        //dataAniversario.setText(data.get(Calendar.DAY_OF_MONTH) + "/" + (data.get(Calendar.MONTH) + 1) + "/" + (data.get(Calendar.YEAR)));
        DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
        JFormattedTextField dataAniversario = new JFormattedTextField(df);
        try {
            MaskFormatter dateMask = new MaskFormatter("##/##/####");
            dateMask.install(dataAniversario);

        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        definicao = "aniversario";
        c.weightx = 2; // percentual de tamanho em relação aos demais
        c.gridx = 1; //localização da celula na linha
        c.gridy = 3; //localização da celula na coluna
        c.fill = GridBagConstraints.HORIZONTAL;
//      limpaCaixaTexto(dataAniversario, definicao);
        telaAtual.add(dataAniversario, c);

        //--------- FIM CAMPO DATA -------------
        return telaAtual;
    }

    public class Background extends JPanel {

        private BufferedImage backgroundImage;

        public Background() throws IOException {
            this.backgroundImage = ImageIO.read(new File("..."));
            setLayout(new BorderLayout());
        }

        @Override
        public Dimension getPreferredSize() {
            return backgroundImage == null ? new Dimension(200, 200) : new Dimension(backgroundImage.getWidth(), backgroundImage.getHeight());
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(backgroundImage, 0, 0, this);
        }
    }
}