Java数字没有显示在文本字段中,我希望以字符串形式读入

时间:2015-12-07 17:19:34

标签: java swing

我是Java新手。我编写了一个类似的应用程序,当我单击按钮时将文本放入JTextField,与该按钮关联的文本将显示在JTextField中。现在我正在做数字(尝试读取字符串),但是当我点击按钮时,什么都没有出现。我知道这可能是我想念的小事。如果你能帮助我真的很感激! :)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleButtons_Wallace extends JPanel implements ActionListener {
    private JButton button0;
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JTextField Textfield;
    public SimpleButtons_Wallace() {
        GridLayout experimentLayout = new GridLayout(0, 2);
        JPanel MiniME = new JPanel();
        button0 = new JButton("zero");
        button0.addActionListener(this);
        button1 = new JButton("1");
        button1.addActionListener(this);
        button2 = new JButton("2");
        button2.addActionListener(this);
        button3 = new JButton("3");
        button3.addActionListener(this);
        Textfield = new JTextField(10);
        Textfield.addActionListener(this);
        MiniME.setLayout(experimentLayout);
        add(MiniME);
        MiniME.add(button0);
        MiniME.add(button1);
        MiniME.add(button2);
        MiniME.add(button3);
        MiniME.add(Textfield);
    }
    public void actionPerformed(ActionEvent e) {
        JButton b = (JButton) e.getSource();
        Textfield.setText(b.getText());
    }
}
import javax.swing.JFrame;
import javax.swing.*;
public class GuiMain_Wallace extends JFrame {
    public GuiMain_Wallace() {
        getContentPane().add(new SimpleButtons_Wallace());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public static void main(String args[]) {
        GuiMain_Wallace aframe = new GuiMain_Wallace();
        aframe.setSize(225, 230);
        aframe.setVisible(true);
    }
}

//这是我尝试使用的两个类。有什么我可以做//使JTextField被填充。

2 个答案:

答案 0 :(得分:1)

  

但是当我点击按钮时,什么都没有出现。

问题在于您正在尝试管理帧的大小(您认为帧大小太小,因此文本字段的文本被截断)。不要这样做。使用pack()方法,以便组件可以按其首选大小显示:

//aframe.setSize(225, 230);
aframe.pack();

使用数字创建JTextField总是一个好主意。此编号用于文本字段以确定其首选大小。在您的情况下,您指定了10,这意味着在您需要滚动文本之前,它将显示至少10个字符。

答案 1 :(得分:0)

这是因为您使用JTextField(10)限制了Textfield。

删除限制:

Textfield = new JTextField();