如何在JOptionPane中的背景图像上对齐多个文本字段?

时间:2013-07-26 02:52:06

标签: java swing jlabel layout-manager joptionpane

我希望多个文本字段以自定义顺序对齐,以便它们位于背景图像的顶部。我尝试使用setBounds,但它不起作用:

import javax.swing.*;


    public class TestJP {


        public static void main(String[] args) {

                  JLabel myLabel = new JLabel();
                  myLabel.setIcon ( new ImageIcon("system\\myBackground.jpg"));
                  myLabel.setBounds(0,0,750,500);


                  JTextField login = new JTextField(5);
                  login.setBounds(50,50,20,100); // This does not work

                  JPasswordField password = new JPasswordField(5);
                  password.setBounds( 50, 70, 20, 100); // Doesn't help either

                  JPanel myPanel = new JPanel();
                  myPanel.add(myLabel);
                  myPanel.add(login);
                  myPanel.add(password);

                   int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Login", JOptionPane.OK_CANCEL_OPTION);

                 // etc

               }

        }

2 个答案:

答案 0 :(得分:4)

请勿使用setBounds()。 Swing旨在与布局管理器一起使用。

您可以通过执行以下操作将文本字段添加到标签中:

JLabel myLabel = new JLabel( new ImageIcon("system\\myBackground.jpg") );
mylabel.setLayout( new FlowLayout() );
mylabel.add(login);
mylabel.add(password);

使用适当的布局管理器来获得所需的布局。

答案 1 :(得分:4)

  

“我尝试使用setBounds,但它不起作用:”

  • 使用布局管理器就是他们的用途。您可以找到布局管理器教程here
  • 将布局添加到显示图像的JLabel。
  • 将您的JTextField添加到该JLabel。
  • 在JOptionPane中显示JLabel。

如需更多帮助,请发布您要尝试的图片。


修改您在评论中说明:

  

谢谢!我在contentPane中多次使用setBounds ...它运行正常。

虽然作为一个新手,你会发现setBounds和null布局似乎更容易使用,你使用swing进行编码的时间越长,你的GUI就越多,你会发现null布局会让你失败,看起来会很糟糕在不同的平台上,将不灵活,不允许您以后更新或改进您的GUI。

  

怎么对JOptionPane不起作用?常规布局管理器不准确......我不想使用它们:east,west

它与JOptionPane无关,而与你如何正确创建GUI无关。学习使用布局管理器,它们将更容易使用。


编辑2 例如:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.beans.Transient;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.*;

public class GridBagEg {
   public static final String IMG_PATH = "https://duke.kenai.com/tshirts/.Midsize/Tshirt1997.png.png";

   private static void createAndShowGui() {
      BufferedImage img = null;
      try {
         URL imgUrl = new URL(IMG_PATH);
         img = ImageIO.read(imgUrl);
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }
      PlayerEditorPanel playerEditorPane = new PlayerEditorPanel(img);

      int result = JOptionPane.showConfirmDialog(null, playerEditorPane,
            "Edit Player", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.PLAIN_MESSAGE);
      if (result == JOptionPane.OK_OPTION) {
         // TODO: do something with info

         for (PlayerEditorPanel.FieldTitle fieldTitle : 
            PlayerEditorPanel.FieldTitle.values()) {
            System.out.printf("%10s: %s%n", fieldTitle.getTitle(),
                  playerEditorPane.getFieldText(fieldTitle));
         }
      }
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

@SuppressWarnings("serial")
class PlayerEditorPanel extends JPanel {
   enum FieldTitle {
      NAME("Name"), SPEED("Speed"), STRENGTH("Strength");
      private String title;

      private FieldTitle(String title) {
         this.title = title;
      }

      public String getTitle() {
         return title;
      }
   };

   private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
   private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
   private static final double SCALE = 0.4;
   private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();
   private BufferedImage backgroundImg = null;
   private int imgWidth;
   private int imgHeight;

   public PlayerEditorPanel(BufferedImage img) {
      this.backgroundImg = img;
      imgWidth = (int) (backgroundImg.getWidth() * SCALE);
      imgHeight = (int) (backgroundImg.getHeight() * SCALE);

      setLayout(new GridBagLayout());
      setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("Player Editor"),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));
      GridBagConstraints gbc;
      for (int i = 0; i < FieldTitle.values().length; i++) {
         FieldTitle fieldTitle = FieldTitle.values()[i];
         gbc = createGbc(0, i);
         JLabel fieldLabel = new JLabel(fieldTitle.getTitle() + ":",
               JLabel.LEFT);
         fieldLabel.setForeground(new Color(200, 10, 10));
         fieldLabel.setFont(fieldLabel.getFont().deriveFont(Font.BOLD, 24f));
         add(fieldLabel, gbc);
         gbc = createGbc(1, i);
         JTextField textField = new JTextField(10);
         add(textField, gbc);

         fieldMap.put(fieldTitle, textField);
      }
   }

   @Override
   @Transient
   public Dimension getPreferredSize() {
      if (backgroundImg != null) {
         return new Dimension(imgWidth, imgHeight);
      }

      return super.getPreferredSize();
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (backgroundImg != null) {
         g.drawImage(backgroundImg, 0, 0, imgWidth, imgHeight, this);
      }
   }

   private GridBagConstraints createGbc(int x, int y) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = x;
      gbc.gridy = y;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;

      gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
      gbc.fill = (x == 0) ? GridBagConstraints.BOTH
            : GridBagConstraints.HORIZONTAL;

      gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
      gbc.weightx = (x == 0) ? 0.1 : 1.0;
      gbc.weighty = 1.0;
      return gbc;
   }

   public String getFieldText(FieldTitle fieldTitle) {
      return fieldMap.get(fieldTitle).getText();
   }

}

显示如下的JOptionPane:

enter image description here