elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: AIO elhacker.NET 2021 Compilación herramientas análisis y desinfección malware


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  Pintar celdas de JTable al hacer clic
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Pintar celdas de JTable al hacer clic  (Leído 2,530 veces)
Zoik

Desconectado Desconectado

Mensajes: 91


Ver Perfil
Pintar celdas de JTable al hacer clic
« en: 23 Junio 2014, 14:06 pm »

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
  1. package base;
  2.  
  3. import graphics.Gui;
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) {
  8. new Gui();
  9. }
  10.  
  11. }
  12.  

Código
  1. package graphics;
  2.  
  3. import java.awt.event.WindowAdapter;
  4. import java.awt.event.WindowEvent;
  5. import javax.swing.JFrame;
  6. import javax.swing.JTable;
  7.  
  8. public class Gui extends JFrame
  9. {
  10.  
  11. /**
  12. *
  13. */
  14. private static final long serialVersionUID = 1L;
  15. private ExampleTableModel model = new ExampleTableModel();
  16. private JTable table = new JTable(model);
  17.  
  18. public Gui()
  19. {
  20. table.setRowHeight(30);
  21. table.setTableHeader(null);
  22. table.setCellSelectionEnabled(true);
  23. table.setCellSelectionEnabled(false);
  24. MyDefaultTableCellRenderer renderer = new MyDefaultTableCellRenderer();
  25. table.setDefaultRenderer(String.class, renderer);  
  26. JFrame frame = new JFrame();
  27. frame.setSize(500, 500);
  28. frame.addWindowListener(
  29. {
  30. public void windowClosing(WindowEvent e)
  31. {
  32. System.exit(0);
  33. }
  34. }
  35. );
  36. frame.getContentPane().add(table);
  37. frame.setResizable(false);
  38. frame.setVisible( true );
  39. }
  40. }
  41.  

Código
  1. package graphics;
  2.  
  3. import javax.swing.table.AbstractTableModel;
  4.  
  5. public class ExampleTableModel extends AbstractTableModel
  6. {
  7.    /**
  8. *
  9. */
  10. private static final long serialVersionUID = 1L;
  11. private final String[] columnNames = {"", "", "", "", "", "", "", "", "", "", "", "", ""};
  12.    final Object[][] data = {
  13.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  14.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  15.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  16.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  17.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  18.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  19.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  20.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  21.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  22.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  23.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  24.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  25.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  26.        {"", "", "", "", "", "", "", "", "", "", "", "", ""}
  27.    };
  28.  
  29.    @SuppressWarnings("unchecked")
  30. public Class getColumnClass(int column)
  31.    {
  32.        return getValueAt(0, column).getClass();
  33.    }
  34.    public int getColumnCount()
  35.    {
  36.        return columnNames.length;
  37.    }
  38.    public String getColumnName( int column )
  39.    {
  40.        return columnNames[column];
  41.    }
  42.    public int getRowCount()
  43.    {
  44.        return data.length;
  45.    }
  46.    public Object getValueAt( int row, int column )
  47.    {
  48.        return data[row][column];
  49.    }
  50.    public void setValueAt(Object value, int row, int column)
  51.    {
  52.     data[row][column] = value;
  53.    }
  54. }

