有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我开始为我自己制作的程序制作一个图形,在其中插入歌曲的名称和长度,我如何在图形中这样做?我发现了如何拿起一个按钮,但我不知道如何吸收插入文本框中的内容

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) 个答案

  1. # 1 楼答案

    我将使用SwingGUI工具包编写它。下面是一个简短的例子:

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