在 gui 中显示树图 java

Display tree map in gui java

首先,我对 Java 完全陌生,所以请您尽可能简单地解释一下!

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

我想在屏幕上显示它,但不知道如何操作。

我确实遇到了 JTable。重新搜索后,我感到困惑,因为我的列是一个字符串数组(只是两列的标题),而我的数据是一个树图。在网上进一步查看后,我发现我应该 create a table model 但在阅读完这篇文章后,我并没有真正理解我需要做什么。任何帮助将不胜感激!

提前致谢。

您想要显示内容的方式因您的要求或信息以用户友好的方式显示的方式而异。

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();
}   
}

如果这对您有帮助或者您有任何疑问,请告诉我。编码愉快! :)

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

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

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

为了做到最低限度,AbstractTableModel 只需要实现 getRowCountgetColumnCountgetValueAt

如果您需要模型是 editable,那么实现它会变得更加复杂。

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);
    }
}