Java Swing actionPerformed() skips visualization - java

I am working on my first sorting visualizer using java and swing. If i hard code selection sort, the visualizer works properly. Its when i add the actionPerformed() method to the "sort" JButton things start going wrong. The program now waits until the sort is done before it repaints. Is there a way around this?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SortingAlgorithmVisualizer implements ActionListener {
private static final int WINDOW_WIDTH = 1200;
private static final int WINDOW_HEIGHT = 600;
private static final String[] ALGORITHM_NAMES = { "Selection Sort", "Insertion Sort", "Quick Sort", "Merge Sort" };
// JFrame to create GUI window
private JFrame window;
private Sort array;
private JButton sortButton;
private JComboBox<String> algorithmMenu;
// Constructor
public SortingAlgorithmVisualizer() {
// Construct the JFrame and add components
addComponents();
// Set Basic JFrame Settings
frameSetup();
// Unsort the array
array.unsort();
}
// Construct the JFrame and add components
public void addComponents() {
window = new JFrame("Sorting Algorith Visualiser");
array = new Sort();
sortButton = new JButton("Sort");
sortButton.addActionListener(this);
algorithmMenu = new JComboBox<>(ALGORITHM_NAMES);
// algorithmMenu.addActionListener(this);
window.add(algorithmMenu, BorderLayout.PAGE_START);
window.add(array, BorderLayout.CENTER);
window.add(sortButton, BorderLayout.SOUTH);
}
// Set Basic JFrame Settings
public void frameSetup() {
window.setLocationRelativeTo(null);
window.setResizable(false);
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sortButton) {
array.selectionSort();
}
}
public static void main(String[] args) {
SortingAlgorithmVisualizer vis = new SortingAlgorithmVisualizer();
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Sort extends JPanel {
private static final long serialVersionUID = 1L;
private static final int ARRAY_SIZE = 25;
private static final int WINDOW_WIDTH = 1200;
private static final int WINDOW_HEIGHT = 600;
private static int barWidth = WINDOW_WIDTH / ARRAY_SIZE;
private int[] elementColor;
// Array to sort
private int[] array;
// Contructor
public Sort() {
// DO SOMETHING WITH THIS!!!!
array = new int[ARRAY_SIZE];
elementColor = new int[ARRAY_SIZE];
// Fill Array
for (int i = 0; i < ARRAY_SIZE; i++) {
array[i] = i + 1;
elementColor[i] = 0;
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
for (int i = 0; i < ARRAY_SIZE; i++) {
int height = (array[i] * 20 + 100);
int x = i + (barWidth - 1) * i;
int y = WINDOW_HEIGHT - height;
g.fillRect(x, y, barWidth, height);
}
}
public void unsort() {
int shuffles = 100;
for (int i = 0; i < shuffles; i++) {
int rand1 = (int) (Math.random() * ARRAY_SIZE);
int rand2 = (int) (Math.random() * ARRAY_SIZE);
int temp = array[rand1];
array[rand1] = array[rand2];
array[rand2] = temp;
}
}
public void selectionSort() {
int n = ARRAY_SIZE;
// Loop thought unsorted array
for (int i = 0; i < n - 1; i++) {
// Set Current Min
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex])
minIndex = j;
}
// Swap the min element with the first element
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
// Repaints the Array after every swap
repaint();
wait(1000);
}
}
public void insertionSort() {
}
public void quickSort() {
}
public void mergeSort() {
}
// Wait fuction for visualisation delay
public static void wait(int ms) {
try {
Thread.sleep(ms);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}

Related

Paint Method in an Applet (Sort Algorithms in Java)

I have two classes: One applet for the GUI and one class to sort numbers.
Sort Class:
public class Sortierung {
public int[] Zahlen = {5,2,3,1,4};
int z;
public static int zufallszahl (int z){
int dauer = ((int)(Math.random()*z))+1;
return dauer;
}
public void ArrayErstellen(int l){
int[] myIntArray = new int[l];
for(int f=0;f<myIntArray.length;f++){
myIntArray[f]=zufallszahl(10);
}
Zahlen=myIntArray;
}
public int[] BubbleSort() {
for(int p=0;p<Zahlen.length-1;p++){
for(int i=0;i<Zahlen.length-1;i++){
if(Zahlen[i]<Zahlen[i+1]){
continue; //beendet den derzeitigen Schleifenablauf
}
else{
z=Zahlen[i];
Zahlen[i]=Zahlen[i+1];
Zahlen[i+1]=z;
}
}
}
return Zahlen;
}
public int[] InsertionSort() {
int f = 0; //Variable 1
int j = 0; //Variable 2
for(int i = 1;i < Zahlen.length;i++){
j = i;
while((j>0)&&(Zahlen[j-1]>Zahlen[j])){
f = Zahlen[j-1];
Zahlen[j-1] = Zahlen[j];
Zahlen[j] = f;
j--;
}
}
return Zahlen;
}
public int[] SelectionSort(){
for (int i = 0; i < Zahlen.length - 1; i++){
int s = i; //Neue Variable für die Schleife
for (int j = i + 1; j < Zahlen.length; j++)
if (Zahlen[j] < Zahlen[s]){
s = j;
}
int smallerNumber = Zahlen[s];
Zahlen[s] =Zahlen[i];
Zahlen[i] = smallerNumber;
}
return Zahlen;
}
public void ArrayWiedergeben(int[] eimer){
for(int u=0;u<eimer.length;u++){
System.out.println(eimer[u]);
}
} }
Gui (Applet):
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Gui extends JApplet {
JTextField tf;
JButton b;
JButton k;
JLabel s;
JLabel u;
int anzahl;
int test = 0;
JPanel p = new JPanel();
JPanel h = new JPanel();
JPanel f = new JPanel();
Sortierung neu = new Sortierung();
Choice Sortierungsmethode = new Choice();
ActionListener startOhr = new ActionListener() {
public void actionPerformed(ActionEvent e) {
anzahl = Integer.parseInt(tf.getText());
if (anzahl > 100) {
tf.setText("Wert zu hoch.");
return;
}
neu.ArrayErstellen(anzahl);
tf.setText("Array[" + anzahl + "] erstellt.");
}
};
ActionListener sortOhr = new ActionListener() {
public void actionPerformed(ActionEvent e) {
switch (Sortierungsmethode.getSelectedIndex()) {
case 0:
int[] eimer = neu.BubbleSort();
neu.ArrayWiedergeben(eimer);
test = 1;
repaint();
break;
case 1:
int[] eimer2 = neu.InsertionSort();
neu.ArrayWiedergeben(eimer2);
break;
case 2:
int[] eimer3 = neu.SelectionSort();
neu.ArrayWiedergeben(eimer3);
break;
default:
break;
}
}
};
public void init() {
tf = new JTextField(8);
b = new JButton("Erstellen");
k = new JButton("Bestätigen");
s = new JLabel("Array Länge");
u = new JLabel("Sortmethode");
Sortierungsmethode.add("Bubblesort");
Sortierungsmethode.add("Insertionsort");
Sortierungsmethode.add("Selectionsort");
setLayout(new BorderLayout());
p.add(s);
p.add(tf);
p.add(b);
h.add(u);
h.add(Sortierungsmethode);
h.add(k);
this.add(p, BorderLayout.NORTH);
this.add(h, BorderLayout.CENTER);
this.add(f, BorderLayout.SOUTH);
b.addActionListener(startOhr);
k.addActionListener(sortOhr);
}
}
My intention is to draw the sorted array in a coordinate system with a paint
method. The problem is, that when I try to create a paint method, the whole screen is white and I cant see anything
You need to address several details:
You should create a class which overrides JPanel to do your custom drawing. You can create an instance of the class in your Gui class.
You should override paintComponet() rather than paint().
The first line in paintComponent(Graphics g) should be super.paintComponent(g) in order to ensure that the super class can paint itself.
You need to be careful that your sorting algorithm doesn't take over the main thread. This will cause your app to freeze and nothing will paint until the sorting has finished.
You need to create a Thread object and set it to call run method 30 times per second. In this method, call repaint() method of main JPanel.

Why aren't the array objects changing when changed in the JFrame they were added to?

I am adding an array of objects onto a JFrame. When I change the object's state in the JFrame, it is not changing in the array. The object's class is called connect2. The change that I am making is increasing connect2's arrayPosition field by 1. The change is made on the object that was added to the JFrame, but not the corresponding array.
The algorithm is as follows:
connect1 extends JFrame and contains the main method which invokes the connect1 constructor. The connect1 constructor set the size for the JFrame, set the JFrame to visible, set a GridLayout, and instantiates 100 connect2 objects which are also JPanels and adds them to an array. The 100 connect2 JPanels are added to the JFrame via for loop.
The connect2 constructor takes in a connect1 argument. When connect2 is clicked, it will increment connect1's static counter field. The counter's value is passed to connect2's arrayposition variable.
For some reason when I access the connect2 object in the array in connect1, the arrayposition variable has not changed.
Can someone please give me a hand with this issue? Why aren't the objects in the array changing as well. Java arrays store the memory locations of the objects, don't they?
Here is my code:
package connect;
import java.awt.*;
import javax.swing.JFrame;
public class connect1 extends JFrame
{
static int counter = 0;
int M = 10;
int N = 10;
int Grid = M*N;
connect2 array[] = new connect2 [Grid];
private static final long serialVersionUID = 1L;
public static void main(String[] args)
{
new connect1();
}
public connect1()
{
setVisible(true);
setSize(1000, 1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(M, N));
//add(new Welcome(this));
//int Grid = M*N;
//connect2 array[] = new connect2 [Grid];
for (int j = 0; j < Grid; j++)
{
array[j] = new connect2(this);
add(array[j]);
}
}
public void toRefresh()
{
if (counter > 0)
{
bubbleSort(array);
}
repaint();
}
public void bubbleSort(connect2[] x)
{
connect2 temp;
for (int i = 0; i < /*x.length*/ counter - 1; i++)
{
for (int j = 1; j < /*x.length*/ counter - i; j++)
{
//System.out.println(x[j - 1].arrayPosition+" j - 1 "+x[j].arrayPosition+" j ");
if (x[j - 1].arrayPosition > x[j].arrayPosition)
{
temp = x[j - 1];
x[j - 1] = x[j];
x[j] = temp;
}
}
}
}
public void undo()
{
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i].arrayPosition);
}
}
}
Connect2 class:
package connect;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class connect2 extends JPanel
{
private static final long serialVersionUID = 1L;
int arrayPosition;
int whenClicked = 0;
connect1 refr = null;
public connect2(connect1 refresh)
{
addMouseListener(new MouseListener()
{
#SuppressWarnings("static-access")
#Override
public void mouseClicked(MouseEvent arg0)
{
if(arg0.getModifiers() == MouseEvent.BUTTON1_MASK)
{
whenClicked++;
refr.counter++;
arrayPosition = refr.counter;
refr.toRefresh();
}
if(arg0.getModifiers() == MouseEvent.BUTTON3_MASK)
{
System.out.println(arrayPosition);
refr.undo();
}
}
#Override
public void mouseEntered(MouseEvent arg0)
{
// Not used
}
#Override
public void mouseExited(MouseEvent arg0)
{
// Not used
}
#Override
public void mousePressed(MouseEvent arg0)
{
// Not used
}
#Override
public void mouseReleased(MouseEvent arg0)
{
// Not used
}
});
refr = refresh;
}
#Override
protected void paintComponent(Graphics g)
{
switch(whenClicked)
{
case 1:
g.setColor(Color.red);
break;
case 2:
g.setColor(Color.blue);
break;
}
g.fillOval(0, 0, 80, 80);
}
}
Look at the refr = refresh; statement. This statement is located below arrayPosition = refr.counter.

