Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: GUI и Java FX приложения > создание таблицы в AWT


Автор: segmentation_fault 14.2.2006, 13:44
Доброго времени суток.
Вопрос у меня такой. Пишу GUI приложение на java 1.1 (соответственно на AWT). Сейчас пишу обычную табличку, (вроде JTable) и уже в самом начале траблы.
У меня есть класс рисующий одну клетку и еще один класс рисующий столбик клеток. Клетка рисуется более-менее но столбик прорисовывает только одну клетку (а не 10, как надо). Вот собственно код:


(Это класс который рисует столбик клеток)
Код

import java.awt.*;
import java.util.*;

public class TableColumn extends Panel {
    
    private Vector tableRow;
    private int rowSize;
    private final int cellHeight = 30;

    public TableColumn(int size) {
        //initialise the member variables
        rowSize = size;
        tableRow = new Vector(size);
        //TODO: create the row caption
        int i;
        for(i=0;i<size;i+=20) {tableRow.add(new TableCell(0, i, 30, 30, "sdf"));}
        

        setLayout(new BorderLayout());
        //cell = new TableCell(0, 0, 30, 30, "");
        //add(cell, BorderLayout.NORTH);  
        //setVisible(true);
    }
    
    public void paint(Graphics g) {
        Iterator iter = tableRow.iterator();
        
        while(iter.hasNext()) {
            TableCell tableCell = (TableCell)iter.next();
            tableCell.paint(g);
        }

        //cell.paint(g);
    }
    
    public Insets insets() {
        return new Insets(3,3,4,4);

    }
    
}

Проблема видимо в методе paint

а вот класс который рисует клетку:
Код

package newtable;

import java.awt.*;

public class TableCell extends Canvas {
//public class TableCell extends Panel {
    
    private int x;
    private int y;
    private int width;
    private int height;
    private String cellContents;
    
    
    public TableCell(int x, int y, int width, int height, String cellContents) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.cellContents = cellContents;
    }
    
    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        //g.drawString(cellContents, x+2, y+2);
        
        //now draw the dashed border around the cell
        drawDashedLine(g, new Point(x, y), new Point((x+width), y), false);  //-----  top border
        drawDashedLine(g, new Point(x, y), new Point(x, (y+height)), true);  //|      left border
        drawDashedLine(g, new Point(x, (y+height)), new Point((x+width), (y+height)), false);  //____   bottom border
        drawDashedLine(g, new Point((x+width), y), new Point((x+width), (y+height)), true);  //     | right border
        //slight bug: for some reason the last line isn't drawn
        
        //g.drawRect(x, y, width, height);
    }
    
    //written since theres no such function in awt 1.1 
    //line can be either horizontal or vertical, 
    //determined by the third argument to the function
    //TODO: make the code nicer and more concise
    public void drawDashedLine(Graphics g, Point begin, Point end, boolean vertical) {
        final int dashLength = 5;  //change to get differrent dash length
        if(vertical) {
            int length = (int)(end.getY() - begin.getY());//length of line
            int i;
            int thexcoord = (int)begin.getX();
            /*
            for(i=(int)begin.getY();i<length;i+=(dashLength*2)) {
                if((i+dashLength) > end.getY()) {g.drawLine(thexcoord, i, thexcoord, i+dashLength);} 
                else {g.drawLine(thexcoord, i, thexcoord, (int)end.getY());} //if the distance to the end of the line is less then the dashLength
            }
            */
            for(i=(int)begin.getX();i<length;i+=dashLength) {                
                if(g.getColor() == Color.WHITE) g.setColor(Color.BLACK);
                else g.setColor(Color.WHITE);
                if((i+dashLength) > end.getY()) {g.drawLine(thexcoord, i, thexcoord, i+dashLength);} 
                else {g.drawLine(thexcoord, i, thexcoord, (int)end.getY());} //if the distance to the end of the line is less then the dashLength              
            }
        }
        else { //horizontal line
            int length = (int)(end.getX() - begin.getX());//length of line
            int i;
            int theycoord = (int)begin.getY();
            
            //below routine should work but for some reason doesn't
            /*
            for(i=(int)begin.getX();i<length;i+=(dashLength*2)) {
                if((i+dashLength) > end.getX()) {g.drawLine(i, theycoord,  i+dashLength, theycoord);} 
                else {g.drawLine(i, theycoord, (int)end.getX(), theycoord);} //if the distance to the end of the line is less then the dashLength
            */
            for(i=(int)begin.getX();i<length;i+=dashLength) {                
                if(g.getColor() == Color.WHITE) g.setColor(Color.BLACK);
                else g.setColor(Color.WHITE);
                if((i+dashLength) > end.getX()) {g.drawLine(i, theycoord,  i+dashLength, theycoord);} 
                else {g.drawLine(i, theycoord, (int)end.getX(), theycoord);} //if the distance to the end of the line is less then the dashLength                
            }
        }
    }
}



Буду благодарен за любые комментарии (только пожалуйста цензурные, я знаю что код не ахти, но с awt я раньше не работал).
P.S. Я знаю что изобретаю велосипед и что легче это было бы зделать на swing но мне сказали что надо писать именно на java 1.1.

Автор: COVD 14.2.2006, 16:42
поищите готовые реализации в интернете, они были для 1.1, и на их базе делайте свою

Автор: powerOn 14.2.2006, 21:05
Цитата

Вопрос у меня такой. Пишу GUI приложение на java 1.1 (соответственно на AWT)


Маньяк, однако...... smile, но...

Раз уж ты решил изобрести велосипед, то посмотри как такой же велик изобрели разработчики Swing. Скачай исходники их (они вроде на www.java.sun.com имеются) JTable, проследи мысли, которые там реализуюстя и дерзай!

P. S. Создание компонентов с нуля не такое уж и легкое занятие, даже кнопку написать не всегда просто, а кстати JTable считается самым сложным компонентом из всех Swing. Но другие написали, и ты сможешь! Все в твоих руках было бы желание. smile

Автор: LSD 14.2.2006, 21:06
Пока нет времени попробовать, но для JDK 1.1 есть версия SWING поставляемая в виде отдельных классов.
Скачать ее можно http://java.sun.com/products/archive/index.html.

Автор: COVD 15.2.2006, 00:11
Цитата(LSD @ 14.2.2006, 21:06 Найти цитируемый пост)
Скачать ее можно отсюда.


обалдеть, 11 мег ! Обычно требование использовать 1.1 возникало при создании апплетов, но сейчас таких браузеров мало осталось, в основном у корпоративных клиентов, у которых софтвер централизовано апгрейдится.

Автор: segmentation_fault 15.2.2006, 01:36
LSD, огромное спасибо! Это наверное самый лучший вариант.
Кстати решение писать ГУИ на 1.1 принимал не я, я не мазохист (во всяком случае не до такой степени smile ).
Спасибо всем остальным кто ответил.

Автор: Hroft 16.2.2006, 17:12
А вообще, по-моему, нужно поставить GridLayout(1,size) вместо Border, и устанавливать его перед add'ами.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)