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

时间:2015-05-29 21:03:59

标签: java swing canvas repaint

基本上,我有一个构造函数类。我在用     import java.awt。;     import javax.swing。;     import java.awt.geom。*;     import java.util.Scanner;

此外,我正在尝试在线创建“战舰”棋盘游戏,并尝试重新绘制在另一种方法中使用一种方法创建的画布。这就是我所拥有的。我不知道如何从第一种方法重新绘制画布,在第二种方法中使用新的东西。

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();
}
}

1 个答案:

答案 0 :(得分:2)

我会做的事与你正在做的完全不同。例如,我:

  • 不在行和列标题中绘制,而是为主JPanel提供GridLayout并使用JLabel显示这些标签。
  • 我也有相同的GridLayout保持JPanel单元格。
  • 如果需要,可以使JPanels不透明,以便在海图下显示背景。
  • 这样可以更轻松地检测鼠标按下的位置。
  • 我会在JPanel的paintComponent方法中执行任何和所有图形,并再次确保始终在同一方法中调用super的paintComponent,以便JPanel可以执行自己的图像管理。

例如,我正在研究一个不完整的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();
         }
      });
   }

}

请运行它以查看它的作用。

我的主程序(我从未完成!)看起来像这样:

enter image description here