1

我有一些我正在编写的拼字游戏代码(实际上是重写),到目前为止它分为 3 个类。当Tile该类被放入窗口时,它似乎正在生成一个 BorderFactory 工件。为什么会出现这个神器,我该如何消除它?

*如果您没有看到工件,请尝试慢慢调整窗口大小。

这是Scrabble课程。

import javax.swing.JFrame;
import java.awt.BorderLayout;
public class Scrabble extends JFrame implements Runnable
{
  public Board board;
  public Scrabble()
  {
    super("Scrabble!");
    board = new Board();
    addBorderLayoutObjects();
  }
  public void run()
  {
    makeSettings();
    setVisible(true);
  }
  public void makeSettings()
  {
    setSize(850, 900);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    //this.setResizable(false);
  }
  public void addBorderLayoutObjects()
  {
    getContentPane().add(BorderLayout.CENTER, board);
  }
  public static void main(String[] args)
  {
    Scrabble s = new Scrabble();
    javax.swing.SwingUtilities.invokeLater(s);
  }
}

这是Board课程。

import javax.swing.JPanel;
import java.awt.Point;
import java.awt.Color;
import java.awt.GridLayout;
public class Board extends JPanel
{
  public Tile [][] board;
  public Board()
  {
    super(new GridLayout(15, 15));
    board = new Tile[15][15];
    makeBoard();
  }
  public void makeBoard()
  {
    for(int k = 0; k < 225; k++)
    {
      board[k/15][k%15] = new Tile(new Color(0xCBC4A8), Color.BLACK);
    }
    for(int a = 0; a < 15; a++)
      {
        for(int l = 0; l < 15; l++)
        {
          add(board[a][l]);
        }
      }
  }
}

Tile班级。

import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Point;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class Tile extends JPanel implements MouseListener
{
  private Color color;
  private Color border;
  public Tile(Color _color, Color _border)
  {
    color = _color;
    border = _border;
  }
  public void mouseEntered(MouseEvent e){}
  public void mouseExited(MouseEvent e){}
  public void mousePressed(MouseEvent e){}
  public void mouseReleased(MouseEvent e){}
  public void mouseClicked(MouseEvent e){}
  @Override
  public void paintComponent(Graphics g)
  {
    g.setColor(color);
    setBorder(BorderFactory.createLineBorder(border, 2));
  }
}
4

1 回答 1

1

这是您的第一个问题(可能是您的第二个问题)

public void paintComponent(Graphics g)
{
    g.setColor(color);
    setBorder(BorderFactory.createLineBorder(border, 2));
}

首先,您必须致电super.paintComponent或对其行为负责。这将清除并准备Graphics进一步绘画的背景。

其次,您不应该从paintXxx可能导致其无效或重绘的方法中修改任何 UI 组件。这样做会结束你烧CPU的无限循环......

在构造函数中设置边框或根据程序需要更改它,不要在paint方法中这样做......

更新了其他示例

当您需要更改边框时,只需调用setBorder您要更改的标题的实例......

public Tile(Color _color, Color _border)
{
    color = _color;
    border = _border;
    setBorder(BorderFactory.createLineBorder(border, 2));
}

或者

Title tile = new Tile(Color.RED, Color.BLUE);
//...
title.setBorder(BorderFactory.createLineBorder(Color.GREEN, 2));

查看如何使用边框了解更多信息...

于 2013-02-14T07:54:38.127 回答