Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> JTableRenderer 
:(
    Опции темы
Yulers
Дата 1.5.2008, 18:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 6
Регистрация: 1.5.2008

Репутация: нет
Всего: нет



Я пытаюсь создать программу которая би позвлоляла менят цвет  cell в JTable dinamically.  весь Table например будет голубого цвета а когда я получу значение из класса Solver с позициеи он понеяет на желтии. Help please
public class ColorTable
{
     static class ColorTableModel extends AbstractTableModel
    { 
       String [] headers = new String []{"","","","","","","","","",""}; //
       Object[][] data = new Object[4][4];
       ColorTableModel(int ctmCol, int ctmRow)
        {   
            int userCol = ctmCol;
            int userRow = ctmRow;
           
            for (int row = 0; row < userCol; row++)
                for(int col = 0; col<userRow; col++)
                {        
                   {   
                       data[row][col] = new Color(0,0,255);
                     }
                 } 
            
        }
    public int getRowCount(){return data.length;}
    public int getColumnCount(){return headers.length;} 
    public String getColumnName(int column){return headers[column];} 
  
    public Class getColumnClass(int column){return Color.class;
    }
  
    public boolean isCellEditiable(int rowIndex, int columnIndex){return true;}
  
  }
     
     static class ICColorRenderer implements TableCellRenderer
  {   
        
      JButton button = new JButton();
      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
      {   
            if (column ==0 && row==0)
            {
               button.setBackground(Color.YELLOW); 
            } 
            else button.setBackground((Color)value);
  
            return button;
         }
        
  }
    
    public ColorTable(int sCol, int sRow)
    {   int cCol = sCol;
        int cRow = sRow;
        JFrame frame = new JFrame("Table with color and and on different color button");
        frame.setSize(300,300);
        frame.setVisible(true);
        JTable table = new JTable(new ColorTableModel(cCol, cRow));
        table.setDefaultRenderer(Color.class, new ICColorRenderer());
        frame.getContentPane().add(table);
    }
    
   public int setSolverRandomLocation(int location)
    {   
        return location;
    }
}

public class Solver 
{   
    private InitialState istate;
    private Grid myGrid;
    protected ColorTable table;
     public Solver(InitialState init)
    {
        istate = init;
        myGrid = new Grid(init.numberRows, init.numberCols); 
        table = new ColorTable(init.numberRows,init.numberCols);
        
    }
    public void Runsimulation()
    {  
       
        for (int i = 0; i<istate.initCellValue; i++)
        {   
            Random generator = new Random();
            int x = generator.nextInt(2); //generate random number between 0 and 3. 100 is the number of cells on the screen
            int y = generator.nextInt(2); // generate random number between 0 and 3
            System.out.println("Before I will put cell on the screen I will print all random numbers"+x+y);
            int k = x+y;
            table.setSolverRandomLocation(k);
            Location RandomLocation = new Location(x, y);
            boolean randomloc = myGrid.IsFree(RandomLocation);
              if (randomloc != false)
              {
                 
                  myGrid.SetCellrandomly(RandomLocation);
                  
              }
        }
          
         
        
              
             for (int j=0; j<10; j++) // when the expiremnet is finished
             { 
                 ArrayList a = myGrid.GetCellList(); // we have got arraylist of cell location now I know whare all cells are. 
                int  t =  a.size(); // 
                 
                 Random generator = new Random();
                 int g = generator.nextInt(t); // pick randomly array position of the cell
                
                 System.out.println("Size of the array"+t);
                 System.out.println("The random generator of the cell:  "+g);
                 Location goLocation = new Location(myGrid.GetFreeNeighbourhoodCell((Location) a.get(g)));// sending to the location 
                 
                 myGrid.MoveCell((Location) a.get(g), goLocation);
          myGrid.killcell((Location) a.get(g));
                 // timestamp ++;
             }
          }
      
}

PM MAIL   Вверх
dorogoyIV
Дата 2.5.2008, 03:35 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1503
Регистрация: 26.3.2007

Репутация: 36
Всего: 46



я не стал читать код, и никто не будет читать код - эти кракозялбы
пользуйся кнопкой "Код"
на твой вопрос ответ - пиши свой Renderer
PM MAIL   Вверх
Yulers
Дата 2.5.2008, 13:22 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 6
Регистрация: 1.5.2008

Репутация: нет
Всего: нет



Ну так оно. Не получишь правелЬный ответ если не умеешь задать правилЬниый ответ. Попытаюсь снова. у меня ест несколько классов Driver - main  Diver initialise Solver. 
Solver initialised  Grid . Теперья пытаюсь представит все это для " user" as GUI. Я решила исполЬзоватЬ JTable. для того чтобы показать картинку. это своего рода "Cellular Automata" все клетки белые если они пустые или черние если заняты. Solver manages JTable. теперь вопрос как менять цвет в jTable работаюшим по правилам solver. может быть  JTable не самий лучшии вариант. Я просто потеряласЬ
PM MAIL   Вверх
dorogoyIV
Дата 2.5.2008, 14:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1503
Регистрация: 26.3.2007

Репутация: 36
Всего: 46



1. я же просил оформить в код  smile 
2. там ты пишеш свой рендерер, который возвращает JButton, зачем? лучше уж JLabel возвратить!!!
    на JLabel клади любую картинку
3. этот код не запускается
PM MAIL   Вверх
Yulers
Дата 2.5.2008, 15:29 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 6
Регистрация: 1.5.2008

Репутация: нет
Всего: нет



Код

package cellsimulationdifferent3;

import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.util.*;
import java.lang.*;
public class Driver {
    
    public InitialState SetInitState()
    {
        InitialState i = new InitialState();//create a new class 
        
        i.numberRows = 4;//number of rows and columns
        i.numberCols = 4;
        i.finalTime  = 10;//when simulation will stop
        i.initCellValue = 2;//one cell on the grid
        
        return i;
    }
    
    public static void main(String[] args) {
        
                Driver d = new Driver();
                InitialState is = d.SetInitState(); 
                Solver       solv = new Solver(is);     
                solv.Runsimulation();
   }
}
package cellsimulationdifferent3;

import java.lang.*;
import java.util.*;
import java.awt.GridLayout;
import java.awt.Color;
import javax.swing.table.*;
import javax.swing.ScrollPaneLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Solver 
{   
    private InitialState istate;
    private Grid myGrid;
    protected ColorTable table;
     public Solver(InitialState init)
    {
        istate = init;
        myGrid = new Grid(init.numberRows, init.numberCols); 
        table = new ColorTable(init.numberRows,init.numberCols);
        
    }
    public void Runsimulation()
    {  
    for (int i = 0; i<istate.initCellValue; i++)
        {   
            Random generator = new Random();
            int x = generator.nextInt(2);
            int y = generator.nextInt(2);
            Location RandomLocation = new Location(x, y);
            boolean randomloc = myGrid.IsFree(RandomLocation);
              if (randomloc != false)
              {
                  myGrid.SetCellrandomly(RandomLocation); 
              }
        }
         for (int j=0; j<10; j++) 
             { 
                 ArrayList a = myGrid.GetCellList();              
                  int  t =  a.size(); 
                 
                 Random generator = new Random();
                 int g = generator.nextInt(t); 
                
                 System.out.println("Size of the array"+t);
                 System.out.println("The random generator of the cell:  "+g);
                 Location goLocation = new Location(myGrid.GetFreeNeighbourhoodCell((Location) a.get(g)));// sending to the location 
                 
                 myGrid.MoveCell((Location) a.get(g), goLocation);
             }
          }
      
}
package cellsimulationdifferent3;

import java.lang.*;
import java.util.*;
import java.util.ArrayList;
public class Grid
{
    Cell [][] state;
    int  nRows;
    int  nCols;
      
    public Grid(int rows, int cols)
    {
        nRows = rows;
        nCols = cols;
                state = new Cell[rows][cols];
        for(int i = 0; i < rows; i++) // filling the grid with null value
            for(int j = 0; j < cols; j++)
                state[i][j] = null;//value has not been set use null value to indicate that value has never been set
    }
         public int GetAnyFreeLocation()
        {  
            Random generator = new Random();
            int g = generator.nextInt(3); //generate random number between 0 and 3
            int h = generator.nextInt(3); // generate random number between 0 and 3
            int f = g*4+h; // return value of free location
            return f;
        }
       public void SetCellrandomly(Location currentLocation)
        {   
            int x = currentLocation.GetRow();
            int y = currentLocation.GetCol();
            Cell c  = new Cell(x, y);
            state[x][y] = c;
            System.out.println("Setting current location for the cells x and y"+x+y);
            
        }
       
         public boolean IsFree(Location currentLocation)// checking if it is occupied or not checking neighbouros of not
        {
            if (currentLocation == null)
            {
                return false;
            }
            if (state[currentLocation.GetRow()][currentLocation.GetCol()]== null)
                
                 return true;
        else     
                  return false;
                
        }
        public Location  GetFreeNeighbourhoodCell (Location currentLocation)
        {
             
             ArrayList myList = new ArrayList(); // check if it is not outside of the grid for an errors check 
              Location eLocation;
              Location wLocation;
              Location nLocation;
              Location sLocation;
             if (currentLocation.GetRow()+1<nRows)
             {
              nLocation = new Location(currentLocation.GetRow()+1, currentLocation.GetCol());
             }
             else 
                 nLocation = null;
              if (currentLocation.GetRow()-1>=0)
              {
                sLocation = new Location(currentLocation.GetRow()-1, currentLocation.GetCol());
              }
              else 
                  sLocation = null;
               if (currentLocation.GetCol()+1<nCols)
             {
              eLocation = new Location(currentLocation.GetRow(), currentLocation.GetCol()+1);
             }
             else 
                 eLocation = null;
              if (currentLocation.GetCol()-1>=0)
             {
              wLocation = new Location(currentLocation.GetRow(),currentLocation.GetCol()-1);
             }
             else 
                 wLocation = null;
         
             if (IsFree(eLocation)==false && IsFree(wLocation)==false && IsFree(nLocation)==false && IsFree(sLocation)==false              return null; 

                 String E = new String("East");
                 String W = new String("West");
                 String N = new String("North");
                 String S = new String("South");
         
                  if (IsFree(eLocation)==true)
                  myList.add(E);//add to the list East 
                  if (IsFree(wLocation)==true)
                  myList.add(W);// add to the list West
                  if (IsFree(nLocation)==true)
                  myList.add(N);//add to the list North
                  if (IsFree(sLocation)==true)
                  myList.add(S);//add to the list South
                  int Length  = myList.size();
                  System.out.println("Printing arraylist with directions"+myList);
                  int rand = (int) (Math.random()*Length);
                  if (myList.get(rand)==E)   
                     return  eLocation;      
                  if (myList.get(rand)==W)   
                     return wLocation;
                  if (myList.get(rand)==N)    
                     return nLocation;
                  else                      //(myList.get(rand)==S) //or s
                  
                     return sLocation;
                 
       }
        public ArrayList GetCellList()
        {    
            ArrayList<Location> result = new ArrayList<Location>();
            
            for (int i = 0; i< nRows; i++)
            {
                for(int j= 0; j < nCols; j++)
                {
                    if(state[i][j]!=null)
                    {   
                        result.add(new Location(i,j));
                    }
                    
                }
            }
            return result;
        }
        public Location MoveCell(Location currentLocation, Location newLocation)
        { 
                int currentX = currentLocation.GetRow();
                int currentY = currentLocation.GetCol();
                int newLocationX = newLocation.GetRow();
                int newLocationY = newLocation.GetCol();
               state[newLocation.GetRow()][newLocation.GetCol()] = state[currentLocation.GetRow()][currentLocation.GetCol()];
                SetCellrandomly(newLocation);
                 Cell c  = new Cell(newLocationX, newLocationY);
                 state[currentLocation.GetRow()][currentLocation.GetCol()] = null;
                 if (state[currentLocation.GetRow()][currentLocation.GetCol()] == null)
                 {
                    System.out.println("ok last coordinates where equall to null those coordinates"+currentLocation.GetRow()+ currentLocation.GetCol());
                 }
                return newLocation;
        }
        
      public int GetGridRow()
      {
          return nRows;
      }
      public int GetGridCol()
      {
          return nCols;
      }
}
package cellsimulationdifferent3;

public class InitialState {

    public int finalTime;
    public int numberRows;
    public int numberCols;
    public int initCellValue;
}
package cellsimulationdifferent3;

public class Location {
    public int row;
    public int col;
    public Location(int x, int y) 
    {
         row = x;
         col = y;
        
    }
    public Location(Location l) 
    {
        row = l.GetRow();
        col = l.GetCol();
        
    }
    public void SetRow(int x)
    {
        row = x;
    }
    public void SetCol(int y)
    {
        col = y;
    }
    public int GetRow()
    {
        return row;
    }
    public int GetCol()
    {
        return col;
    }
}
package cellsimulationdifferent3;
public class Cell 
{
    public Cell(int r, int c) // passing for set up history, when time has been created
    {   
        int row = r;
        int col = c;
        
        }
        
}
package cellsimulationdifferent3;
import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.util.*;
import java.lang.*;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.Color;
public class ColorTable{
     static class ColorTableModel extends DefaultTableModel
    { 
       String [] headers = new String []{"","","","","","","","","",""};
       Object[][] data = new Object[10][10];//should be the value from user 
       ColorTableModel(int ctmCol, int ctmRow)
        {   
            int userCol = ctmCol;
            int userRow = ctmRow;
                    for (int row = 0; row < userCol; row++)// userCol = i.numberRows  iz InitialState
                for(int col = 0; col<userRow; col++)//
                {        
                   {   
                       data[row][col] = new Color((int)255);
                     }
                 } 
            

                      
        }
    public int getRowCount(){return data.length;}//показывает ошибку
    public int getColumnCount(){return headers.length;} 
    public String getColumnName(int column){return headers[column];} 
    
    public Object getValueAt(int row, int column){return data[row][column];}
    public Class getColumnClass(int column){return Color.class;}
  
    public boolean isCellEditiable(int rowIndex, int columnIndex){return true;}
  
  }
     
     static class ICColorRenderer implements TableCellRenderer
  {   
        
      JButton button = new JButton();
      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
      {   
               button.setBackground((Color)value); // должен получит то же самое значение как Grid Class 
                                                                          // когда становитЬся occupied например желтыи
               return button;
         }
        
  }
    
    public ColorTable(int sCol, int sRow)
    {   int cCol = sCol;
        int cRow = sRow;
        JFrame frame = new JFrame("Table with color and and on different color button");
        frame.setSize(300,300);
        frame.setVisible(true);
        JTable table = new JTable(new ColorTableModel(cCol, cRow));
        table.setDefaultRenderer(Color.class, new ICColorRenderer());
        frame.getContentPane().add(table);
    }
    
   public int setSolverRandomLocation(int location)
    {   
        return location;
    }
}



Добавлено через 2 минуты и 57 секунд
Я не волшебник, но я учусЬ... надеюсЬ код не такои страшныИ и понятныи  smile Thank 
PM MAIL   Вверх
IgorJ
Дата 3.5.2008, 15:21 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 2
Регистрация: 3.5.2008

Репутация: нет
Всего: нет



я тебе постараюсь помочь.
правда меня забанили, ну да ладно, это мой косяк.
Цитата

Я не волшебник, но я учусЬ... надеюсЬ код не такои страшныИ и понятныи   Thank

это хорошо, что есть стремление!!!
рендерер пишется примерно так: (я его упростил на сколько мог)
Код

import java.awt.*;
import javax.swing.table.*;
import javax.swing.*;

public class ForYulers extends JFrame
{
 JTable table = new JTable(10, 10);

 public ForYulers()
 {
  for(int i=0; i < table.getColumnCount(); i++)
  {
   TableColumn tc = table.getColumnModel().getColumn(i);
   tc.setCellRenderer(new MyRenderer());
  }

  add(table);
 }

 public static void main(String [] args)
 {
  JFrame f = new ForYulers();
  f.setBounds(100, 100, 400, 300);
  f.setVisible(true);
  f.setDefaultCloseOperation(3);
 }
}

class MyRenderer extends JLabel
                 implements TableCellRenderer
{
 public Component getTableCellRendererComponent(JTable table,
                    Object value, boolean isSelected,
                    boolean hasFocus, int row, int column)
 {
  setIcon(new ImageIcon("myimage.gif")); // здесь твоя картинка
  return this;
 }
}

PM MAIL   Вверх
Yulers
Дата 3.5.2008, 16:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 6
Регистрация: 1.5.2008

Репутация: нет
Всего: нет



спасибо болЬшое!! обьяснЬят не всегда  хочется. Я пробобавала что такое же написать. а как вот соединитЬ s Solver. вот ето не получаеться. мне нужно взять части этого кода и применитЬ в JTable 
Код

  for (int i = 0; i<istate.initCellValue; i++)
        {   
            Random generator = new Random();
            int x = generator.nextInt(2);
            int y = generator.nextInt(2);
            Location RandomLocation = new Location(x, y);
            boolean randomloc = myGrid.IsFree(RandomLocation);
              if (randomloc != false)
              {
                  myGrid.SetCellrandomly(RandomLocation); 
              }


то есть  RandomLocation или value взятЬ из Solver. если например  RandomLocation = (0,0) то цвет клетки в  JTable должен быть чернии а весь осталЬнои  JTable белыи если это понятно. Вот это я не знаю как сделатЬ
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   jk1
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, jk1.

 
1 Пользователей читают эту тему (1 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: GUI и Java FX приложения | Следующая тема »


 




[ Время генерации скрипта: 0.1222 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.