设置JTextArea的位置不起作用

问题描述

我不知道如何设置文本区域的位置。这是我的代码。不知道什么不起作用,显然JTextArea并不像设置按钮一样简单。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class BackgroundImageJFrame extends JFrame {
    
    JButton b1;
    JLabel l1;
    
    public BackgroundImageJFrame() {
        setTitle("Background Color for JFrame");
        setSize(1000,1000);
        setLocationRelativeto(null);
        setDefaultCloSEOperation(EXIT_ON_CLOSE);
        setVisible(true);
        /*One way-----------------*/
        setLayout(new BorderLayout());
        JLabel background = new JLabel(new ImageIcon("background-landing.png"));
        add(background);
        background.setLayout(new FlowLayout());
        l1 = new JLabel("Here is a button");
        b1 = new JButton("I am a button");
        JTextArea t1 = new JTextArea("enter username",10,20);
        t1.setLocation(30,30);
        background.add(l1);
        background.add(b1);
        background.add(t1);
    }
    
    public static void main(String args[]) {
        new BackgroundImageJFrame();
    }
}

follow up to the last comment,this is what I am trying to achieve

解决方法

显然,JTextArea并不像设置按钮一样简单。

您尝试创建带有文本“这里是按钮”和带有文本“我是按钮”的标签

您的按钮也不显示,因此注释没有意义。

问题是您要向JLabel添加组件。默认情况下,JLabel不显示子组件,因为它没有布局管理器。

您将可以通过设置布局管理器将组件添加到标签:

JLabel background = new JLabel(...);
background.setLayout( new FlowLayout() );

阅读Layout Managers上Swing教程中的部分,以获取更多使用布局管理器的基础知识和实用示例。该教程代码还将向您展示如何更好地构建类,以便您遵循Swing指南。

您还可以签出:Background Panel,以获取可能的替代解决方案。