今天学习Java开发实战1200例(第1卷)窗口在屏幕中的任意位置,改写如下:
一、窗口框架类:
import java.awt.BorderLayout;
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.SwingConstants;
public class WFrame extends JFrame {
private JTextField left;
private JTextField right;
private int l;
private int r;
public WFrame(){
//setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
left=new JTextField();
right=new JTextField();
JPanel centerPanel=new JPanel();
centerPanel.setLayout(new GridLayout(2,2));
centerPanel.add(new JLabel("左边距: ",SwingConstants.RIGHT));
centerPanel.add(left);
centerPanel.add(new JLabel("右边距:",SwingConstants.RIGHT));
centerPanel.add(right);
add(centerPanel,BorderLayout.CENTER);
JPanel southPanel=new JPanel();
JButton btn=new JButton("设置");
southPanel.add(btn);
//btnActionListener b=new btnActionListener();
btn.addActionListener(event->{
l=Integer.parseInt(left.getText());//获取TextField中的数字
r=Integer.parseInt(right.getText());
setLocation(l,r);//设置窗口位置
});
add(southPanel,BorderLayout.SOUTH);
pack();
}
}
二、测试代码:
import java.awt.EventQueue;
import javax.swing.JFrame;
public class WindowFrameTest {
public static void main(String[] agrs){
EventQueue.invokeLater(()->{
WFrame frame=new WFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}