几个简单的JAVA GUI练习
最近在听 NEU 的 JAVA 慕课,然后有两个简单的 GUI 课后练习:
菜单栏相关练习
编写如图所示应用程序,单击选择菜单项退出后,显示下面的请选择对话框,选择是结束程序,选择否显示下面的消息对话框。
题目要求使用菜单栏 JMenuBar 和 菜单项 JMenuItem, 很遗憾 IEDA 所提供的 SwingGUIdesigner 并没有默认提高 菜单栏 和 菜单项的选则。因此这里被迫使用了 JFormDesigner 来创建可视化界面:
这里,题目要求的两个 optionPane 也是可以先在 jFromDesinger 中先画好的。这样就可以不用手动初始化了。
至此,系统自动生成的代码如下:
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
menuBar1 = new JMenuBar();
menuFile = new JMenu();
menuItemOpen = new JMenuItem();
menuItemExit = new JMenuItem();
menuEidt = new JMenu();
menuForm = new JMenu();
optionPaneChoose = new JOptionPane();
optionPaneNo = new JOptionPane();
//======== this ========
setTitle("EmptinessBoy\u4f5c\u4e1a");
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(3, 4));
//======== menuBar1 ========
{
//======== menuFile ========
{
menuFile.setText("\u6587\u4ef6");
//---- menuItemOpen ----
menuItemOpen.setText("\u6253\u5f00");
menuFile.add(menuItemOpen);
//---- menuItemExit ----
menuItemExit.setText("\u9000\u51fa");
menuItemExit.addActionListener(e -> menuItemExitActionPerformed(e));
menuFile.add(menuItemExit);
}
menuBar1.add(menuFile);
//======== menuEidt ========
{
menuEidt.setText("\u7f16\u8f91");
}
menuBar1.add(menuEidt);
//======== menuForm ========
{
menuForm.setText("\u7a97\u53e3");
}
menuBar1.add(menuForm);
}
setJMenuBar(menuBar1);
setSize(445, 315);
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JMenuBar menuBar1;
private JMenu menuFile;
private JMenuItem menuItemOpen;
private JMenuItem menuItemExit;
private JMenu menuEidt;
private JMenu menuForm;
private JOptionPane optionPaneChoose;
private JOptionPane optionPaneNo;
// JFormDesigner - End of variables declaration //GEN-END:variables
为了使程序完成题目要求的功能,我们需要给菜单项 JMenuItem【menuItemExit】设置监听器。
事件监听代码:
optionPane 对话框写法
private void menuItemExitActionPerformed(ActionEvent e) {
// TODO add your code here
int i = optionPaneChoose.showConfirmDialog(null,"是否退出系统?","请选择", JOptionPane.YES_NO_OPTION);
if(i==0)
System.exit(0);
else{
//ConfirmDialog(null,"您选择了否!","消息",JOptionPane.YES_OPTION);
optionPaneNo.showMessageDialog(null,"您选择了否","消息", JOptionPane.YES_OPTION);
}
}
对于多选对话框,int i 的返回值就是指代了用户选中的 “是” 或 “否” 的值。一般情况下,选中是为 0.
optionPaneNo.showMessageDialog 显示一个消息提示
optionPaneChoose.showConfirmDialog 显示可确认对话框
设置点击关闭窗体的默认事件
只要在实现 JFrame 类的构造函数中加入一条
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
即可轻松搞定。
最后,整体运行效果:
窗体相关练习
窗体中显示一个图片,用鼠标可以拖动图片到任意位置。
没错,作业只有这么简简单单一句话。然后我也天真的以为这是一道秒杀题。但是,往往是我太天真了(悲哀
头里的步骤并不难,这里使用 JFormDesigner 创建窗体。然后随便拖拽一个 JLable 用来存放图片。
下面是系统自动生成的代码(含后面加的监听器):
……
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
label1 = new JLabel();
textField1 = new JTextField();
//======== this ========
setMinimumSize(new Dimension(500, 500));
setTitle("EmptinessBoyMooc\u4f5c\u4e1a");
var contentPane = getContentPane();
//---- label1 ----
label1.setIcon(null);
label1.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
label1MouseDragged(e);
}
});
label1.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
label1MousePressed(e);
}
});
//---- textField1 ----
textField1.setText("\u6b64\u5904\u663e\u793a\u5750\u6807");
GroupLayout contentPaneLayout = new GroupLayout(contentPane);
contentPane.setLayout(contentPaneLayout);
contentPaneLayout.setHorizontalGroup(
contentPaneLayout.createParallelGroup()
.addGroup(contentPaneLayout.createSequentialGroup()
.addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(label1, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
.addGroup(contentPaneLayout.createSequentialGroup()
.addContainerGap()
.addComponent(textField1)))
.addContainerGap())
);
contentPaneLayout.setVerticalGroup(
contentPaneLayout.createParallelGroup()
.addGroup(contentPaneLayout.createSequentialGroup()
.addComponent(label1, GroupLayout.PREFERRED_SIZE, 100, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 302, Short.MAX_VALUE)
.addComponent(textField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JLabel label1;
private JTextField textField1;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
到这里,我们需要给 jlable 设置 icon,这里将设置 icon 的代码放到构造函数中:
Jlabel 设置 icon 方法
public MovePic() {
initComponents();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
ImageIcon i = new ImageIcon("src/logo.png");
Image pic = i.getImage().getScaledInstance(100,100,Image.SCALE_DEFAULT);
ImageIcon ico = new ImageIcon(pic);
label1.setIcon(ico);
}
现在是不是只要给 存放了图片的 jlable 设置 MouseDragged 鼠标拖拽监听函数呢?
最开始一脸小白的我确实是这么想的,然后写下了简单的
错误代码:
x = e.getX();
y = e.getY();
textField1.setText(x+","+y);
label1.setLocation(x,y);
网上都说了 e.getX(); e.getY(); 不就是获取当前是鼠标位置嘛。(呵呵
然而在实际测试中发现,实际上,这两个获取到的都是以 jlable 为容器,鼠标在 jlable 中的相对位置。因此单纯这样的代码无法实现所需要的功能。
那么,一心想偷懒的我想,那么只要针对 Jlable 的父容器设置鼠标监听器来改变坐标不就完了?(理想很美好,现实确是:
因为子容器遮挡了父容器,当鼠标移动到 Jlable 上时,设置在父容器 JFrame 的监听器就失效了!!
只有鼠标移出图片的时候,才能正确获取针对窗体的坐标。
终极坐标解决方案
那么只能使出大杀器了,(用我小学的算数水平,通过绝对坐标加减来获取位置了
经过查找文档,可知:
e.getXOnScreen() e.getYOnScreen() 可以用来获取鼠标在整个屏幕的绝对位置,而 this.getX() this.getY()可以获得当前窗体在屏幕中的左上角位置。
那么?!
只要使用 x = e.getXOnScreen()-this.getX()
就可以通过计算获得鼠标在窗体内部的相对位置啦!!!
但是这时候还是有些小小的瑕疵 ——鼠标拖拽后,显示的位置是以鼠标结束位置作为左上角定点的,拖拽感觉不够自然。
修复的方法很简单。既然 e.getX() 可以获取当前鼠标相对于图片(jlable)的相对位置,那么只要在我们刚才获取的 x 减去 这个内部的相对位置就完美啦!!注意这个坐标需要在刚开始按下鼠标时获取才有用,因此需要放在 MousePressed 监听器中。
最后附上代码:
public class MovePic extends JFrame {
int x,y,a,b;
public static void main(String[] args) {
new MovePic().setVisible(true);
}
public MovePic() {
initComponents();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
ImageIcon i = new ImageIcon("src/logo.png");
Image pic = i.getImage().getScaledInstance(100,100,Image.SCALE_DEFAULT);
ImageIcon ico = new ImageIcon(pic);
label1.setIcon(ico);
}
private void label1MouseDragged(MouseEvent e) {
// TODO add your code here
x = e.getXOnScreen()-this.getX()-a;
y = e.getYOnScreen()-this.getY()-b-20;
textField1.setText(x+","+y);
label1.setLocation(x,y);
}
private void label1MousePressed(MouseEvent e) {
// TODO add your code here
a = e.getX();
b = e.getY();
}
……
运行效果:
nice!又是洗洗睡的一天(PS,最近腰疼犯了,睡觉保命要紧【滑稽】
控件和监听器练习
题目要求:使用 Java 实现一个RGB调色板程序,点击加减按钮可以调整RGB数值并显示颜色
由于已经比较习惯了 JFormDesigner 那么完成这个任务也靠Ta啦!
设计界面
这里外层的 Jframe 使用了 IntelijGridLayOut ,比起标准的 GridLayout 可以自由调整 margin,以及内部的浮动(有点像安卓里的 Gravaty
内部划分了两个 panel 用于摆放控件,下方的 panel 则用来显示实时的颜色输出
划分完成 UI ,并设置完成事件监听器后,系统就自动生成了 UI 相关的代码
……
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
panelSetColor = new JPanel();
labelRed = new JLabel();
buttonSubRed = new JButton();
textFieldRed = new JTextField();
buttonAddRed = new JButton();
labelGreen = new JLabel();
buttonSubGreen = new JButton();
textFieldGreen = new JTextField();
buttonAddGreen = new JButton();
labelBlue = new JLabel();
buttonSubBlue = new JButton();
textFieldBlue = new JTextField();
buttonAddBlue = new JButton();
panelColor = new JPanel();
labelShowColor = new JLabel();
//======== this ========
setTitle("2018010587-\u80e1\u6653\u5e06\uff08\u8c03\u8272\u677f\uff09");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(550, 350));
setFont(new Font(Font.DIALOG, Font.PLAIN, 16));
setBackground(Color.white);
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayoutManager(4, 1, new Insets(0, 20, 20, 20), 0, 5));
//======== panelSetColor ========
{
panelSetColor.setFont(panelSetColor.getFont().deriveFont(panelSetColor.getFont().getSize() + 4f));
panelSetColor.setLayout(new GridLayoutManager(3, 4, new Insets(20, 0, 10, 0), 3, 3));
//---- labelRed ----
labelRed.setText("\u7ea2\u8272 R");
labelRed.setForeground(Color.red);
labelRed.setFont(labelRed.getFont().deriveFont(labelRed.getFont().getStyle() | Font.BOLD, labelRed.getFont().getSize() + 4f));
panelSetColor.add(labelRed, new GridConstraints(0, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonSubRed ----
buttonSubRed.setText("\u51cf\u5c11");
buttonSubRed.setFont(buttonSubRed.getFont().deriveFont(buttonSubRed.getFont().getSize() + 4f));
buttonSubRed.addActionListener(e -> buttonSubRedActionPerformed(e));
panelSetColor.add(buttonSubRed, new GridConstraints(0, 1, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- textFieldRed ----
textFieldRed.setText("155");
textFieldRed.setFont(textFieldRed.getFont().deriveFont(textFieldRed.getFont().getSize() + 4f));
panelSetColor.add(textFieldRed, new GridConstraints(0, 2, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonAddRed ----
buttonAddRed.setText("\u589e\u52a0");
buttonAddRed.setFont(buttonAddRed.getFont().deriveFont(buttonAddRed.getFont().getSize() + 4f));
buttonAddRed.addActionListener(e -> buttonAddRedActionPerformed(e));
panelSetColor.add(buttonAddRed, new GridConstraints(0, 3, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- labelGreen ----
labelGreen.setText("\u7eff\u8272 G");
labelGreen.setForeground(new Color(0, 204, 51));
labelGreen.setFont(labelGreen.getFont().deriveFont(labelGreen.getFont().getStyle() | Font.BOLD, labelGreen.getFont().getSize() + 4f));
panelSetColor.add(labelGreen, new GridConstraints(1, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonSubGreen ----
buttonSubGreen.setText("\u51cf\u5c11");
buttonSubGreen.setFont(buttonSubGreen.getFont().deriveFont(buttonSubGreen.getFont().getSize() + 4f));
buttonSubGreen.addActionListener(e -> buttonSubGreenActionPerformed(e));
panelSetColor.add(buttonSubGreen, new GridConstraints(1, 1, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- textFieldGreen ----
textFieldGreen.setText("155");
textFieldGreen.setFont(textFieldGreen.getFont().deriveFont(textFieldGreen.getFont().getSize() + 4f));
panelSetColor.add(textFieldGreen, new GridConstraints(1, 2, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonAddGreen ----
buttonAddGreen.setText("\u589e\u52a0");
buttonAddGreen.setFont(buttonAddGreen.getFont().deriveFont(buttonAddGreen.getFont().getSize() + 4f));
buttonAddGreen.addActionListener(e -> buttonAddGreenActionPerformed(e));
panelSetColor.add(buttonAddGreen, new GridConstraints(1, 3, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- labelBlue ----
labelBlue.setText("\u84dd\u8272 B");
labelBlue.setForeground(new Color(0, 102, 255));
labelBlue.setFont(labelBlue.getFont().deriveFont(labelBlue.getFont().getStyle() | Font.BOLD, labelBlue.getFont().getSize() + 4f));
panelSetColor.add(labelBlue, new GridConstraints(2, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonSubBlue ----
buttonSubBlue.setText("\u51cf\u5c11");
buttonSubBlue.setFont(buttonSubBlue.getFont().deriveFont(buttonSubBlue.getFont().getSize() + 4f));
buttonSubBlue.addActionListener(e -> buttonSubBlueActionPerformed(e));
panelSetColor.add(buttonSubBlue, new GridConstraints(2, 1, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- textFieldBlue ----
textFieldBlue.setText("155");
textFieldBlue.setFont(textFieldBlue.getFont().deriveFont(textFieldBlue.getFont().getSize() + 4f));
panelSetColor.add(textFieldBlue, new GridConstraints(2, 2, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonAddBlue ----
buttonAddBlue.setText("\u589e\u52a0");
buttonAddBlue.setFont(buttonAddBlue.getFont().deriveFont(buttonAddBlue.getFont().getSize() + 4f));
buttonAddBlue.addActionListener(e -> buttonAddBlueActionPerformed(e));
panelSetColor.add(buttonAddBlue, new GridConstraints(2, 3, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
}
contentPane.add(panelSetColor, new GridConstraints(0, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//======== panelColor ========
{
panelColor.setLayout(new GridLayoutManager(1, 1, new Insets(0, 10, 0, 10), 0, 0));
//---- labelShowColor ----
labelShowColor.setText("\u6b64\u5904\u663e\u793a\u6700\u7ec8\u989c\u8272");
panelColor.add(labelShowColor, new GridConstraints(0, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
}
contentPane.add(panelColor, new GridConstraints(2, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JPanel panelSetColor;
private JLabel labelRed;
private JButton buttonSubRed;
private JTextField textFieldRed;
private JButton buttonAddRed;
private JLabel labelGreen;
private JButton buttonSubGreen;
private JTextField textFieldGreen;
private JButton buttonAddGreen;
private JLabel labelBlue;
private JButton buttonSubBlue;
private JTextField textFieldBlue;
private JButton buttonAddBlue;
private JPanel panelColor;
private JLabel labelShowColor;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
核心代码
第一步要解决的就是程序刚运行时显示的颜色。这里我给类创建了r,g,b三个整型的变量。
然后只要在构造函数中把 panel 的颜色设置成预设的 rgb 即可。这里使用了 .setBackground
方法来设置背景色值。
public class ColorPanel extends JFrame {
int r=155,g=155,b=155;
Color bgColor = new Color(r, g, b);//设置初始颜色
……
public ColorPanel() {
initComponents();
textFieldRed.setText(String.valueOf(r));
textFieldGreen.setText(String.valueOf(g));
textFieldBlue.setText(String.valueOf(b));
panelColor.setBackground(bgColor);
}
接下来就是要通过按钮的按动来改变颜色了,这里以红色减少按钮为例:
private void buttonSubRedActionPerformed(ActionEvent e) {
// TODO add your code here
GetNum();
if(r>0&&r<=255)
r--;
else
System.out.println("红色已到临界值");
ShowColor();
}
这段代码中,使用了我写的两个函数 GetNum() 和 ShowColor()。GetNum 的目的是获取两个按钮中的文本框的值,来允许程序运行的时候可以手动输入数值。而 showColor 则是因为每个按钮最后都有显示颜色的功能,这段代码可以用函数来做。
GetNum():
void GetNum(){
//允许用户输入数值修改rgb
r = Integer.parseInt(textFieldRed.getText());
g = Integer.parseInt(textFieldGreen.getText());
b = Integer.parseInt(textFieldBlue.getText());
}
ShowColor():
void ShowColor(){
textFieldRed.setText(String.valueOf(r));
textFieldGreen.setText(String.valueOf(g));
textFieldBlue.setText(String.valueOf(b));
bgColor = new Color(r,g,b);
panelColor.setBackground(bgColor);
panelColor.setBackground(bgColor);
labelShowColor.setText("当前颜色16进制为:#"+Integer.toHexString(r)+Integer.toHexString(g)+Integer.toHexString(b));
}
最后附上运行效果:
完整代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.intellij.uiDesigner.core.*;
/**
* @author huxiaofan
*/
public class ColorPanel extends JFrame {
int r=155,g=155,b=155;
Color bgColor = new Color(r, g, b);//设置初始颜色
public static void main(String[] args) {
new ColorPanel().setVisible(true);
}
public ColorPanel() {
initComponents();
textFieldRed.setText(String.valueOf(r));
textFieldGreen.setText(String.valueOf(g));
textFieldBlue.setText(String.valueOf(b));
panelColor.setBackground(bgColor);
}
void ShowColor(){
textFieldRed.setText(String.valueOf(r));
textFieldGreen.setText(String.valueOf(g));
textFieldBlue.setText(String.valueOf(b));
bgColor = new Color(r,g,b);
panelColor.setBackground(bgColor);
panelColor.setBackground(bgColor);
labelShowColor.setText("当前颜色16进制为:#"+Integer.toHexString(r)+Integer.toHexString(g)+Integer.toHexString(b));
}
void GetNum(){
//允许用户输入数值修改rgb
r = Integer.parseInt(textFieldRed.getText());
g = Integer.parseInt(textFieldGreen.getText());
b = Integer.parseInt(textFieldBlue.getText());
}
private void buttonSubRedActionPerformed(ActionEvent e) {
// TODO add your code here
GetNum();
if(r>0&&r<=255)
r--;
else
System.out.println("红色已到临界值");
ShowColor();
}
private void buttonAddRedActionPerformed(ActionEvent e) {
// TODO add your code here
GetNum();
if(r>=0&&r<255)
r++;
else
System.out.println("红色已到临界值");
ShowColor();
}
private void buttonSubGreenActionPerformed(ActionEvent e) {
// TODO add your code here
GetNum();
if(g>0&&g<=255)
g--;
else
System.out.println("绿色已到临界值");
ShowColor();
}
private void buttonAddGreenActionPerformed(ActionEvent e) {
// TODO add your code here
GetNum();
if(g>=0&&g<255)
g++;
else
System.out.println("绿色已到临界值");
ShowColor();
}
private void buttonSubBlueActionPerformed(ActionEvent e) {
// TODO add your code here
GetNum();
if(b>0&&b<=255)
b--;
else
System.out.println("蓝色已到临界值");
ShowColor();
}
private void buttonAddBlueActionPerformed(ActionEvent e) {
// TODO add your code here
GetNum();
if(b>=0&&b<255)
b++;
else
System.out.println("蓝色已到临界值");
ShowColor();
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
panelSetColor = new JPanel();
labelRed = new JLabel();
buttonSubRed = new JButton();
textFieldRed = new JTextField();
buttonAddRed = new JButton();
labelGreen = new JLabel();
buttonSubGreen = new JButton();
textFieldGreen = new JTextField();
buttonAddGreen = new JButton();
labelBlue = new JLabel();
buttonSubBlue = new JButton();
textFieldBlue = new JTextField();
buttonAddBlue = new JButton();
panelColor = new JPanel();
labelShowColor = new JLabel();
//======== this ========
setTitle("2018010587-\u80e1\u6653\u5e06\uff08\u8c03\u8272\u677f\uff09");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(550, 350));
setFont(new Font(Font.DIALOG, Font.PLAIN, 16));
setBackground(Color.white);
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayoutManager(4, 1, new Insets(0, 20, 20, 20), 0, 5));
//======== panelSetColor ========
{
panelSetColor.setFont(panelSetColor.getFont().deriveFont(panelSetColor.getFont().getSize() + 4f));
panelSetColor.setLayout(new GridLayoutManager(3, 4, new Insets(20, 0, 10, 0), 3, 3));
//---- labelRed ----
labelRed.setText("\u7ea2\u8272 R");
labelRed.setForeground(Color.red);
labelRed.setFont(labelRed.getFont().deriveFont(labelRed.getFont().getStyle() | Font.BOLD, labelRed.getFont().getSize() + 4f));
panelSetColor.add(labelRed, new GridConstraints(0, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonSubRed ----
buttonSubRed.setText("\u51cf\u5c11");
buttonSubRed.setFont(buttonSubRed.getFont().deriveFont(buttonSubRed.getFont().getSize() + 4f));
buttonSubRed.addActionListener(e -> buttonSubRedActionPerformed(e));
panelSetColor.add(buttonSubRed, new GridConstraints(0, 1, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- textFieldRed ----
textFieldRed.setText("155");
textFieldRed.setFont(textFieldRed.getFont().deriveFont(textFieldRed.getFont().getSize() + 4f));
panelSetColor.add(textFieldRed, new GridConstraints(0, 2, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonAddRed ----
buttonAddRed.setText("\u589e\u52a0");
buttonAddRed.setFont(buttonAddRed.getFont().deriveFont(buttonAddRed.getFont().getSize() + 4f));
buttonAddRed.addActionListener(e -> buttonAddRedActionPerformed(e));
panelSetColor.add(buttonAddRed, new GridConstraints(0, 3, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- labelGreen ----
labelGreen.setText("\u7eff\u8272 G");
labelGreen.setForeground(new Color(0, 204, 51));
labelGreen.setFont(labelGreen.getFont().deriveFont(labelGreen.getFont().getStyle() | Font.BOLD, labelGreen.getFont().getSize() + 4f));
panelSetColor.add(labelGreen, new GridConstraints(1, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonSubGreen ----
buttonSubGreen.setText("\u51cf\u5c11");
buttonSubGreen.setFont(buttonSubGreen.getFont().deriveFont(buttonSubGreen.getFont().getSize() + 4f));
buttonSubGreen.addActionListener(e -> buttonSubGreenActionPerformed(e));
panelSetColor.add(buttonSubGreen, new GridConstraints(1, 1, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- textFieldGreen ----
textFieldGreen.setText("155");
textFieldGreen.setFont(textFieldGreen.getFont().deriveFont(textFieldGreen.getFont().getSize() + 4f));
panelSetColor.add(textFieldGreen, new GridConstraints(1, 2, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonAddGreen ----
buttonAddGreen.setText("\u589e\u52a0");
buttonAddGreen.setFont(buttonAddGreen.getFont().deriveFont(buttonAddGreen.getFont().getSize() + 4f));
buttonAddGreen.addActionListener(e -> buttonAddGreenActionPerformed(e));
panelSetColor.add(buttonAddGreen, new GridConstraints(1, 3, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- labelBlue ----
labelBlue.setText("\u84dd\u8272 B");
labelBlue.setForeground(new Color(0, 102, 255));
labelBlue.setFont(labelBlue.getFont().deriveFont(labelBlue.getFont().getStyle() | Font.BOLD, labelBlue.getFont().getSize() + 4f));
panelSetColor.add(labelBlue, new GridConstraints(2, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonSubBlue ----
buttonSubBlue.setText("\u51cf\u5c11");
buttonSubBlue.setFont(buttonSubBlue.getFont().deriveFont(buttonSubBlue.getFont().getSize() + 4f));
buttonSubBlue.addActionListener(e -> buttonSubBlueActionPerformed(e));
panelSetColor.add(buttonSubBlue, new GridConstraints(2, 1, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- textFieldBlue ----
textFieldBlue.setText("155");
textFieldBlue.setFont(textFieldBlue.getFont().deriveFont(textFieldBlue.getFont().getSize() + 4f));
panelSetColor.add(textFieldBlue, new GridConstraints(2, 2, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonAddBlue ----
buttonAddBlue.setText("\u589e\u52a0");
buttonAddBlue.setFont(buttonAddBlue.getFont().deriveFont(buttonAddBlue.getFont().getSize() + 4f));
buttonAddBlue.addActionListener(e -> buttonAddBlueActionPerformed(e));
panelSetColor.add(buttonAddBlue, new GridConstraints(2, 3, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
}
contentPane.add(panelSetColor, new GridConstraints(0, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//======== panelColor ========
{
panelColor.setLayout(new GridLayoutManager(1, 1, new Insets(0, 10, 0, 10), 0, 0));
//---- labelShowColor ----
labelShowColor.setText("\u6b64\u5904\u663e\u793a\u6700\u7ec8\u989c\u8272");
panelColor.add(labelShowColor, new GridConstraints(0, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
}
contentPane.add(panelColor, new GridConstraints(2, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JPanel panelSetColor;
private JLabel labelRed;
private JButton buttonSubRed;
private JTextField textFieldRed;
private JButton buttonAddRed;
private JLabel labelGreen;
private JButton buttonSubGreen;
private JTextField textFieldGreen;
private JButton buttonAddGreen;
private JLabel labelBlue;
private JButton buttonSubBlue;
private JTextField textFieldBlue;
private JButton buttonAddBlue;
private JPanel panelColor;
private JLabel labelShowColor;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
带IO操作的登录窗体
编写一个登录窗体,输入用户名和密码,验证通过显示登录成功的消息框,否则显示用户名或密码错误的消息框。用户名和密码存放在 c 盘 java 目录下的 login.txt 中,用文本信息存储,每行一个用户名和密码,用户名和密码用 # 分隔
核心代码
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Arrays;
import javax.swing.*;
import com.intellij.uiDesigner.core.*;
/**
* @author huxiaofan
*/
public class loginPanel extends JFrame {
File f = new File("login.txt"); //创建一个用于读取用户名密码的文件对象
public static void main(String[] args) {
new loginPanel().setVisible(true); //显示窗体
}
public loginPanel() {
initComponents();
}
private void buttonLoginActionPerformed(ActionEvent e) {
// TODO add your code here
if(doLogin())
optionPaneok.showMessageDialog(null,"恭喜你登录成功!","登录成功",JOptionPane.INFORMATION_MESSAGE); //显示成功弹窗
else
optionPanefail.showMessageDialog(null, "用户名密码错误!", "登录失败",JOptionPane.ERROR_MESSAGE); //显示失败弹窗
}
boolean doLogin(){ //函数登录成功返回 true
try {
BufferedReader br = new BufferedReader(new FileReader(f)); //新建字符缓冲流
String u = textFieldUserName.getText(); //获取用户输入在文本框的用户名
String p = String.valueOf(passwordFieldPass.getPassword()); //获取用户输入在密码框的密码,要把原始的字符数组用 String.valueOf() 方法转为字符串
String s; //存放临时读取的每一行字符串
while((s = br.readLine())!=null){
String[] temp = s.split("#"); //拆分字符串
if(temp[0].equals(u)&&temp[1].equals(p)){
System.out.println("登录成功");
return true;
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private void button2ActionPerformed(ActionEvent e) {
// TODO add your code here
}
……
UI自动生成代码
……
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
panel1 = new JPanel();
labelUser = new JLabel();
textFieldUserName = new JTextField();
labelPass = new JLabel();
passwordFieldPass = new JPasswordField();
buttonLogin = new JButton();
optionPaneok = new JOptionPane();
optionPanefail = new JOptionPane();
//======== this ========
setTitle("Emptinessboy \u6155\u8bfeIO\u4f5c\u4e1a");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(420, 250));
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(0, 0, 5, 0), -1, -1));
//======== panel1 ========
{
panel1.setMinimumSize(new Dimension(180, 90));
panel1.setLayout(new GridLayoutManager(2, 2, new Insets(10, 30, 10, 60), 0, 10));
//---- labelUser ----
labelUser.setText("\u7528\u6237\u540d \uff1a");
labelUser.setFont(labelUser.getFont().deriveFont(labelUser.getFont().getStyle() | Font.BOLD, labelUser.getFont().getSize() + 3f));
panel1.add(labelUser, new GridConstraints(0, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- textFieldUserName ----
textFieldUserName.setFont(textFieldUserName.getFont().deriveFont(textFieldUserName.getFont().getSize() + 3f));
panel1.add(textFieldUserName, new GridConstraints(0, 1, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- labelPass ----
labelPass.setText("\u5bc6 \u7801 \uff1a");
labelPass.setFont(labelPass.getFont().deriveFont(labelPass.getFont().getStyle() | Font.BOLD, labelPass.getFont().getSize() + 3f));
panel1.add(labelPass, new GridConstraints(1, 0, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- passwordFieldPass ----
passwordFieldPass.setFont(passwordFieldPass.getFont().deriveFont(passwordFieldPass.getFont().getSize() + 3f));
panel1.add(passwordFieldPass, new GridConstraints(1, 1, 1, 1,
GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
}
contentPane.add(panel1, new GridConstraints(0, 0, 1, 1,
GridConstraints.ANCHOR_SOUTH, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
//---- buttonLogin ----
buttonLogin.setText("\u767b \u5f55");
buttonLogin.setVerticalTextPosition(SwingConstants.TOP);
buttonLogin.setFont(buttonLogin.getFont().deriveFont(buttonLogin.getFont().getStyle() | Font.BOLD, buttonLogin.getFont().getSize() + 3f));
buttonLogin.addActionListener(e -> {
button2ActionPerformed(e);
buttonLoginActionPerformed(e);
});
contentPane.add(buttonLogin, new GridConstraints(1, 0, 1, 1,
GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
null, null, null));
pack();
setLocationRelativeTo(getOwner());
//---- optionPaneok ----
optionPaneok.setIcon(UIManager.getIcon("OptionPane.informationIcon"));
optionPaneok.setMessageType(JOptionPane.INFORMATION_MESSAGE);
//---- optionPanefail ----
optionPanefail.setIcon(UIManager.getIcon("OptionPane.errorIcon"));
optionPanefail.setMessageType(JOptionPane.ERROR_MESSAGE);
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JPanel panel1;
private JLabel labelUser;
private JTextField textFieldUserName;
private JLabel labelPass;
private JPasswordField passwordFieldPass;
private JButton buttonLogin;
private JOptionPane optionPaneok;
private JOptionPane optionPanefail;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
运行效果

This blog is under a CC BY-NC-ND 4.0 Unported License
本文链接:https://coding.emptinessboy.com/2020/05/%E5%87%A0%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84JAVA-GUI%E7%BB%83%E4%B9%A0/