JTextArea未添加到框架中

时间:2016-01-31 05:51:34

标签: java swing

我无法理解为什么JTextArea没有显示我的代码。 这是我第一次在swing程序中使用FocusAdapter类。

这是代码。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Focus extends FocusAdapter
{
    JFrame f;
    JTextArea jt;
    Focus()
    {
        f=new JFrame("focus");
        jt=new JTextArea(50,50);
        jt.addFocusListener(this);
        jt.setFont(new Font("varinda",Font.PLAIN,15));

        f.setSize(550,550);
        f.setLayout(null);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
    public void focusGained(FocusEvent fe)
    {
        jt.setText("focusgained");
    }
    public static void main(String s[])
    {
        new Focus();
    }

}

3 个答案:

答案 0 :(得分:2)

  

我无法理解为什么JTextArea没有显示我的代码。这是我第一次在swing程序中使用FocusAdapter类。

这是因为您将JFrame的布局设置为null,并且我没有看到您将JTextField添加到JFrame。

你可以这样做:

f.add(jt);
jt.setBounds(x, y, width, height); //Give int values for x, y, width, height

最后但并非最不重要的是,尝试使用JFrame的布局,您可以考虑向JFrame添加JPanel,而不是直接将组件添加到JFrame中。

答案 1 :(得分:2)

避免使用null布局,像素完美布局是现代ui设计中的一种幻觉。影响组件个体大小的因素太多,您无法控制。 Swing旨在与布局管理器一起工作,放弃这些将导致问题和问题的终结,您将花费越来越多的时间来纠正

问题的基本答案是,您需要将JTextArea实际添加到展位容器中,例如,您的JFrame,...

public class Focus extends FocusAdapter
{
    JFrame f;
    JTextArea jt;
    Focus()
    {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }


                jt=new JTextArea(50,50);
                jt.addFocusListener(this);
                jt.setFont(new Font("varinda",Font.PLAIN,15));

                f = new JFrame("Testing");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(new JScrollPane(jt));
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });
    }
    public void focusGained(FocusEvent fe)
    {
        jt.setText("focusgained");
    }
    public static void main(String s[])
    {
        new Focus();
    }
}

看看

了解更多详情

答案 2 :(得分:0)

您尚未将JTextArea添加到JFrame。这就是为什么它'没有添加。 ;)

您可以通过以下方式实现:

f.add(jt);
f.setSize(500,500);

或:

f.add(new JScrollPane(jt) );
相关问题