通过组件直接控制窗体的位置

    xiaoxiao2021-11-29  21

    /*这个的核心思想是首先将一个组件加到Panel上,通过控制Panel以及各种组件的位置大小等信息并将panel加到Frame上。这里主要是监听器的添加,只要将组建的ActionListener监听器加上以后便可以实现目的。这里简单的写一个通过button来控制窗体的位置。 package 设置窗口的位置; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Window; import java.awt.event.*; import javax.swing.*; public class example { public static void main(String[] args){ JFrame f = new JFrame("封娜宝宝");//默认BorderLayout所以可以直接让他将按钮添加在south或者将布局管理设置为null f.setLayout(null);//将布局设置为null视为了后来将label和文本框能用一个面板直接加进去 f.setBounds(300, 20, 400, 400); JPanel a = new JPanel(); JButton bt = new JButton(" 设置 "); a.setBounds(0, 320, 400, 60);//位置坐标,大小; a.add(bt); f.add(a); JPanel a1 = new JPanel(); JLabel l1 = new JLabel("左边距:"); JTextField in1= new JTextField(25); a1.setLayout(new FlowLayout(FlowLayout.LEFT, 15, 0)); a1.setBounds(0, 50, 400, 60); a1.add(l1); a1.add(in1); JPanel a2 = new JPanel(); //用面板的原因方便管理 虽然这里目前不用面板也可以但是为了以后考虑吧 JLabel l2 = new JLabel("右边距:"); JTextField in2= new JTextField(25); a2.setLayout(new FlowLayout(FlowLayout.LEFT, 15, 0)); a2.setBounds(0, 150, 400, 60);//设置窗体的位置和大小 a2.add(l2); a2.add(in2); f.add(a1); f.add(a2); bt.addActionListener(new ActionListener(){//这里需要注意监听器是ActionListener的 public void actionPerformed(ActionEvent e){//addActionListener的固定用法后面必须跟actionPerformed String value = in1.getText();//得到输入的值 String value2 = in2.getText(); if(value == null || value2 == null) return; int left = Integer.parseInt(value);//将由数字组成的字符串直接转换为相应的数字 int top = Integer.parseInt(value2); f.setLocation(left, top);//直接更新当前窗体的位置 } }); f.setVisible(true); f.addWindowListener(new windowclosing()); } } class windowclosing extends WindowAdapter{//关闭窗口的监听器 public void WindowClosing(WindowEvent e){ Window w = (Window) e.getComponent(); w.dispose(); } } */
    转载请注明原文地址: https://ju.6miu.com/read-678813.html

    最新回复(0)