how to display chart in a Jpanel with Jframe [duplicate]

This question already has an answer here:
swing window getting frozen ,not displaying content
(1 answer)
Closed 8 years ago.
I want to create a Java application that visualizes merge sort using swing components. So far I've written this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MergeSort extends JFrame {
private int[] helper;
private int[] heights;
private JPanel mainPanel;
private JTextArea[] areas;
private JTextArea txtSpeed;
private JLabel lblSpeed;
private JButton btnStart;
private Random rnd;
private final int FRAME_HEIGHT = 550;
private final int FRAME_WIDTH = 1100;
private final int ELEMENTS_TO_SORT = 100;
private final int BAR_WIDTH = 7;
private final int SPACING = 10;
private int SLEEP_TIME = 50;
public MergeSort() {
super("Merge Sort Visualisation");
helper = new int[ELEMENTS_TO_SORT];
mainPanel = new JPanel();
mainPanel.setLayout(null);
rnd = new Random();
areas = new JTextArea[ELEMENTS_TO_SORT];
heights = new int[areas.length];
for (int i = 0; i < areas.length; i++) {
areas[i] = new JTextArea();
heights[i] = rnd.nextInt(FRAME_HEIGHT - 100);
mainPanel.add(areas[i]);
areas[i].setSize(BAR_WIDTH, heights[i]);
areas[i].setLocation((i + 1) * SPACING,
FRAME_HEIGHT - areas[i].getHeight());
areas[i].setText(toDigits(heights[i]));
}
btnStart = new JButton("Start");
btnStart.addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
setSleepTime(Integer.parseInt(txtSpeed.getText()));
sort();
} catch (NumberFormatException ex) {
//s
} catch (InterruptedException ex) {
//i
}
}
}
);
mainPanel.add(btnStart);
btnStart.setSize(100, 25);
btnStart.setLocation(0, 25);
txtSpeed = new JTextArea("50");
mainPanel.add(txtSpeed);
txtSpeed.setSize(100, 25);
txtSpeed.setLocation(0, 0);
lblSpeed = new JLabel("Sleep Time");
mainPanel.add(lblSpeed);
lblSpeed.setSize(100, 25);
lblSpeed.setLocation(110, 0);
this.add(mainPanel);
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void setSleepTime(int x) {
if (x >= 0) {
SLEEP_TIME = x;
} else {
SLEEP_TIME = 0;
}
}
public void sort() throws InterruptedException {
mergesort(0, heights.length - 1);
}
private void mergesort(int low, int high) throws InterruptedException {
if (low < high) {
int middle = low + (high - low) / 2;
mergesort(low, middle);
mergesort(middle + 1, high);
merge(low, middle, high);
}
}
private void merge(int low, int middle, int high) throws InterruptedException {
for (int i = low; i <= high; i++) {
helper[i] = heights[i];
}
int i = low;
int j = middle + 1;
int k = low;
while (i <= middle && j <= high) {
if (helper[i] <= helper[j]) {
heights[k] = helper[i];
updateAreaX(k);
Thread.currentThread().sleep(SLEEP_TIME);
i++;
} else {
heights[k] = helper[j];
updateAreaX(k);
Thread.currentThread().sleep(SLEEP_TIME);
j++;
}
k++;
}
// Copy the rest of the left side of the array into the target array
while (i <= middle) {
heights[k] = helper[i];
updateAreaX(k);
Thread.currentThread().sleep(SLEEP_TIME);
k++;
i++;
}
}
private String toDigits(int a) {
StringBuilder bdr = new StringBuilder();
while (a > 0) {
bdr.insert(0, Integer.toString(a % 10) + String.format("%n"));
a /= 10;
}
if (bdr.length() > 0) {
bdr.setLength(bdr.length() - 1);
}
return bdr.toString();
}
private void updateAreaX(int x) {
areas[x].setSize(BAR_WIDTH, heights[x]);
areas[x].setLocation(areas[x].getLocation().x,
FRAME_HEIGHT - areas[x].getHeight() - 40);
areas[x].setText(toDigits(heights[x]));
}
public static void main(String[] args) throws InterruptedException {
MergeSort sorter = new MergeSort();
sorter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sorter.setVisible(true);
}
}
The problem is that when i click the start button the whole JFrame freezes until everything is sorted and then it displays the result. If i don't start the sort() method via the button but write sorter.sort() in the public static void main() it works. How can I fix it? I guess I need to put the sorting on another thread or something but i have no idea how.
Your problem in next: you block EDT in your ActionListener, because of your frame freezes until actionPerformed() method will be exited. When you use Thread.sleep(...) it doesn't help Swing to repaint your frame.
Seems you need to use Swing Timer for updating. Also you can use SwingWorker for long time background processes.
Read about Concurency in Swing.

java swing setlocation doesn't work for second time

Frame has mainContentPane with layout manager = null
mainContentPane gamePanel, which holds jLabel Background at z-order 1 and a bunch of backgammon stones at z- order 0, if i set their positions before adding them to game panel, they end up in places i need them to be, but if im trying to set their places in game they all end ap at point 0,0 and calling get location says that its at a different location. Plese help me out on what im doing wrong with swing layout etc. setStones is the void that suppose to do it and getLocation after it ran gives locations I need, but everything is still at 0,0 on the screen
public class MainWindow extends JFrame implements ActionListener, ItemListener,
MouseListener, MouseMotionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private final int NUMBER_OF_STONES = 30;
private JPanel mainContentPane;
private JLayeredPane gamePanel;
private JLabel background;
private JMenuBar menuBar;
private JMenu menuGameTitle, aboutGameTitle;
private JMenuItem newGame, exit, help;
private JLabel[] stones;
private Dimension preferredSize;
private int stoneDragged = NUMBER_OF_STONES;
private int clickX = 0;
private int clickY = 0;
private HashMap<game.Color, String> stoneImage;
private HashMap<Integer, int[]> locations;
private int currStone;
public MainWindow() {
createGUI();
stoneImage = new HashMap<game.Color, String>();
stoneImage.put(game.Color.BLACK, "SilverNSH.jpg");
stoneImage.put(game.Color.WHITE, "GoldNSH.jpg");
locations = new HashMap<Integer, int[]>();
locations.put(0, new int[] {355,509});
locations.put(1, new int[] {655, 509});
.....
currStone = 0;
play();
}
private void createGUI() {
preferredSize = new Dimension(800, 600);
mainContentPane = new JPanel();
mainContentPane.setLayout(null);
mainContentPane.setPreferredSize(preferredSize);
gamePanel = new JLayeredPane();
gamePanel.setBounds(0, 0, 800, 600);
setSize(preferredSize);
background = new JLabel(new ImageIcon("BackGammon.jpg"));
// adding stones;
initStones();
for (int i = 0; i < stones.length; i++) {
gamePanel.add(stones[i], 0);
}
// setting background to 1 Z order
gamePanel.add(background, 1);
// set Z level to 0
for (int i = 0; i < stones.length; i++) {
gamePanel.setComponentZOrder(stones[i], 0);
}
mainContentPane.add(gamePanel);
setContentPane(mainContentPane);
pack();
}
private void initStones() {
stones = new JLabel[NUMBER_OF_STONES];
for (int i = 0; i < stones.length; i++) {
if (i < NUMBER_OF_STONES / 2) {
stones[i] = new JLabel(new ImageIcon("SilverNSH.gif"));
} else {
stones[i] = new JLabel(new ImageIcon("GoldNSH.gif"));
}
stones[i].setName(i + "");
stones[i].setSize(40,40);
stones[i].addMouseListener(this);
stones[i].addMouseMotionListener(this);
}
}
#Override
public void mousePressed(MouseEvent e) {
stoneDragged = Integer.parseInt(e.getComponent().getName());
clickX = e.getX();
clickY = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
// no stone is dragged
stoneDragged = NUMBER_OF_STONES;
}
#Override
public void mouseDragged(MouseEvent e) {
// off screen check
int yLoc;
int xLoc;
if (stoneDragged >= 0 && stoneDragged < NUMBER_OF_STONES) {
xLoc = e.getComponent().getX() + e.getX() - clickX;
yLoc = e.getComponent().getY() + e.getY() - clickY;
stones[stoneDragged].setLocation(xLoc, yLoc);
if (stones[stoneDragged].getX() <= 50)
stones[stoneDragged].setLocation(51, 51);
if (stones[stoneDragged].getY() <= 50)
stones[stoneDragged].setLocation(51, 51);
if (stones[stoneDragged].getX() >= 660)
stones[stoneDragged].setLocation(659, 509);
if (stones[stoneDragged].getY() >= 510)
stones[stoneDragged].setLocation(659, 509);
}
}
private void play() {
setStones(board.getAmountArray(), board.getColorArray());
}
private void setStones(int[] amountArray, game.Color[] colorArray) {
currStone = 0;
for (int i = 0; i < Board.NO_OF_PLAYABLE_FIELDS;i++){
if (amountArray[i] != 0) {
placeStones(i, amountArray[i], stoneImage.get(colorArray[i]));
}
}
}
private void placeStones(int startPos, int amount, String picture) {
for (int i = 0; i < amount;i++){
stones[currStone].setIcon(new ImageIcon(picture));;
if (startPos < 13) {
stones[currStone].setLocation(locations.get(startPos)[0], locations.get(startPos)[1] - i*40);
} else {
stones[currStone].setLocation(locations.get(startPos)[0], locations.get(startPos)[1] + i*40);
}
stones[currStone].setSize(40, 40);
currStone++;
}
}
}

My way to get X and Y index of buttons inside GridLayout

This is related to How to get X and Y index of element inside GridLayout? post and its answers.
For whatever reason none of them suggested to extend JButton to include its position in the grid and in associated array of buttons.
I have made the following illustration that simply displays button's coordinates when it's clicked.
Extended JButton:
package buttons_array;
import javax.swing.*;
#SuppressWarnings("serial")
public class ButtonWithCoordinates extends JButton {
int coordX;
int coordY;
public ButtonWithCoordinates(String buttonText, int coordX, int coordY) {
super(buttonText);
this.coordX = coordX;
this.coordY = coordY;
}
/**
* #return the coordX
*/
public int getCoordX() {
return coordX;
}
/**
* #return the coordY
*/
public int getCoordY() {
return coordY;
}
}
sample GUI:
package buttons_array;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonsArray implements ActionListener {
private ButtonWithCoordinates buttons[][];
private int nRows;
private int nCols;
private JFrame frame;
private JPanel panel;
public ButtonsArray(int x, int y) {
if (x > 0 && y > 0) {
nRows = x;
nCols = y;
buttons = new ButtonWithCoordinates[nRows][nCols];
for (int i=0; i < nRows; ++i) {
for (int j=0; j < nCols; ++j) {
buttons[i][j] = new ButtonWithCoordinates(" ", i, j);
buttons[i][j].addActionListener(this);
}
}
} else {
throw new IllegalArgumentException("Illegal array dimensions!!!");
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
ButtonWithCoordinates button = (ButtonWithCoordinates) e.getSource();
button.setText(button.getCoordX() + ", " + button.getCoordY());
}
public void GUI() {
if (buttons == null) { throw new NullPointerException("Array is not initialized!!!"); }
frame = new JFrame();
panel = new JPanel();
frame.setContentPane(panel);
panel.setLayout(new GridLayout(nRows, nCols));
for (int i=0; i < nRows; ++i) {
for (int j=0; j < nCols; ++j) {
panel.add(buttons[i][j]);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ButtonsArray(3, 5).GUI();
}
});
}
}
Now my questions:
Have I been reinventing the wheel here? I mean, is there a more straightforward way to achieve the same?
Is it in any way inferior to searching through the array each time we need to find the coordinates?
The original version of this example used extension:
GridButton extends JButton
The updated version was predicated on the colloquy seen here. While extension may be appropriate in some contexts, a few alternatives are mentioned here; a client property is particularly convenient. Identifying a button from its grid coordinates is also easy:
private static final int N = 5;
List<JButton> list = new ArrayList<>();
…
private JButton getGridButton(int r, int c) {
int index = r * N + c;
return list.get(index);
}

Categories