2

在 SO 的其他程序员的帮助下,我有一些代码。首先,谢谢大家。现在我有这个刽子手的代码。我希望文本字段出现在图像下方,现在它正在它上面拍摄。我在代码中提供了图像的链接。但您可能需要下载它以避免引发异常。我想为计时器保留右上角的空闲时间,我还没有想过该怎么做。我需要帮助以使图像和 texfield 处于正确的位置。请执行代码以查看当前的外观。我尝试了 BorderLayout.SOUTH 和 BorderLayout.PAGE_END,但没有帮助 谢谢

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

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;

public class HangmanGUI {
   private DetailsPanel myPanel;
   private ImagePanel imagePanel = new ImagePanel();

   public HangmanGUI() throws ParseException {
      myPanel = new DetailsPanel();
      JFrame myframe = new JFrame();
      // myframe.getContentPane().setLayout(new BorderLayout());
      myframe.getContentPane().add(imagePanel, BorderLayout.CENTER);
      myframe.getContentPane().add(myPanel, BorderLayout.SOUTH);
      myframe.setTitle("Hangman Game");
      // myframe.setVisible(true);
      // myframe.setLocationRelativeTo(null);
      myframe.pack();
      myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      myframe.setLocationRelativeTo(null);
      myframe.setVisible(true);
   }

   public static void main(String[] args) throws ParseException {
      new HangmanGUI();
   }
}

class ImagePanel extends JPanel {
   private static final int PREF_W = 400;
   private static final int PREF_H = PREF_W;
   private static final String TITLE = "Hangman Image";
   private BufferedImage image;

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   public ImagePanel() {
      setBorder(BorderFactory.createTitledBorder(TITLE));
      try {
          image = ImageIO.read(new File("http://upload.wikimedia.org/wikipedia/commons/8/8b/Hangman-0.png"));
      } catch (IOException ex) {
           ex.printStackTrace();
      }

      add(createFormattedPanel(),BorderLayout.SOUTH);
  //add(createFormattedPanel(),BorderLayout.PAGE_END);
   }

   @Override
   protected void paintComponent(Graphics g) {
       super.paintComponent(g);
       g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters            
   }

   public JPanel createFormattedPanel() {
          JPanel panel = new JPanel();
          MaskFormatter formatter = null;
          try {
             JLabel label = new JLabel("Guesss");
             formatter = new MaskFormatter("? ? ? ? ? ? ?");
             formatter.setPlaceholderCharacter('?');
             JFormattedTextField input = new JFormattedTextField(formatter);
             input.setColumns(20);
             panel.add(label);
             panel.add(input);
          } catch (java.text.ParseException exc) {
             System.err.println("formatter is bad: " + exc.getMessage());
             System.exit(-1);
          }

          return panel;
       }

   }

class DetailsPanel extends JPanel {
   public DetailsPanel() {
      setLayout(new BorderLayout());

      setBorder(BorderFactory.createTitledBorder(" click here "));
      //add(createFormattedPanel(), BorderLayout.PAGE_START);

      JPanel letterPanel = new JPanel(new GridLayout(0, 5));
      for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
         String buttonText = String.valueOf(alphabet);
         JButton letterButton = new JButton(buttonText);
         letterButton.addActionListener(clickedbutton());
         letterPanel.add(letterButton, BorderLayout.CENTER);
      }
      add(letterPanel, BorderLayout.CENTER);
   }

   private ActionListener clickedbutton() {
      return new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            String actionCommand = e.getActionCommand();
            System.out.println("actionCommand is: " + actionCommand);
         }
      };
   }

}
4

1 回答 1

4

因为您将自定义绘画和组件混合到一个组件中,所以您将失去对组件布局方式的控制。

想到了两个解决方案...

使用 JLabel

使用aJLabel来显示图片,将其放置在该CENTER位置,ImagePane并将“格式化面板”放置在该SOUTH位置

将组件分成逻辑组

拆分您的 UI,以便每个组件都被隔离...

