Как получить индекс X и Y элемента внутри GridLayout?
Я изучаю учебник по java и вижу, что способ найти индексы x/y JButton внутри GridLayout состоит в том, чтобы пересечь двумерный массив кнопок 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, y == 1
@GameWindow.java:
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);
}
}
Ответы
Ответ 1
В этом примере показано, как создать кнопку сетки, которая знает свое местоположение в сетке. Метод getGridButton()
показывает, как получить ссылку на кнопку эффективно на основе координат ее сетки, а прослушиватель действий показывает, что кнопки с нажатыми и найденными идентичны.
![GridButtonPanel]()
package gui;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* @see http://stackoverflow.com/questions/7702697
*/
public class GridButtonPanel {
private static final int N = 5;
private final List<JButton> list = new ArrayList<JButton>();
private JButton getGridButton(int r, int c) {
int index = r * N + c;
return list.get(index);
}
private JButton createGridButton(final int row, final int col) {
final JButton b = new JButton("r" + row + ",c" + col);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton gb = GridButtonPanel.this.getGridButton(row, col);
System.out.println("r" + row + ",c" + col
+ " " + (b == gb)
+ " " + (b.equals(gb)));
}
});
return b;
}
private JPanel createGridPanel() {
JPanel p = new JPanel(new GridLayout(N, N));
for (int i = 0; i < N * N; i++) {
int row = i / N;
int col = i % N;
JButton gb = createGridButton(row, col);
list.add(gb);
p.add(gb);
}
return p;
}
private void display() {
JFrame f = new JFrame("GridButton");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(createGridPanel());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new GridButtonPanel().display();
}
});
}
}
Ответ 2
Вы сохранили массив всех JButtons; вы можете найти ae.getSource()
, и у вас есть позиция.
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if( b[i][j] == ae.getSource() ) {
// position i,j
}
}
}
Ответ 3
Из JButtons
-
JButton # SetName (строка);
-
JButton # setActionCommand (строка);
-
JButton # SetAction (действий);
from/to Container
SwingUtilities # convert...
SwingUtilities # getDeepestComponentAt
Ответ 4
Вы можете использовать setName() для хранения в JButton своего местоположения (например, button.setName(i + "" + j);) при его создании; вы можете получить к нему доступ, разделив строку, которую вы получаете от button.getName() вокруг пробела. Это не особенно эффективный метод, но он немного напоминает то, что вы (или были, к настоящему времени) ищете.
Ответ 5
это решение выбирает все объекты между ними.
первый
написать метод, который получает текст или все необходимое для Jbuuton или jlable или....
второе изменение по коду
public class Event_mouse implements MouseListener {
@Override
public void mouseReleased(MouseEvent e) {
try {
Everything source = (Everything) e.getSource();
if(Everything.gettext==gol){
}
} catch (Exception ee) {
JOptionPane.showMessageDialog(null, ee.getMessage());
}
}