Пытаюсь сделать способ, отключающий JButtons.
JButtons находятся в массиве в виде сетки, JButton [int][int] и целые числа должны быть координатами.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
public class BS {
public static JFrame f = new JFrame("BS");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
initializeGui();
}
});
}
static void initializeGui() {
JPanel gui = new JPanel(new BorderLayout(3,1));
//This is the array of the JButtons in the form of a grid
final JButton[][] coordinates = new JButton[15][15];
JPanel field;
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
field = new JPanel(new GridLayout(0, 15));
field.setBorder(new CompoundBorder(new EmptyBorder(15,15,15,15),new LineBorder(Color.BLACK)));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(field);
gui.add(boardConstrain);
//The making of the grid
for (int ii = 0; ii < coordinates.length; ii++) {
for (int jj = 0; jj < coordinates[ii].length; jj++) {
JButton b = new JButton();
ImageIcon icon = new ImageIcon(
new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
b.setIcon(icon);
coordinates[jj][ii] = b;
field.add(coordinates[jj][ii]);
}
}
f.add(gui);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
}
@Frakcool извините за то, что не опубликовал полный код, вопрос почему-то звучал в моей голове просто :)
Это простая проблема, но на этом сайте вы должны предоставить свой код, иначе ваш код будет воспринят как «слишком общий». Когда вы пытаетесь отключить JButton? Когда нажали?
@Frakcool При нажатии было бы более эффективно, если это возможно, но при нажатии я хотел бы, чтобы определенное количество кнопок, следующих за ним, также было отключено.
Объясните, что вы имеете в виду под "определенное количество кнопок, следующих за ним, также будет отключено" Сколько? Точно такой же ряд? Следующий ряд? Столбцы? Как? Кстати, использование коротких имен для имен классов или любой другой переменной может сбивать с толку в больших программах (BS, что это значит?)
@Frakcool Допустим, я нажимаю кнопку и вторую, все кнопки между этими двумя кнопками отключены. Так что у пользователя есть возможность выбрать, будет ли это строка или столбец (вертикальный или горизонтальный). Извините, если я что-то не понимаю. Я в основном хочу отключить столбец или строку кнопок, но вместо того, чтобы делать одну за другой, я просто нажимаю кнопку запуска и кнопку завершения строки кнопок, которые я хочу отключить.
Хорошо, понял, позволь мне кое-что попробовать




