在gui java中显示树图

时间:2015-04-25 21:47:03

标签: java swing jtable treemap

首先,我是Java新手,所以请您尽可能简单地解释一下!

所以我有一个树形图,键是指向字符串的日期。

我想在屏幕上显示,但不知道该怎么做。

我确实遇到过JTable。在重新研究之后,我很困惑,因为我的列是一个字符串数组(只是两列的标题),而我的数据是树图。在进一步在线查看之后,我发现我应该create a table model,但在阅读完之后,我并不真正理解我需要做什么。任何帮助将非常感谢!

提前致谢。

2 个答案:

答案 0 :(得分:3)

您希望显示内容的方式取决于您的要求或信息如何以用户友好的方式显示。

JTable是一个很好的方法,JTree也是一个很好的方法,尽管如此,我认为JTable是一种更标准的方法。

我采用了一种方法,我实施得非常快,试图简化所有复杂的内容,并实现我从您的问题中理解的内容:

public class TableExample {

//Asuming you have a treemap like this
static Map<Date, String> sampleMap = new TreeMap<Date, String>();

//Initialize the sample treemap with some values (this static block will execute the first time we run this app)
static {
    sampleMap.put(createBirthdayFromString("14/02/1990"), "Marcelo's Birthday");
    sampleMap.put(createBirthdayFromString("29/06/1989"), "Oscar's Birthday");
    sampleMap.put(createBirthdayFromString("21/04/1985"), "Carlos' Birthday");
}

//This will create a date object based on a given String
public static Date createBirthdayFromString(String dateAsString) {
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    Date convertedDate = null;
    try {
        convertedDate = formatter.parse(dateAsString);
    } catch (ParseException e) {
        // Print stacktrace and default to current Date
        e.printStackTrace();
        convertedDate = new Date();
    }
    return convertedDate;
}

public void init() {
    //Create the JFrame to display the table
    JFrame mainFrame = new JFrame();
    mainFrame.setTitle("My Table Example");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setSize(520, 520);

    //Then a panel to keep our Main frame available to display other contents
    JPanel myPanel = new JPanel();
    myPanel.setBounds(mainFrame.getBounds());
    myPanel.setBackground(Color.DARK_GRAY);
    myPanel.setVisible(true);

    //Add the panel to the frame
    mainFrame.add(myPanel);

    //You will need to specify the columns you want to display in your table, for this case:
    String[] columns = new String[] {"Birthday", "Name"};

    //Then you can create a table model with zero rows at the beginning
    //The table model will define how the data in your table would be displayed
    //As well as provide some useful methods if you want to add certain events or edition capabilities :)
    DefaultTableModel defaultModel = new DefaultTableModel(columns, 0);

    //Then you create your table based on your model
    JTable myTable = new JTable(defaultModel);

    //Then you will like to fill each table row with the data of your treemap

    //We iterate over your map to obtain the records
    for (Map.Entry<Date, String> entry : sampleMap.entrySet()) {
        defaultModel.addRow(new Object[] {entry.getKey(), entry.getValue()});
    }

    //Now add the table to your frame
    myPanel.add(new JScrollPane(myTable));

    //Set the frame visible
    mainFrame.setVisible(true);
}

/**
 * Main method that will execute this example
 * @param args
 */
public static void main(String[] args) {
    new TableExample().init();
}   
}

如果这有助于您或您有任何疑问,请告诉我。快乐的编码! :)

答案 1 :(得分:1)

表模型负责管理JTable显示的数据。

JTable中的条目由行索引和列索引引用,但TreeMap没有这种排列。我们仍然可以通过使用计数器迭代条目集来引用TreeMap中的条目,就像它们被索引一样。

这类似于,例如,迭代链表以按索引检索元素。

要做到最低限度,AbstractTableModel只需要实施getRowCountgetColumnCountgetValueAt

如果您需要模型可编辑,那么实现它会变得更复杂。

class TreeMapTableModel extends AbstractTableModel {
    private TreeMap<?, ?> data;

    TreeMapTableModel(TreeMap<?, ?> data) {
        this.data = data;
    }

    private Map.Entry<?, ?> getEntryFor(int row) {
        int index = 0;
        for( Map.Entry<?, ?> entry : data.entrySet() ) {
            if( index == row )
                return entry;
            index++;
        }
        throw outOfBounds("row", row);
    }

    @Override
    public Object getValueAt(int row, int column) {
        Map.Entry<?, ?> entry = getEntryFor( row );

        switch( column ) {
            case 0: return entry.getKey();
            case 1: return entry.getValue();

            default: throw outOfBounds("column", column);
        }
    }

    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public int getColumnCount() {
        return 2;
    }

    private static IndexOutOfBoundsException outOfBounds(
            String parameter, int value) {
        return new IndexOutOfBoundsException(
            parameter + "=" + value);
    }
}