2017-08-01 3 views
2

私はSwingを使用してFire Emblem Mockを作成しています(これは、ちょうど私が悩んでいるところですが、私はほとんどがコンソールプログラムで働いていました)。ゲームに精通していない人には、格子状(チェスに似た)にユニットを移動させるタイルベースの戦略ゲームです。JButtonの背景色とフォアグラウンドアイコンを定義しますか?

Example

プレイヤーは自分が移動したいユニットをクリックして、彼の目的地をクリックすることができるように、私は、グリッドのJButtonがを使用して考えています。画像のように、ユニットの背後にあるタイルの色が変わることがあります(赤はユニットがそのタイルのユニットを攻撃できることを意味し、青は選択したユニットが移動できるタイルを意味します)。私は各ユニット(青色の背景を持つUnitX、赤い背景を持つUnitX、緑色の背景を持つUnitXなど)に15種類のタイルデザインを持たせたくないので、JButtonで「レイヤー」を使用する方法はありますか?青いタイルを描き、その上に正しい文字を描きますか?

+0

これは、あなたが https://stackoverflow.com/questions/2407024/drawing-graphics-on-top-ofをやろうとしているもののために役に立つかもしれない:ボタンは、それがクリックされていますその背景色を変更します-a-jbutton – Matt

答えて

0

答えはcamickrです(あなたの質問を理解したと仮定して)。

JButtonsetBackgroundsetIconを使用する方法を次のコードで示します。これは、背景色とアイコンのボタンを表示します。

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は、ソリューションをテストするために現在のプログラムに2行のコードを追加するだけです。 – camickr

3

青いタイルを描き、その上に正しい文字を描きますか?

  1. 使用

    背景色を設定するsetBackground(...)方法。

  2. 文字を設定するには、setIcon(...)メソッドを使用します。

関連する問題