亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何獲得GridLayout內部元素的X和Y指數?

如何獲得GridLayout內部元素的X和Y指數?

LEATH 2019-06-15 13:52:56
如何獲得GridLayout內部元素的X和Y指數?我正在學習一個java教程,并看到在GridLayout中查找JButton的x/y索引的方法是遍歷一個與布局相關的二維按鈕數組b,并檢查b[i][j] == buttonReference.  @Override   public void actionPerformed(ActionEvent ae) {     JButton bx = (JButton) ae.getSource();     for (int i = 0; i < 5; i++)       for (int j = 0; j < 5; j++)         if (b[i][j] == bx)         {           bx.setBackground(Color.RED);         }   }是否有更簡單的方法來獲取按鈕的X/Y索引?類似于:JButton button = (JButton) ev.getSource();int x = this.getContentPane().getComponentXIndex(button);int y = this.getContentPane(). getComponentYIndex(button);this作為一個GameWindow實例ev當用戶按下按鈕時觸發ActionEvent。在這種情況下,它應該得到:x=2,[email protected]:package javaswingapplication;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.*;import javax.swing.*; public class GameWindow extends JFrame implements ActionListener{   JButton b[][] = new JButton[5][5];   int v1[] = { 2, 5, 3, 7, 10 };   int v2[] = { 3, 5, 6, 9, 12 };   public GameWindow(String title)   {     super(title);     setLayout(new GridLayout(5, 5));     setDefaultCloseOperation(EXIT_ON_CLOSE );     for (int i = 0; i < 5; i++)       for (int j = 0; j < 5; j++)       {         b[i][j] = new JButton();         b[i][j].addActionListener(this);         add(b[i][j]);       }   }   @Override   public void actionPerformed(ActionEvent ae) {     ((JButton)ae.getSource()).setBackground(Color.red);   }}@JavaSwingApplication.java:package javaswingapplication;public class JavaSwingApplication {   public static void main(String[] args) {     GameWindow g = new GameWindow("Game");     g.setVisible(true);     g.setSize(500, 500);   }}
查看完整描述

3 回答

?
MYYA

TA貢獻1868條經驗 獲得超4個贊

來自JButtons

  • JButton#setName(字符串);

  • JBUtton#setActionCommand(String);

  • JBUtton#setAction(行動);

往來集裝箱

搖擺實用程序#轉換.。

搖擺實用程序#getDeepestComponentat


查看完整回答
反對 回復 2019-06-15
  • 3 回答
  • 0 關注
  • 710 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號