Java的setLayout

在Java中,setLayout 方法是用于设置容器(如 JFrameJPanel 等)的布局管理器的。布局管理器负责容器内组件的摆放和大小调整。当你添加组件到容器中时,布局管理器会根据其规则决定这些组件的位置和大小。

Java提供了多种布局管理器,例如 FlowLayoutBorderLayoutGridLayoutCardLayoutGridBagLayout 等,每一种都有其特定的排列组件的方式。

使用 setLayout 的基本步骤:

  1. 创建容器
    首先,你需要一个容器(如 JFrame),它将包含其他组件。

    JFrame frame = new JFrame();
    ```
    
    
  2. 选择布局管理器
    决定使用哪种布局管理器。例如,FlowLayout 是默认的布局管理器,它会按照组件的添加顺序排列组件,并让它们保持它们的首选大小。

    LayoutManager layout = new FlowLayout();
    ```
    
    
  3. 设置布局管理器
    使用 setLayout 方法为容器设置布局管理器。

     
    frame.setLayout(layout);
    ```
    
    
  4. 添加组件
    向容器中添加组件(如按钮、标签等),布局管理器会根据其规则安排这些组件。

     
    frame.add(new JButton("Button 1"));
    frame.add(new JButton("Button 2"));
    ```
    
    
  5. 显示容器
    最后,设置容器的大小,使其可见,并确保当关闭窗口时程序会退出。

    frame.setSize(300, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ```
    

示例:设置不同的布局管理器

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

public class LayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Layout Example");

        // 设置为FlowLayout
        frame.setLayout(new FlowLayout());

        // 添加组件
        frame.add(new JButton("Button 1"));
        frame.add(new JButton("Button 2"));
        frame.add(new JButton("Button 3"));

        // 配置框架
        frame.setSize(200, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

在上面的例子中,我们创建了一个 JFrame 对象,并且通过 setLayout 方法设置了 FlowLayout 作为布局管理器。之后,我们添加了三个按钮到框架中。当运行程序时,你会看到一个窗口,其中包含按照流式布局排列的三个按钮。

根据需要,你可以将 FlowLayout 更换为其他布局管理器,并根据该布局管理器的特定规则添加相应的组件。每个布局管理器都有其独特的构造函数和设置方式,所以在使用之前你可能需要查阅相关的文档或教程来了解如何最有效地利用它。


 

以下是几个使用不同布局管理器的 setLayout 方法的Java示例。

BorderLayout

BorderLayout 把容器分割为五个区域:北(North), 南(South), 东(East), 西(West) 和 中(Center)。每个区域只能包含一个组件。

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

public class BorderLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("BorderLayout Example");
        frame.setLayout(new BorderLayout(5, 5)); // 5 pixels horizontal and vertical gaps

        frame.add(new JButton("North"), BorderLayout.NORTH);
        frame.add(new JButton("South"), BorderLayout.SOUTH);
        frame.add(new JButton("East"), BorderLayout.EAST);
        frame.add(new JButton("West"), BorderLayout.WEST);
        frame.add(new JTextArea("Center"), BorderLayout.CENTER);

        frame.pack(); // Adjusts the frame size to fit the components
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

GridLayout

GridLayout 将容器划分为大小相等的矩形网格,行数和列数在创建 GridLayout 对象时确定。

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

public class GridLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("GridLayout Example");
        frame.setLayout(new GridLayout(3, 2, 5, 5)); // 3 rows, 2 cols, 5px vert and horiz gaps

        frame.add(new JButton("Button 1"));
        frame.add(new JButton("Button 2"));
        frame.add(new JButton("Button 3"));
        frame.add(new JButton("Button 4"));
        frame.add(new JButton("Button 5"));
        frame.add(new JButton("Button 6"));

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

CardLayout

CardLayout 允许多个组件共享同一个显示空间,一次只显示一个组件。

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

public class CardLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("CardLayout Example");
        CardLayout cardLayout = new CardLayout();
        frame.setLayout(cardLayout);

        // 创建几个面板作为卡片
        JPanel card1 = new JPanel();
        card1.add(new JLabel("Card 1"));
        card1.setBackground(Color.GREEN);
        
        JPanel card2 = new JPanel();
        card2.add(new JLabel("Card 2"));
        card2.setBackground(Color.BLUE);
        
        // 添加到帧中
        frame.add(card1, "Card 1");
        frame.add(card2, "Card 2");

        // 切换卡片的按钮
        JButton btn = new JButton("Next");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                cardLayout.next(frame.getContentPane());
            }
        });

        frame.add(btn, BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

BoxLayout

BoxLayout 可以按照一列或一行的方式排列组件。

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

public class BoxLayoutExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("BoxLayout Example");
        // 设置为BoxLayout, 沿着Y轴排列组件
        frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));

        frame.add(new JButton("Button 1"));
        frame.add(new JButton("Button 2"));
        frame.add(new JButton("Button 3"));

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package cn.tedu.chart2; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.JTextField; /** * 客户端窗体 */ public class ClientFrame extends JFrame implements ActionListener, KeyListener { JButton but; JTextArea message; JTextField text; Socket s; ClientThread client; public static void main(String[] args) { new ClientFrame(); } // 在构造函数中对窗体进行初始化 public ClientFrame() { // 取消JFrame的布局 this.setLayout(null); this.setTitle("客户端"); this.setBounds(100, 20, 400, 400); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 聊天记录 --- JTextArea message = new JTextArea(); message.setBounds(10, 10, 360, 200); // 设置聊天记录不能修改 message.setEditable(false); this.add(message); // 信息发送 JTextField JButton text = new JTextField(); text.setBounds(10, 260, 250, 40); text.addKeyListener(this); this.add(text); but = new JButton("发送"); but.setBounds(280, 260, 100, 40); // 给but按钮添加动作监听 but.addActionListener(this); this.add(but); this.setVisible(true); // 和服务器取得联系 try { s = new Socket("127.0.0.1", 65000); client = new ClientThread(s, message); client.start(); } catch (Exception e) { e.printStackTrace(); } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == but) { if (!s.isClosed()) { String data = text.getText(); if (!"".equals(data)) { // 向服务器发送信息 client.send(data); // 清空文本框 text.setText(null); } }else { //在关闭状态下点击发送按钮 JOptionPane.showMessageDialog(null, "Socket连接已关闭,不能发送信息!", "提示", JOptionPane.ERROR_MESSAGE); } } } public void keyTyped(KeyEvent e) {} @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { if (!s.isClosed()) { String data = text.getText(); if (!"".equals(data)) { // 向服务器发送信息 client.send(data); // 清空文本框 text.setText(null); } }else { //在关闭状态下点击发送按钮 JOptionPane.showMessageDialog(null, "Socket连接已关闭,不能发送信息!", "提示", JOptionPane.ERROR_MESSAGE); } } } public void keyReleased(KeyEvent e) {} }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值