我想用JFrame创建一个文本生成器,就像里面的图片一样:

时间:2014-12-08 14:24:19

标签: java swing jframe

我开始熟悉Java和JFrame软件包,但我并不完全相同。这就是我想要的:

enter image description here

正如你所看到的,我希望能够填充盒子,然后拿出盒子里的东西并用它做一个预先写好的句子!

2 个答案:

答案 0 :(得分:1)

在Swing中,有两个不同的组件。 JTextArea和JTextPane。 JTextArea易于使用,但不允许格式化。如果您不打算更改不同单词的格式,那就是要使用的单词格式。 JTextArea更强大但更难使用。

查看Java教程以获取更多信息。

http://docs.oracle.com/javase/tutorial/uiswing/components/text.html

答案 1 :(得分:-1)

我希望这会有所帮助......

  

<强> TextGenerator.java

package textgenerator;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;

public class TextGenerator {

    JFrame frame;
    JPanel panel;
    JTextPane textPane;
    JLabel namel;
    JLabel agel;
    JTextField namef;
    JTextField agef;
    JButton button;

    public TextGenerator() {
        frame = new JFrame("My Frame");//Construct the frame
        frame.setBounds(200, 100, 1000, 500);//set the size and position
        frame.setLayout(new GridLayout(1, 2));//set layout with 1 row and 2 columns
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);//restrict the resixing of the frame

        panel = new JPanel();//create a panel
        panel.setLayout(null);
        textPane = new JTextPane();//create a textpane
        textPane.setEditable(false);
        frame.add(panel);//add panel to the frame
        frame.add(textPane);//add textpane to the frame

        //create labels and textfields and add them to the panel
        namel = new JLabel("Name : ");
        namel.setBounds(20, 200, 150, 20);
        agel = new JLabel("Age : ");
        agel.setBounds(20, 250, 150, 20);
        namef = new JTextField();
        namef.setBounds(220, 200, 150, 20);
        agef = new JTextField();
        agef.setBounds(220, 250, 150, 20);
        panel.add(namel);
        panel.add(agel);
        panel.add(namef);
        panel.add(agef);

        //create button and add it to the panel
        button = new JButton("Done !");
        button.setBounds(350, 400, 100, 20);
        panel.add(button);

        //set the required text to the textfield on button click
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                textPane.setText("Hello !\n"
                        + "My name is " + namef.getText() + ", and I'm " + agef.getText() + ".\n"
                        + "How are you ?");
            }
        });

        frame.setVisible(true);//make the frame visible
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TextGenerator();
            }
        });
    }

}

Output looks like this