简体   繁体   中英

using jTable data to jTextField using jComboBox list

I have a jComboBox which supposedly contains data from a jTable . My combobox lists are

  • Archer
  • Knight
  • Rogue
  • Mage

What I want is if a Knight is chosen from the combobox I want the data of Knight from the jTable to be imported to a specific jTextField .

I have a jTextField1 as STR, jTextField2 as AGI, and so on..

How do I code these instructions?

jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"Archer",  new Double(5.0),  new Double(12.0),  new Double(6.0),  new Double(3.0),  new Double(4.0)},
            {"Knight",  new Double(14.0),  new Double(4.0),  new Double(10.0),  new Double(1.0),  new Double(1.0)},
            {"Rogue",  new Double(6.0),  new Double(18.0),  new Double(3.0),  new Double(4.0),  new Double(5.0)},
            {"Mage",  new Double(3.0),  new Double(4.0),  new Double(4.0),  new Double(18.0),  new Double(17.0)}
        },
        new String [] {
            "Specializations", "STR", "AGI", "CON", "INT", "WIS"
        }

I think you can make a Heroe Class, to create your heroes (Wrap the values in a class and override the toString() method.)

class ComboItem
{
private String key;
private String value;

public ComboItem(String key, String value)
{
    this.key = key;
    this.value = value;
}

@Override
public String toString()
{
    return key;
}

public String getKey()
{
    return key;
}

public String getValue()
{
    return value;
}

Add the ComboItem to your comboBox.

comboBox.addItem(new ComboItem("Visible String 1", "Value 1"));
comboBox.addItem(new ComboItem("Visible String 2", "Value 2"));
comboBox.addItem(new ComboItem("Visible String 3", "Value 3"));

Whenever you get the selected item.

Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();

If the data in the combobox are in the same order as in jTable:

int selectedIndex = jComboBox1.getSelectedIndex();
    Object valueAt0 = jTable1.getModel().getValueAt(selectedIndex, 0);
    Object valueAt1 = jTable1.getModel().getValueAt(selectedIndex, 1);
    jTextField1.setText("" + valueAt0 + " " + valueAt1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM