Get input text without scanner

孤街浪徒 提交于 2019-12-24 21:45:58

问题


I work on a school project and I am now wondering if it is possible to get text from JTextField with get?

    // Textrutor
    JTextField textTitel = new JTextField(null, 20);
    textTitel.setToolTipText("ex. Flickan som lekte med elden");
    JTextField textSort = new JTextField(null, 10);
    textSort.setToolTipText("ex. Skräck, Action");
    JTextField textDesc = new JTextField(null, 15);
    textDesc.setToolTipText("ex. Stieg Larsson");

    // Knappar
    JButton addButton = new JButton("Lägg till");

    // Combobox
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Film");
    comboBox.addItem("CD");
    comboBox.addItem("Bok");
    comboBox.addItem("Annat");

I am trying to get the text and adding it to my array like this:

public String getTitelText() {
    return titelText;
}

public String getDescText() {
    return descText;
}

public String getSortText() {
    return sortText;
}

public void actionPerformed(ActionEvent e) {
    DatabaseTable dt = new DatabaseTable();
    dt.add(titelText, sortText, descText, descText);

But I think that this way is wrong, but dont know how to solve it. Another question is there any easy way to know what is selected on JComboBox?


回答1:


For JTextField use myTextField.getText() For tooltip in JTextField use myTextField.getToolTipText() For JComboBox use myComboBox.getSelectedIndex() or myComboBox.getSelectedItem() First gives you the index of the selected item and he second gives you the actual item.




回答2:


comboBox.getSelectedItem();

public String getSortText() {
    return sortText.getText();
}

All this can easily be found in the Java DOCs from SUN.

--edit-- updated my answer to really make sure you understand :)



来源:https://stackoverflow.com/questions/2309629/get-input-text-without-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!