2017-05-27 103 views
1

我正在为一个项目创建一个Flight Reservation系统,该应用程序的GUI有问题。我正在使用CardLayout来管理该程序的多个卡。带背景图像的Java卡布局

在登录卡中,我试图添加背景图像,但输入字段显示在图像下方。

本方案的代码是

import java.io.*; 
    import java.awt.*; 
    import java.awt.image.*; 
    import javax.swing.*; 
    import javax.imageio.*; 
    import java.net.*; 

    public class CardPanel { 
     public static void main(String[] args) { 
      try { 
       CardLayout cardLayout = null; 
       JFrame frame = new JFrame("Welcome"); 
       JPanel contentPane = new JPanel(cardLayout); 

       URL url = new URL("https://i.stack.imgur.com/P59NF.png"); 
       BufferedImage img = ImageIO.read(url); 
       ImageIcon imageIcon = new ImageIcon(img); 
       JLabel logo = new JLabel(imageIcon); 

       JPanel buttonsPanel = new JPanel(); 
       JButton login = new JButton("Login"); 
       buttonsPanel.add(login); 

       contentPane.setLayout(new BorderLayout(10, 15)); 

       contentPane.add(logo, BorderLayout.NORTH); 
       contentPane.add(buttonsPanel, BorderLayout.SOUTH); 

       frame.add(contentPane, BorderLayout.CENTER); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setResizable(false); 
       frame.pack(); 
       frame.setVisible(true); 
      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

该应用的屏幕截图也附着(http://i.imgur.com/PkjblPu.png)。

我想按钮在背景图像上方。

+0

_but输入字段的显示image_下面那么,及应如何出现? – Reimeus

+0

@Reimeus我想要图像作为背景和它上面的输入字段。 –

+0

尝试使用卡布局中的两个面板重新创建此卡,每个面板都有一个组件。获取图像的一种方法是通过[本问答](http://stackoverflow.com/q/19209650/418556)中的图像进行热链接。为了尽快提供更好的帮助,请发布[MCVE]或[简短,独立,正确的示例](http://www.sscce.org/)。 –

回答

1

测试表明卡片布局不能用于显示BG图像。看起来它在内部移除一张卡并在交换组件时添加另一张卡。使用自定义绘制的JPanel绘制BG图像。

以下是证据。

enter image description here

即红色是与卡的布局的面板,按钮面板被设置为是透明的。

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

public class CardPanel { 

    public static void main(String[] args) throws Exception { 
     CardLayout cardLayout = new CardLayout(); 
     JFrame frame = new JFrame("Welcome"); 
     JPanel contentPane = new JPanel(cardLayout); 
     contentPane.setBackground(Color.RED); 

     ImageIcon imageIcon = new ImageIcon(new URL("https://i.stack.imgur.com/OVOg3.jpg")); 
     JLabel logo = new JLabel(imageIcon); 

     JPanel buttonsPanel = new JPanel(); 
     JButton login = new JButton("Login"); 
     buttonsPanel.add(login); 

     buttonsPanel.setOpaque(false); 

     contentPane.add(logo, "logo"); 
     contentPane.add(buttonsPanel, "button"); 

     cardLayout.show(contentPane, "button"); 

     frame.add(contentPane, BorderLayout.CENTER); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
}