Código
  1. package graphics;
  2.  
  3. import java.awt.Color;
  4. import java.awt.Component;
  5. import javax.swing.JTable;
  6. import javax.swing.table.DefaultTableCellRenderer;
  7.  
  8. public class MyDefaultTableCellRenderer  extends DefaultTableCellRenderer
  9. {
  10.  
  11. /**
  12. *
  13. */
  14. private static final long serialVersionUID = 1L;
  15. private Color [] colors = {Color.WHITE,
  16. Color.BLACK};
  17.  
  18. public Component getTableCellRendererComponent
  19. (JTable table, Object value, boolean isSelected,
  20. boolean hasFocus, int row, int column)
  21. {
  22. Component cell = super.getTableCellRendererComponent
  23. (table, value, isSelected, hasFocus, row, column);
  24.  
  25. setBorder(noFocusBorder);
  26.  
  27. if(row == table.getSelectedRow() && column == table.getSelectedColumn()) {
  28. System.out.println("Recorriendo " + row + " - " + column + "\nSeleccionada " + table.getSelectedRow() + " - " + table.getSelectedColumn());
  29. if(cell.getBackground().equals(colors[1]))
  30. {
  31. System.out.println("Pinto Blanco");
  32. cell.setBackground(Color.WHITE);
  33. } else if(cell.getBackground().equals(colors[0]))
  34. {
  35. System.out.println("Pinto Negro");
  36. cell.setBackground(Color.BLACK);
  37. }
  38. }
  39.  
  40. return cell;
  41. }
  42.  
  43. }
  44.  

Un saludo y gracias de antemano


En línea

Zoik

Desconectado Desconectado

Mensajes: 91


Ver Perfil
Re: Pintar celdas de JTable al hacer clic
« Respuesta #1 en: 24 Junio 2014, 19:37 pm »

Buenas gente.

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

Código
  1. package base;
  2.  
  3. import graphics.Gui;
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) {
  8. new Gui();
  9. }
  10.  
  11. }

Código
  1. package graphics;
  2.  
  3. import java.awt.event.MouseEvent;
  4. import java.awt.event.MouseListener;
  5. import java.awt.event.WindowAdapter;
  6. import java.awt.event.WindowEvent;
  7.  
  8. import javax.swing.JFrame;
  9. import javax.swing.JTable;
  10.  
  11. public class Gui extends JFrame implements MouseListener
  12. {
  13.  
  14. /**
  15. *
  16. */
  17. private static final long serialVersionUID = 1L;
  18. private ExampleTableModel model = new ExampleTableModel();
  19. private JTable table = new JTable(model);
  20. private MyDefaultTableCellRenderer renderer;
  21.  
  22. public Gui()
  23. {
  24. table.setRowHeight(30);
  25. table.setTableHeader(null);
  26. table.setCellSelectionEnabled(false);
  27. table.addMouseListener(this);
  28. renderer = new MyDefaultTableCellRenderer();
  29. table.setDefaultRenderer(String.class, renderer);  
  30. JFrame frame = new JFrame();
  31. frame.setSize(500, 500);
  32. frame.addWindowListener(
  33. {
  34. public void windowClosing(WindowEvent e)
  35. {
  36. System.exit(0);
  37. }
  38. }
  39. );
  40. frame.getContentPane().add(table);
  41. frame.setResizable(false);
  42. frame.setVisible( true );
  43. }
  44.  
  45. public void mouseClicked(MouseEvent e)
  46. {
  47.  
  48. }
  49.  
  50. public void mouseEntered(MouseEvent arg0)
  51. {
  52.  
  53. }
  54.  
  55. public void mouseExited(MouseEvent arg0)
  56. {
  57.  
  58. }
  59.  
  60. public void mousePressed(MouseEvent arg0)
  61. {
  62. int check = renderer.checkContainsCoordinates(table.getSelectedRow(), table.getSelectedColumn());
  63. if(check == -1)
  64. {
  65. System.out.println("Agrego");
  66. renderer.addCoordinate(table.getSelectedRow(), table.getSelectedColumn());
  67. } else if(check != -1)
  68. {
  69. System.out.println("Borro");
  70. renderer.removeCoordinate(check);
  71. }
  72. table.repaint();
  73. }
  74.  
  75. public void mouseReleased(MouseEvent arg0)
  76. {
  77.  
  78. }
  79. }

