Pintar celdas de JTable al hacer clic

Iniciado por Zoik, 23 Junio 2014, 14:06 PM

0 Miembros y 1 Visitante están viendo este tema.

Zoik

Primeramente buenas a todos.

Bueno estoy empezando a mirar temas de heurísitica y he empezado haciendo la búsqueda del recorrido mas corto con el algoritmo A*.

Hasta aquí todo bien, pero me surge un problema y es que para testear todo esto, quiero hacer una JTable que al yo clicar en una celda de color blanco esta se pinte de color negro para dar a entender a la aplicación que es una celda infranqueable por el contrario si clico en una negra, se volverá blanca.

Básicamente el problema es que cuando selecciono la celda blanca, me vuelve negras esa y todas las siguientes.

A ver si me pudieseis echar una mano.

Código (java) [Seleccionar]
package base;

import graphics.Gui;

public class Main {

public static void main(String[] args) {
new Gui();
}

}


Código (java) [Seleccionar]
package graphics;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JTable;

public class Gui extends JFrame
{

/**
*
*/
private static final long serialVersionUID = 1L;
private ExampleTableModel model = new ExampleTableModel();
private JTable table = new JTable(model);

public Gui()
{
table.setRowHeight(30);
table.setTableHeader(null);
table.setCellSelectionEnabled(true);
table.setCellSelectionEnabled(false);
MyDefaultTableCellRenderer renderer = new MyDefaultTableCellRenderer();
table.setDefaultRenderer(String.class, renderer); 
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
frame.getContentPane().add(table);
frame.setResizable(false);
frame.setVisible( true );
}
}


Código (java) [Seleccionar]
package graphics;

import javax.swing.table.AbstractTableModel;

public class ExampleTableModel extends AbstractTableModel
{
    /**
*
*/
private static final long serialVersionUID = 1L;
private final String[] columnNames = {"", "", "", "", "", "", "", "", "", "", "", "", ""};
    final Object[][] data = {
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "", "", "", "", ""}
    };
   
    @SuppressWarnings("unchecked")
public Class getColumnClass(int column)
    {
        return getValueAt(0, column).getClass();
    }
    public int getColumnCount()
    {
        return columnNames.length;
    }
    public String getColumnName( int column )
    {
        return columnNames[column];
    }
    public int getRowCount()
    {
        return data.length;
    }
    public Object getValueAt( int row, int column )
    {
        return data[row][column];
    }
    public void setValueAt(Object value, int row, int column)
    {
    data[row][column] = value;
    }
}


Código (java) [Seleccionar]
package graphics;

import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

public class MyDefaultTableCellRenderer  extends DefaultTableCellRenderer
{

/**
*
*/
private static final long serialVersionUID = 1L;
private Color [] colors = {Color.WHITE,
Color.BLACK};

public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
Component cell = super.getTableCellRendererComponent
(table, value, isSelected, hasFocus, row, column);

setBorder(noFocusBorder);

if(row == table.getSelectedRow() && column == table.getSelectedColumn()) {
System.out.println("Recorriendo " + row + " - " + column + "\nSeleccionada " + table.getSelectedRow() + " - " + table.getSelectedColumn());
if(cell.getBackground().equals(colors[1]))
{
System.out.println("Pinto Blanco");
cell.setBackground(Color.WHITE);
} else if(cell.getBackground().equals(colors[0]))
{
System.out.println("Pinto Negro");
cell.setBackground(Color.BLACK);
}
}

return cell;
}

}


Un saludo y gracias de antemano

Zoik

Buenas gente.

Ya lo tengo solucionado, lo dejo por aquí por si a alguien le interesa.

Código (java) [Seleccionar]
package base;

import graphics.Gui;

public class Main {

public static void main(String[] args) {
new Gui();
}

}


Código (java) [Seleccionar]
package graphics;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JTable;

public class Gui extends JFrame implements MouseListener
{

/**
*
*/
private static final long serialVersionUID = 1L;
private ExampleTableModel model = new ExampleTableModel();
private JTable table = new JTable(model);
private MyDefaultTableCellRenderer renderer;

public Gui()
{
table.setRowHeight(30);
table.setTableHeader(null);
table.setCellSelectionEnabled(false);
table.addMouseListener(this);
renderer = new MyDefaultTableCellRenderer();
table.setDefaultRenderer(String.class, renderer);  
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
frame.getContentPane().add(table);
frame.setResizable(false);
frame.setVisible( true );
}

public void mouseClicked(MouseEvent e)
{

}

public void mouseEntered(MouseEvent arg0)
{

}

public void mouseExited(MouseEvent arg0)
{

}

public void mousePressed(MouseEvent arg0)
{
int check = renderer.checkContainsCoordinates(table.getSelectedRow(), table.getSelectedColumn());
if(check == -1)
{
System.out.println("Agrego");
renderer.addCoordinate(table.getSelectedRow(), table.getSelectedColumn());
} else if(check != -1)
{
System.out.println("Borro");
renderer.removeCoordinate(check);
}
table.repaint();
}

public void mouseReleased(MouseEvent arg0)
{

}
}


Código (java) [Seleccionar]
package graphics;

import javax.swing.table.AbstractTableModel;

public class ExampleTableModel extends AbstractTableModel
{
   /**
*
*/
private static final long serialVersionUID = 1L;
private final String[] columnNames = {"", "", "", "", "", "", "", "", "", "", "", "", ""};
   final Object[][] data = {
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""},
       {"", "", "", "", "", "", "", "", "", "", "", "", ""}
   };
   
   @SuppressWarnings("unchecked")
public Class getColumnClass(int column)
   {
       return getValueAt(0, column).getClass();
   }
   public int getColumnCount()
   {
       return columnNames.length;
   }
   public String getColumnName( int column )
   {
       return columnNames[column];
   }
   public int getRowCount()
   {
       return data.length;
   }
   public Object getValueAt( int row, int column )
   {
       return data[row][column];
   }
   public void setValueAt(Object value, int row, int column)
   {
    data[row][column] = value;
   }
}


Código (java) [Seleccionar]
package graphics;

import java.awt.Component;
import java.util.ArrayList;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;

import staticvar.staticvar;

public class MyDefaultTableCellRenderer extends DefaultTableCellRenderer
{

/**
*
*/
private static final long serialVersionUID = 1L;
private ArrayList<Integer[]> coordinates = new ArrayList<Integer[]>();

public void addCoordinate(int row, int col)
{
coordinates.add(new Integer [] {row, col});
}

public void removeCoordinate(int position)
{
coordinates.remove(position);
}

public Component getTableCellRendererComponent
(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int col)
{

if(checkContainsCoordinates(row, col) != -1)
{
this.setBackground(staticvar.colors[1]);
} else if(checkContainsCoordinates(row, col) == -1)
{
this.setBackground(staticvar.colors[0]);
}

return this;
}

public int checkContainsCoordinates(int row, int col)
{
for(int i = 0; i < coordinates.size(); i++)
{
if(coordinates.get(i)[0] == row && coordinates.get(i)[1] == col)
{
return i;
}
}
return -1;
}

}


Código (java) [Seleccionar]
package staticvar;

import java.awt.Color;

public class staticvar {

public static final Color [] colors = {Color.WHITE,
Color.BLACK};

}


Un saludo