简体   繁体   English

在ImageIcon之上堆叠JTextField / JTextArea

[英]Stack JTextField/JTextArea on top of ImageIcon

Hello fellow programmers, quick question about a simple Java program. 程序员大家好,快速提问一个简单的Java程序。 I am trying to create a login screen for my program. 我正在尝试为我的程序创建一个登录屏幕。 I am currently using a ImageIcon, which contains an animated gif. 我目前正在使用ImageIcon,其中包含一个GIF动画。 I want to have multiple JTextFields or JTextAreas (whichever is easier) on top of this animated gif, so that I can enter info with a really nice background. 我希望在这个动画gif的顶部有多个JTextFields或JTextAreas(以较简单的方式),以便我可以输入非常好的背景信息。 Is this possible? 这可能吗? If so how would I start? 如果是这样我将如何开始?

UPDATED CODE 更新的代码

class PaintPane extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(background.getImage(), 0, 0, null);
        add(enterUsername);//enterUsername is a JTextField
        add(enterPassword);//enterPassword is a JPasswordField
        repaint();
        revalidate();
    }

}

Extend JPanel and override paintComponent() to draw the background in that JPanel. 扩展JPanel并覆盖paintComponent()以在该JPanel中绘制背景。 Add your JTextFields and JTextAreas (both are equally "easy") to that JPanel just like you would any other JPanel. 将JTextFields和JTextAreas(两者同样“简单”)添加到该JPanel,就像您使用任何其他JPanel一样。

Recommended reading: http://docs.oracle.com/javase/tutorial/uiswing/painting/ 推荐阅读: http//docs.oracle.com/javase/tutorial/uiswing/painting/

Edit after updated code: You shouldn't put the code that adds the JTextField inside the paintComponent() method. 更新代码后编辑:您不应该将添加JTextField的代码放在paintComponent()方法中。 That's going to add a new JTextField to your JPanel every time it's painted, which is a lot! 这将在每次绘制时为你的JPanel添加一个新的JTextField,这是很多! Instead, treat the PaintPane as you would any other JPanel and add the components to it just once, whenever you add it to the JFrame. 相反,只要将其添加到JFrame,就像处理任何其他JPanel一样处理PaintPane并将组件添加到其中一次。 Something like: 就像是:

public class Test{
   public static void main(String... args){
      JFrame frame = new JFrame("Testing");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      //this JPanel paints its own background
      JPanel myPanel = new PaintPane();

      frame.add(myPanel);
      myPanel.add(new JTextField("text field");
      myPanel.add(new JButton("button"));

      frame.setSize(500, 500);
      frame.setVisible(true);
   }
}

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

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