2017-08-01 81 views
2

我正在使用Swing开发一个Fire Emblem模拟器(我刚开始使用Swing,之前我主要在控制台程序上工作)。对于那些不熟悉游戏的人来说,这是一个基于瓦片的战略游戏,你可以在网格上移动单位(类似于国际象棋)。为JButton定义背景颜色和前景图标?

Example

我在考虑使用Jbutton将网格,让玩家能够点击他想要移动,点击他的目的地的单元上。正如你在图片上看到的,单位后面的瓷砖颜色可能会有所不同(红色表示单位可以攻击该瓷砖上的单位,蓝色表示所选单位可以移动的瓷砖)。我不希望每个单元有15种不同的瓷砖设计(UnitX具有蓝色背景,UnitX具有红色背景,UnitX具有绿色背景等等),所以有没有办法在JButton中使用“图层”?画一个蓝色的瓷砖,并在其上绘制正确的字符?

+0

这可能是你正在试图做 https://stackoverflow.com/questions/2407024/drawing-graphics-on-top-of什么有用-j-jbutton – Matt

回答

0

camickr得到的答案是正确的(假设我已经理解了你的问题)。

以下代码演示了如何在JButton上使用setBackgroundsetIcon。它显示了一个带有背景颜色和图标的按钮。该键可以改变被点击时,其背景色:

import javax.swing.*; 
import java.awt.*; 
import java.net.*; 
import java.util.*; 
import java.util.List; 

public class ButtonBackgroundAndIcon { 
    private static final List<Color> BACKGROUND_COLORS = Arrays.asList(
      new Color(229, 119, 120), 
      Color.BLUE, 
      Color.CYAN, 
      Color.GREEN, 
      Color.YELLOW, 
      Color.RED 
    ); 

    private int backgroundIndex; 

    public static void main(String[] arguments) { 
     SwingUtilities.invokeLater(new ButtonBackgroundAndIcon()::run); 
    } 

    private void run() { 
     JFrame frame = new JFrame("Stack Overflow"); 
     frame.setBounds(100, 100, 800, 600); 
     frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 

     JButton tileButton = new JButton(); 
     tileButton.setBackground(BACKGROUND_COLORS.get(0)); 

     Icon icon = getRoyIcon(); 
     if (icon != null) { 
      tileButton.setIcon(icon); 
     } 

     tileButton.addActionListener(actionEvent -> { 
      backgroundIndex = (backgroundIndex + 1) % BACKGROUND_COLORS.size(); 
      tileButton.setBackground(BACKGROUND_COLORS.get(backgroundIndex)); 
     }); 

     frame.getContentPane().add(tileButton); 

     frame.setVisible(true); 
    } 

    private ImageIcon getRoyIcon() { 
     ImageIcon imageIcon; 

     try { 
      String iconLocation = "http://orig06.deviantart.net/fd0e/f/2008" 
            + "/060/d/1/roy_sprite_by_chstuba007.gif"; 
      imageIcon = new ImageIcon(new URL(iconLocation)); 
     } catch (MalformedURLException e) { 
      imageIcon = null; 
     } 

     return imageIcon; 
    } 
} 
+0

(1-)正如你所说的答案已经给出。无需重复答案。无需编写代码。所有OP所要做的就是将两行代码添加到他们当前的程序中来测试解决方案。 – camickr

3

画一个蓝色的瓷砖,并在其上绘制正确的字符?

  1. 使用setBackground(...)方法来设置背景颜色 。

  2. 使用setIcon(...)方法来设置字符。