从文本框接收Java图形中的字符串

时间:2018-04-28 17:04:47

标签: java graphics

我开始为我制作的程序制作图形,其中插入了一首歌的名称和长度,我该如何在图形中进行?我发现了如何拿起一个按钮,但我不明白如何吸收插入文本框的内容

import java.awt.*;
import java.awt.event.*;
public class Active extends Frame {
public void init() {
    ActionListener al = new MyActionListener();
    TextField tf = new TextField(20);
    Button b;
    setLayout(new FlowLayout());
    setSize(1000, 1000);
    b = new Button ("first");
    b.setActionCommand("First");
    b.addActionListener(al);
    add(b);
    b = new Button ("Second");
    b.setActionCommand("Second");
    b.addActionListener(al);
    add(b);
    setVisible(true);   
    add(tf);
}
public Active(String caption) {
    super(caption);
    init();
}
public static void main(String[] args) {
    Active m = new Active("Active buttons");
}
}

主要:

import java.awt.*;
import java.awt.event.*;
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
    String s = e.getActionCommand();
    if(s.equals("First")) {
        System.out.println("The first button was switched");
    }
    if(s.equals("Second")) {
        System.out.println("The second button was switched");
    }
}
}

1 个答案:

答案 0 :(得分:0)

我会用 Swing GUI Toolkit 编写它。这是一个简短的例子:

public class MyPanel extends JPanel
{
    private JTextField songNameField;
    private JTextField songLengthField;
    private JButton assignBtn;

    public MyPanel()
    {
        this.songNameField = new JTextField();
        this.songLengthField = new JTextField();
        this.assignBtn = new JButton("Assign");

        this.assignBtn.addActionListener(new ActionListener() {
            @Override public void actionPerformed(ActionEvent event)
            {
                String name = songNameField.getText();
                int length = Integer.parseInt(parsesongLengthField.getText());

                ...
            }
        });

        this.add(songNameField);
        this.add(songLengthField);
        this.add(assignBtn);
    }
}