简体   繁体   English

如何正确使用repaint()方法?

[英]How to use the repaint() method properly?

Basically, I have a constructor class. 基本上,我有一个构造函数类。 I am using import java.awt. 我正在使用import java.awt。 ; ; import javax.swing. 导入javax.swing。 ; ; import java.awt.geom.*; 导入java.awt.geom。*; import java.util.Scanner; 导入java.util.Scanner;

Also, I am trying to create a "Battleship" board game online and am trying to repaint the canvas that was created in one method in another method. 另外,我正在尝试在线创建“战舰”棋盘游戏,并试图重新绘制以另一种方法创建的画布。 This is what I have. 这就是我所拥有的。 I don't have any idea how to repaint the canvas from the first method, with the new stuff in the second method. 我不知道如何用第一种方法用第二种方法中的新内容重新绘制画布。

public class Battleship extends JApplet
{

public void paint(Graphics page)
{
page.fillRect(40, 50,500,2);//Lines From Here
page.fillRect(40,100,500,2);
page.fillRect(40,150,500,2);
page.fillRect(40,200,500,2);
page.fillRect(40,250,500,2);
page.fillRect(40,300,500,2);
page.fillRect(40,350,500,2);
page.fillRect(40,400,500,2);
page.fillRect(40,450,500,2);
page.fillRect(40,500,500,2);
page.fillRect(40,550,500,2);
page.fillRect(40,50,2,500);
page.fillRect(90,50,2,500);
page.fillRect(140,50,2,500);
page.fillRect(190,50,2,500);
page.fillRect(240,50,2,500);
page.fillRect(290,50,2,500);
page.fillRect(340,50,2,500);
page.fillRect(390,50,2,500);
page.fillRect(440,50,2,500);
page.fillRect(490,50,2,500);
page.fillRect(540,50,2,500);//To Here
page.drawString("A", 60, 40);//X Axis From Here
page.drawString("B", 110, 40);
page.drawString("C", 160, 40);
page.drawString("D", 210, 40);
page.drawString("E", 260, 40);
page.drawString("F", 310, 40);
page.drawString("G", 360, 40);
page.drawString("H", 410, 40);
page.drawString("I", 460, 40);
page.drawString("J", 510, 40);//To Here
page.drawString("0", 15, 80);//Y Axis From Here
page.drawString("1", 15, 130);
page.drawString("2", 15, 180);
page.drawString("3", 15, 230);
page.drawString("4", 15, 280);
page.drawString("5", 15, 330);
page.drawString("6", 15, 380);
page.drawString("7", 15, 430);
page.drawString("8", 15, 480);
page.drawString("9", 15, 530);//To Here
}
public void Start()
{
String input;
Scanner next = new Scanner(System.in);
input = next.nextLine();
page.drawString("testing testingajsdbasdkj", 15, 530);
repaint();
}
}

I would do things completely differently than what you're doing. 我做的事情与您所做的完全不同。 For instance, I'd: 例如,我会:

  • Not draw in the row and column headers but rather give a main JPanel a GridLayout and use JLabels to display these labels. 不绘制行和列标题,而是给主JPanel一个GridLayout并使用JLabel显示这些标签。
  • I'd also have that same GridLayout hold JPanel cells. 我也将拥有相同的GridLayout容纳JPanel单元。
  • If you want, you can make the JPanels non-opaque so that it can display a background under the sea image. 如果需要,可以使JPanels不透明,以便它可以在海底图像下显示背景。
  • This will make it easier to detect where the mouse presses occur. 这将使检测鼠标按下的位置更加容易。
  • I'd do any and all graphics in a JPanel's paintComponent method, and again, making sure to always call the super's paintComponent in that same method so that the JPanel can do its own image housekeeping. 我将在JPanel的paintComponent方法中进行所有图形处理,并再次确保始终以相同的方法调用上级的paintComponent,以便JPanel可以进行自己的图像整理。

For example, I was working on an incomplete BattleShip program and parts of it look like this class: 例如,我正在研究一个不完整的BattleShip程序,它的部分内容类似于此类:

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

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

@SuppressWarnings("serial")
public class BattleShipGridPanel {
   public static final String MOUSE_PRESSED = "Mouse Pressed";
   // public static final String MOUSE_DRAGGED = "Mouse Dragged";
   private static final int ROW_COUNT = 11;
   private static final int COL_COUNT = 11;

   // the main JPanel for this part of my program
   private JPanel mainPanel = new JPanel(){
      // it draws an image if available
      protected void paintComponent(Graphics g) {
         super.paintComponent(g);
         myPaint(g);
      };
   };
   private Image img = null;
   private String selectedCellName = "";
   private JLabel selectedLabel = null;
   private Map<String, JLabel> labelMap = new HashMap<String, JLabel>();
   private SwingPropertyChangeSupport propChangeSupport = new SwingPropertyChangeSupport(this);