-- Hangman Image --------------
| --------------------------- |
| | ----------------------- | |
| | |                     | | |
| | |                     | | |
| | | (Image Pane)        | | |
| | |                     | | |
| | |                     | | |
| | ----------------------- | |
| | ----------------------- | |
| | | Guess: ? ? ? ? ? ?  | | |
| | ----------------------- | |
| --------------------------- |
| -- click here ------------- |
| |                         | |
| |                         | |
| | (buttons   )            | |
| |                         | |
| |                         | |
| --------------------------- |
-------------------------------

基本上, the ImagePane、 theGuessPane和 theClickPane都是独立的组件。

然后,您可以将ImagePaneand添加GuessPane到另一个JPanel(使用BorderLayout)上,然后将其添加ClickPane到主面板(使用 a BorderLayout)。

这将使您能够更好地控制各个组件的布局和组合方式。

== 使用示例JLabel==

这是JLabel使用自定义绘画的一个基本示例。

ImagePaneGuessPane被添加到单独的面板中,该面板被添加到框架的CENTER位置。然后DetailsPane将其添加到SOUTH框架的位置...

在此处输入图像描述

import javax.swing.*;
import javax.swing.text.MaskFormatter;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

public class HangmanGUI {

    private DetailsPanel myPanel;

    public HangmanGUI() throws ParseException {
        myPanel = new DetailsPanel();
        JFrame myframe = new JFrame();

        JPanel content = new JPanel(new BorderLayout());
        content.add(new ImagePane());
        content.add(new GuessPane(), BorderLayout.SOUTH);
        content.setBorder(BorderFactory.createTitledBorder("Hangman Image"));

        myframe.getContentPane().add(content, BorderLayout.CENTER);
        myframe.getContentPane().add(myPanel, BorderLayout.SOUTH);
        myframe.setTitle("Hangman Game");
        myframe.pack();
        myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myframe.setLocationRelativeTo(null);
        myframe.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }
                try {
                    new HangmanGUI();
                } catch (ParseException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public class ImagePane extends JPanel {

        private JLabel label;

        public ImagePane() {
            setLayout(new BorderLayout());
            label = new JLabel();
            add(label);
            try {
                label.setIcon(new ImageIcon(ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/commons/8/8b/Hangman-0.png"))));
            } catch (IOException ex) {
                label.setText("Bad Image");
                ex.printStackTrace();
            }
        }

    }

    public static class GuessPane extends JPanel {

        public GuessPane() {
            MaskFormatter formatter = null;
            try {
                JLabel label = new JLabel("Guesss");
                formatter = new MaskFormatter("? ? ? ? ? ? ?");
                formatter.setPlaceholderCharacter('?');
                JFormattedTextField input = new JFormattedTextField(formatter);
                input.setColumns(20);
                add(label);
                add(input);
            } catch (java.text.ParseException exc) {
                System.err.println("formatter is bad: " + exc.getMessage());
                System.exit(-1);
            }
        }

    }

    public static class DetailsPanel extends JPanel {

        public DetailsPanel() {
            setLayout(new BorderLayout());

            setBorder(BorderFactory.createTitledBorder(" click here "));
            //add(createFormattedPanel(), BorderLayout.PAGE_START);

            JPanel letterPanel = new JPanel(new GridLayout(0, 5));
            for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
                String buttonText = String.valueOf(alphabet);
                JButton letterButton = new JButton(buttonText);
                letterButton.addActionListener(clickedbutton());
                letterPanel.add(letterButton, BorderLayout.CENTER);
            }
            add(letterPanel, BorderLayout.CENTER);
        }

        private ActionListener clickedbutton() {
            return new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    String actionCommand = e.getActionCommand();
                    System.out.println("actionCommand is: " + actionCommand);
                }
            };
        }

    }
}

这种类型的分离将需要使用某种模型来桥接组件。

也就是说,当用户进行猜测时,您需要更新模型,这将通知其他组件(通过某种侦听器 API)发生了一些变化,这将允许其他 UI 元素根据需要更新自己满足模型的要求。

模型应该包含游戏的逻辑并驱动 UI。

于 2013-10-18T00:28:02.683 回答