/*文章中用到的代码只是一部分,需要源码的可通过邮箱联系我 1978702969@qq.com*/

在上篇博客中提到了JAVA图形界面开发时的两种布局,流式布局和边框布局。

在实际使用中可能会发现,往容器中添加组件往往并不能得到想要的结果。比如想上下对齐两个组件,而流式布局是从左到右的,此时就很难实现上下对齐,此篇文章将介绍两个方法。

1.直接使用坐标贴图

  如下面这个计算器的制作

  JAVA 图形开发中组件对齐方法及界面开发

 1 package Graphic;
 2 
 3 import java.awt.BorderLayout;
 4 import java.awt.Dimension;
 5 import java.awt.FlowLayout;
 6 
 7 import javax.swing.JButton;
 8 import javax.swing.JFrame;
 9 import javax.swing.JLabel;
10 import javax.swing.JPanel;
11 import javax.swing.JTextField;
12 
13 public class Calculator {
14 
15     public static void main(String[] args) {
16         Calculator login = new Calculator();
17         login.Init();
18     }
19 
20     public void Init()
21     {
22         String arr[] = {"1","2","3","4","5","6","7","8","9","0","+","-","*","/","="};
23         
24         JFrame frame = new JFrame();
25         frame.setTitle("计算器");
26         frame.setSize(600,400);
27         frame.setLocationRelativeTo(null);
28         frame.setDefaultCloseOperation(3);
29         frame.setResizable(false);
30 
31         frame.setLayout(null);
32         
33         JTextField text1 = new     JTextField();
34         text1.setBounds(40, 20, 400, 40);
35         frame.add(text1);
36         
37         
38         for(int i=0;i<9;i++)
39         {
40             JButton button = new JButton();
41             button.setText(arr[i]);
42             button.setBounds((i%3)*100+40, (i/3)*60+80, 80, 40);
43             frame.add(button);
44         }
45         
46         JButton button = new JButton();
47         button.setText("0");
48         button.setBounds(40, 260, 180, 40);
49         frame.add(button);
50         
51         JButton button1 = new JButton();
52         button1.setText(".");
53         button1.setBounds(240, 260, 80, 40);
54         frame.add(button1);
55         
56         for(int i=10;i<arr.length - 1;i++)
57         {
58             JButton button2 = new JButton();
59             button2.setText(arr[i]);
60             button2.setBounds(360, (i-10)*60+80, 80, 40);
61             frame.add(button2);
62         }
63         
64 
65         JButton button2 = new JButton();
66         button2.setText("x^2");
67         button2.setBounds(460, 80, 80, 40);
68         frame.add(button2);
69         
70         JButton button3 = new JButton();
71         button3.setText("√x");
72         button3.setBounds(460, 140, 80, 40);
73         frame.add(button3);
74         
75         JButton button4 = new JButton();
76         button4.setText("=");
77         button4.setBounds(460, 200, 80, 100);
78         frame.add(button4);
79         
80         frame.setVisible(true);
81     }
82 }
计算器

相关文章:

  • 2021-05-01
  • 2021-11-19
  • 2021-12-24
  • 2022-01-16
  • 2021-11-11
  • 2021-07-05
  • 2022-12-23
猜你喜欢
  • 2021-05-31
  • 2021-07-08
  • 2022-01-03
  • 2021-04-19
  • 2021-10-21
  • 2022-12-23
相关资源
相似解决方案