Código
  1. package graphics;
  2.  
  3. import javax.swing.table.AbstractTableModel;
  4.  
  5. public class ExampleTableModel extends AbstractTableModel
  6. {
  7.    /**
  8. *
  9. */
  10. private static final long serialVersionUID = 1L;
  11. private final String[] columnNames = {"", "", "", "", "", "", "", "", "", "", "", "", ""};
  12.    final Object[][] data = {
  13.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  14.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  15.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  16.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  17.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  18.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  19.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  20.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  21.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  22.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  23.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  24.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  25.        {"", "", "", "", "", "", "", "", "", "", "", "", ""},
  26.        {"", "", "", "", "", "", "", "", "", "", "", "", ""}
  27.    };
  28.  
  29.    @SuppressWarnings("unchecked")
  30. public Class getColumnClass(int column)
  31.    {
  32.        return getValueAt(0, column).getClass();
  33.    }
  34.    public int getColumnCount()
  35.    {
  36.        return columnNames.length;
  37.    }
  38.    public String getColumnName( int column )
  39.    {
  40.        return columnNames[column];
  41.    }
  42.    public int getRowCount()
  43.    {
  44.        return data.length;
  45.    }
  46.    public Object getValueAt( int row, int column )
  47.    {
  48.        return data[row][column];
  49.    }
  50.    public void setValueAt(Object value, int row, int column)
  51.    {
  52.     data[row][column] = value;
  53.    }
  54. }

Código
  1. package graphics;
  2.  
  3. import java.awt.Component;
  4. import java.util.ArrayList;
  5.  
  6. import javax.swing.JTable;
  7. import javax.swing.table.DefaultTableCellRenderer;
  8.  
  9. import staticvar.staticvar;
  10.  
  11. public class MyDefaultTableCellRenderer extends DefaultTableCellRenderer
  12. {
  13.  
  14. /**
  15. *
  16. */
  17. private static final long serialVersionUID = 1L;
  18. private ArrayList<Integer[]> coordinates = new ArrayList<Integer[]>();
  19.  
  20. public void addCoordinate(int row, int col)
  21. {
  22. coordinates.add(new Integer [] {row, col});
  23. }
  24.  
  25. public void removeCoordinate(int position)
  26. {
  27. coordinates.remove(position);
  28. }
  29.  
  30. public Component getTableCellRendererComponent
  31. (JTable table, Object value, boolean isSelected,
  32. boolean hasFocus, int row, int col)
  33. {
  34.  
  35. if(checkContainsCoordinates(row, col) != -1)
  36. {
  37. this.setBackground(staticvar.colors[1]);
  38. } else if(checkContainsCoordinates(row, col) == -1)
  39. {
  40. this.setBackground(staticvar.colors[0]);
  41. }
  42.  
  43. return this;
  44. }
  45.  
  46. public int checkContainsCoordinates(int row, int col)
  47. {
  48. for(int i = 0; i < coordinates.size(); i++)
  49. {
  50. if(coordinates.get(i)[0] == row && coordinates.get(i)[1] == col)
  51. {
  52. return i;
  53. }
  54. }
  55. return -1;
  56. }
  57.  
  58. }

Código
  1. package staticvar;
  2.  
  3. import java.awt.Color;
  4.  
  5. public class staticvar {
  6.  
  7. public static final Color [] colors = {Color.WHITE,
  8. Color.BLACK};
  9.  
  10. }

Un saludo


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
JTable pintar en celldas
Java
sapito169 1 2,589 Último mensaje 18 Enero 2009, 22:26 pm
por Chuidiang
JTable tamaño de celdas ajustable y mostrar texto completo
Java
marvic 1 29,332 Último mensaje 12 Abril 2009, 19:57 pm
por marvic
Se podría hacer clic en un tabulador
Programación Visual Basic
Senior++ 6 2,642 Último mensaje 16 Junio 2011, 15:13 pm
por Senior++
Mostrar menú al hacer clic en un listview
ASM
.:UND3R:. 5 4,118 Último mensaje 13 Mayo 2013, 03:27 am
por .:UND3R:.
Deshabilitar Editar Celdas JTable
Java
MiguelP 2 11,496 Último mensaje 29 Abril 2014, 20:08 pm
por MiguelP
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines