按钮控件JButton的使用

来源:互联网 发布:python pyswip 编辑:程序博客网 时间:2024/04/29 15:59

---------------siwuxie095

  

  

  

  

  

  

  

工程名:TestUI

包名:com.siwuxie095.ui

类名:TestButton.java

  

  

工程结构目录如下:

  

  

  

  

  

在 Design 的根面板 contentPane 的上中下分别添加

一个 JTextField、JTextArea、JButton

  

  

对于 JButton,可以设置颜色,字体,文本内容,文本对齐方式

  

「foreground 是 文本颜色,background 是 文本以外部分的颜色」

  

  

  

将这个按钮的文本(text)设定为确定

  

  

添加鼠标点击的监听:

选中这个按钮,右键->Addevent handler->mouse->mouseClicked

  

将会自动创建一个函数mouseClicked(),只要鼠标点击按钮,就会触发

自动创建的这个函数

  

可以在这个函数中添加代码,来完成相应的动作

  

如:实现鼠标点击按钮时,将上方的文本框的内容显示到中间的文本框

  

  

  

代码:

  

package com.siwuxie095.ui;

  

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.EventQueue;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

  

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextArea;

import javax.swing.JTextField;

import javax.swing.border.EmptyBorder;

  

public class TestButtonextends JFrame {

  

private JPanel contentPane;

private JTextField textField;

  

/**

* Launch the application.

*/

public staticvoid main(String[] args) {

EventQueue.invokeLater(new Runnable() {

publicvoid run() {

try {

TestButton frame =new TestButton();

frame.setVisible(true);

}catch (Exception e) {

e.printStackTrace();

}

}

});

}

  

/**

* Create the frame.

*/

public TestButton() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(100,100, 450,300);

contentPane =new JPanel();

contentPane.setBorder(new EmptyBorder(5,5, 5,5));

contentPane.setLayout(new BorderLayout(0,0));

setContentPane(contentPane);

 

textField =new JTextField();

contentPane.add(textField, BorderLayout.NORTH);

textField.setColumns(10);

 

JTextArea textArea =new JTextArea();

contentPane.add(textArea, BorderLayout.CENTER);

 

JButton btnNewButton =new JButton("确定");

btnNewButton.setForeground(Color.BLACK);

btnNewButton.setBackground(Color.LIGHT_GRAY);

 

 

//添加鼠标监听事件,当鼠标点击时将上方的 TextField

//的内容显示到中间的 TextArea

btnNewButton.addMouseListener(new MouseAdapter() {

@Override

publicvoid mouseClicked(MouseEvent arg0) {

 

//先从上方的文本框获取用户输入的文本,然后显示到中间的文本框

textArea.setText(textField.getText());

 

}

});

contentPane.add(btnNewButton, BorderLayout.SOUTH);

}

  

}

  

  

运行后,在上方输入123,点击 确定,中间将显示 123

  

  

  

  

  

  

  

  

【made by siwuxie095】

0 0
原创粉丝点击