Я внес некоторые изменения в ваш код:
public static JFrame f = new JFrame("BS");JFrame не должен быть static и должен иметь более значимое имя (например, frame).
final JButton[][] coordinates = new JButton[15][15]; переместил этот массив как член класса и сделал его не окончательным, а также изменил имя на buttons, так как его легче узнать (для меня coordinates больше похож на массив Point или int)
После этого я добавил ActionListener, см. Руководство по Как использовать Действия.
private ActionListener listener = e -> {
//Loops through the whole array in both dimensions
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) { //Find the JButton that was clicked
if (isStartButton) { //startButton is a boolean variable that tells us if this is the first button clicked or not
startXCoord = i;
startYCoord = j;
} else {
endXCoord = i;
endYCoord = j;
disableButtons(); //Only when we have clicked twice we disable all the buttons in between
}
isStartButton = !isStartButton; //In every button click we change the value of this variable
break; //No need to keep looking if we found our clicked button. Add another one with a condition to skip the outer loop.
}
}
}
};
И метод под названием disableButtons(), который отключает все кнопки между двумя нажатыми кнопками:
private void disableButtons() {
compareCoords(); //This method checks if first button clicked is after 2nd one.
for (int i = startXCoord; i <= endXCoord; i++) {
for (int j = startYCoord; j <= endYCoord; j++) {
buttons[i][j].setEnabled(false); //We disable all buttons in between
}
}
}
В конце наш код заканчивается так:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class DisableButtonsInBetween {
private JFrame frame = new JFrame(getClass().getSimpleName());
private JButton[][] buttons;
private int startXCoord = -1;
private int startYCoord = -1;
private int endXCoord = -1;
private int endYCoord = -1;
private boolean isStartButton = true;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DisableButtonsInBetween().initializeGui();
}
});
}
void initializeGui() {
JPanel gui = new JPanel(new BorderLayout(3, 1));
// This is the array of the JButtons in the form of a grid
JPanel pane;
buttons = new JButton[15][15];
// set up the main GUI
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
pane = new JPanel(new GridLayout(0, 15));
pane.setBorder(new CompoundBorder(new EmptyBorder(15, 15, 15, 15), new LineBorder(Color.BLACK)));
JPanel boardConstrain = new JPanel(new GridBagLayout());
boardConstrain.add(pane);
gui.add(boardConstrain);
// The making of the grid
for (int ii = 0; ii < buttons.length; ii++) {
for (int jj = 0; jj < buttons[ii].length; jj++) {
buttons[jj][ii] = new JButton();
ImageIcon icon = new ImageIcon(new BufferedImage(30, 30, BufferedImage.TYPE_INT_ARGB));
buttons[jj][ii].setIcon(icon);
buttons[jj][ii].addActionListener(listener);
pane.add(buttons[jj][ii]);
}
}
frame.add(gui);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
}
//The ActionListener is what gets called when you click a JButton
private ActionListener listener = e -> {
//These for loops are done to identify which button was clicked.
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) {
if (isStartButton) {
//We save the coords of the 1st button clicked
startXCoord = i;
startYCoord = j;
} else {
//We save the coords of the 2nd button clicked and call the disableButtons method
endXCoord = i;
endYCoord = j;
disableButtons();
}
isStartButton = !isStartButton;
break;
}
}
}
};
//This method disables all the buttons between the 2 that were clicked
private void disableButtons() {
compareCoords();
for (int i = startXCoord; i <= endXCoord; i++) {
for (int j = startYCoord; j <= endYCoord; j++) {
buttons[i][j].setEnabled(false);
}
}
}
//This method compares the coords if the 2nd button was before (in its coords) than the 1st one it switched their coords
private void compareCoords() {
if (endXCoord < startXCoord) {
int aux = startXCoord;
startXCoord = endXCoord;
endXCoord = aux;
}
if (endYCoord < startYCoord) {
int aux = startYCoord;
startYCoord = endYCoord;
endYCoord = aux;
}
}
}
Я надеюсь, что это то, что вы пытались сделать ... если нет, пожалуйста, поясните.
I do not have the arrow operator, " -> ". I think it requires a higher Java. Is there a way to replace this?
Для Java 7 и ниже используйте это для ActionListener:
private ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
if (e.getSource().equals(buttons[i][j])) {
if (isStartButton) {
startXCoord = i;
startYCoord = j;
} else {
endXCoord = i;
endYCoord = j;
disableButtons();
}
isStartButton = !isStartButton;
break;
}
}
}
}
};
У меня нет оператора стрелки "->". Думаю, для этого нужна более высокая Java. Есть способ заменить это?
При добавлении ActionListener я получаю следующую ошибку: тип new ActionListener () {} должен реализовывать унаследованный абстрактный метод ActionListener.actionPerformed (ActionEvent)
Вы добавили 2 следующие строки? Как @Override и public void actionPerformed(ActionEvent e) {, как я в отредактированном коде? Просто скопируйте и вставьте весь ActionListener, и все будет в порядке.
Я исправил это, импортировав java.awt.event.ActionEvent и удалив переопределение
Не могли бы вы добавить какие-то комментарии над методами, я пытаюсь понять это. Спасибо!
Какие методы? Я все объяснил в отрывках выше ... Что вы не понимаете?
Я пытался объяснить, что делают эти методы, я не знаю, помогает ли это, но, не зная, чего вы не понимаете, я не могу объяснить больше
Ничего, мне просто нужно было прочитать код несколько раз. Спасибо вам за помощь!!
Если этот ответ решает ваш вопрос, обязательно принять это
Вызовите
JButton#setEnabled(false)вJButton, который вы хотите отключить. Теперь, чтобы лучше помочь, скорее опубликуйте правильный минимальный воспроизводимый пример, который показывает ваши усилия, пытающиеся решить проблему самостоятельно.