   public BattleShipGridPanel(Image img, int cellSideLength) {
      this.img = img;
      mainPanel.setLayout(new GridLayout(11, 11));
      mainPanel.setBorder(BorderFactory.createLineBorder(Color.black));

      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      mainPanel.addMouseListener(myMouseAdapter);

      for (int row = 0; row < ROW_COUNT; row++) {
         for (int col = 0; col < COL_COUNT; col++) {
            String rowStr = String.valueOf((char) ('A' + row - 1));
            String colStr = String.valueOf(col);
            String name = ""; // name for component
            String text = ""; // text to display

            // create JLabel to add to grid
            JLabel label = new JLabel("", SwingConstants.CENTER);

            // text to display if label is a row header at col 0
            if (col == 0 && row != 0) {
               text = "" + rowStr;
            } else

            // text to display if label is a col header at row 0
            if (row == 0 && col != 0) {
               text = "" + colStr;
            } else

            // name to give to label if label is on the grid and not a
            // row or col header
            if (row != 0 && col != 0) {
               name = rowStr + " " + colStr;
               labelMap.put(name, label);
            }
            label.setText(text);
            label.setName(name);
            label.setPreferredSize(new Dimension(cellSideLength, cellSideLength));
            label.setBorder(BorderFactory.createLineBorder(Color.black));
            mainPanel.add(label);
         }
      }
   }

   private void myPaint(Graphics g) {
      if (img != null) {
         int w0 = mainPanel.getWidth();
         int h0 = mainPanel.getHeight();
         int x = w0 / 11;
         int y = h0 / 11;

         int iW = img.getWidth(null);
         int iH = img.getHeight(null);

         g.drawImage(img, x, y, w0, h0, 0, 0, iW, iH, null);
      }
   }

   public void addPropertyChangeListener(PropertyChangeListener listener) {
      propChangeSupport.addPropertyChangeListener(listener);
   }

   private class MyMouseAdapter extends MouseAdapter {
      @Override
      public void mousePressed(MouseEvent mEvt) {
         if (mEvt.getButton() == MouseEvent.BUTTON1) {
            Component comp = mainPanel.getComponentAt(mEvt.getPoint());
            if (comp instanceof JLabel) {
               String name = comp.getName();
               if (!name.trim().isEmpty()) {
                  String oldValue = selectedCellName;
                  String newValue = name;
                  selectedCellName = name;
                  selectedLabel = (JLabel) comp;
                  propChangeSupport.firePropertyChange(MOUSE_PRESSED, oldValue, newValue);
               }
            }
         }
      }
   }

   public JPanel getMainPanel() {
      return mainPanel;
   }

   public String getSelectedCellName() {
      return selectedCellName;
   }

   public char getSelectedRow() {
      if (selectedCellName.isEmpty()) {
         return (char)0;
      } else {
         return selectedCellName.split(" ")[0].charAt(0);
      }
   }

   public int getSelectedCol() {
      if (selectedCellName.isEmpty()) {
         return 0;
      } else {
         return Integer.parseInt(selectedCellName.split(" ")[1]);
      }
   }

   public JLabel getSelectedLabel() {
      return selectedLabel;
   }

   public void resetSelections() {
      selectedCellName = "";
      selectedLabel = null;
   }

   public JLabel getLabel(String key) {
      return labelMap.get(key);
   }

   public void resetAll() {
      resetSelections();
      for (String key : labelMap.keySet()) {
         labelMap.get(key).setIcon(null);
      }
   }

   // for testing purposes only
   private static void createAndShowGui() {
      // path to some undersea image
      String imgPath = "http://upload.wikimedia.org/wikipedia/"
            + "commons/3/31/Great_white_shark_south_africa.jpg";
      BufferedImage img = null;
      try {
         img = ImageIO.read(new URL(imgPath));
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }

      int cellSideLength = 36;
      BattleShipGridPanel gridPanel = new BattleShipGridPanel(img, cellSideLength);
      gridPanel.addPropertyChangeListener(new PropertyChangeListener() {

         @Override
         public void propertyChange(PropertyChangeEvent evt) {
            // print out where the mouse pressed:
            System.out.println(evt.getNewValue());
         }
      });
      JFrame frame = new JFrame("BattleShipGridPanel");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(gridPanel.getMainPanel());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

}

Please run it to see what it does. 请运行它以查看其作用。

My main program (that I never completed!) looked like this: 我的主程序(我从未完成!)看起来像这样:

在此处输入图片说明

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

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