文本浏览器

JFrame图形界面(进阶)和多方法函数传递

发布者 : @gmail | 发布时间 : 2019-01-17 19:21:36
文章号 : 36 | 阅读量 : 93+1 | AAW值(?) : 0.00 (仅供参考)

package com.hotpot.main;
import 
javax.swing.*;
import 
java.awt.*;
class 
Jlget {
    
publicJlget(JLabel jl) {
        
//文字颜色
        
jl.setForeground(Color.RED);
        
jl.setBounds(30,10,280,30);
    
}
}
public class main {
    
public static void main (String[] args) {
        
//新建一个JFrame窗体
        
JFrame jf = new JFrame("电梯模拟器");
        
//设置窗体的宽为400 高为300
        
jf.setSize(400500);
        
//直接设置窗口开启后再屏幕上显示的位置
        
//jf.setLocation(200,200);
        //
设置窗口居中
        
//setLocationRelativeTo: 设置窗口相对坐标
        
jf.setLocationRelativeTo(null);
        
//设置布局(下面一章有解释)
        
jf.setLayout(null);
        
//设置文本内容
        
JLabel jl = new JLabel("文字");
        
Jlget jg = new Jlget(jl);
         
jf.add(jl);
        
//点叉之后结束进程
        
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
//显示窗口
        
jf.setVisible(true);
    
}
}

显示网络图片

package com.hotpot.main;
import 
javax.swing.*;
import 
java.awt.*;
import 
java.util.Scanner;
public class 
main {
    
public static void main (String[] args) {
        
//新建一个JFrame窗体
        
JFrame jf = new JFrame("电梯模拟器");
        
//设置窗体的宽为400 高为300
        
jf.setSize(400500);
        
//直接设置窗口开启后再屏幕上显示的位置
        
//jf.setLocation(200,200);
        //
设置窗口居中
        
//setLocationRelativeTo: 设置窗口相对坐标
        
jf.setLocationRelativeTo(null);
        
//设置布局(下面一章有解释)
        
jf.setLayout(null);
        
//设置文本内容
        
JLabel jl = new JLabel("显示文本1");
        
Jlget jg = new Jlget(jl);
        
//添加文本框到窗体
         
jf.add(jl);
         
System.out.println("输入图片地址: ");
        
JLabel pic = new JLabel();
        
Scanner scn1 = new Scanner(System.in);
        
String url = scn1.nextLine();
        
System.out.println("图片下载中...");
        
PicDisplay pd = new PicDisplay(picurl);
        
jf.add(pic);
        
//点叉之后结束进程
        
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
//显示窗口
        
jf.setVisible(true);
    
}
}
class Jlget {
    
publicJlget(JLabel jl) {
        
//文字颜色
        
jl.setForeground(Color.RED);
        
jl.setBounds(30,10,280,30);
    
}
}
class PicDisplay { //图片
    
publicPicDisplay(JLabel jlString url) {
        jl.setText(
"<html><img src='" + url + "'/></html>");
        
jl.setBounds(3040128128);
    
}
}

(重要)更多实现

标签

Label用于显示文字

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(null);
        JLabel l = new JLabel("LOL文字");
        //文字颜色
        l.setForeground(Color.red);
        l.setBounds(50, 50, 280, 30);
        f.add(l);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

使用JLabel显示图片

java GUI 显示图片是通过在label上设置图标实现的

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(580, 200);
        f.setLayout(null);
        JLabel l = new JLabel();
        //根据图片创建ImageIcon对象
        ImageIcon i = new ImageIcon("e:/project/j2se/shana.png");
        //设置ImageIcon
        l.setIcon(i);
        //label的大小设置为ImageIcon,否则显示不完整
        l.setBounds(50, 50, i.getIconWidth(), i.getIconHeight());
        f.add(l);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

按钮

JButton 普通按钮

import javax.swing.JButton;
import javax.swing.JFrame;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(null);
        JButton b = new JButton("一键秒对方基地挂");
        b.setBounds(50, 50, 280, 30);
        f.add(b);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

复选框

JCheckBox 复选框

使用isSelected来获取是否选中了

import javax.swing.JCheckBox;
import javax.swing.JFrame;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(580, 200);
        f.setLayout(null);
        JCheckBox bCheckBox = new JCheckBox("物理英雄");
        //设置 为 默认被选中 
        bCheckBox.setSelected(true);
        bCheckBox.setBounds(50, 50, 130, 30);
        JCheckBox bCheckBox2 = new JCheckBox("魔法英雄");
        bCheckBox2.setBounds(50, 100, 130, 30);
        //判断 是否 被 选中 
        System.out.println(bCheckBox2.isSelected());
        f.add(bCheckBox);
        f.add(bCheckBox2);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

5单选框

JRadioButton 单选框 
使用isSelected来获取是否选中了 
为了实现只能选中一个,还需要用到ButtonGroup

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(580, 200);
        f.setLayout(null);
        JRadioButton b1 = new JRadioButton("物理英雄");
        // 设置 为 默认被选中
        b1.setSelected(true);
        b1.setBounds(50, 50, 130, 30);
        JRadioButton b2 = new JRadioButton("魔法 英雄");
        b2.setBounds(50, 100, 130, 30);
        System.out.println(b2.isSelected());
        f.add(b1);
        f.add(b2);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

按钮组

ButtonGroup 对按钮进行分组,把不同的按钮,放在同一个分组里,同一时间,只有一个按钮会被选中

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(580, 240);
        f.setLayout(null);
        JRadioButton b1 = new JRadioButton("物理英雄");
        b1.setSelected(true);
        b1.setBounds(50, 50, 130, 30);
        JRadioButton b2 = new JRadioButton("魔法 英雄");
        b2.setBounds(50, 100, 130, 30);
        // 按钮分组
        ButtonGroup bg = new ButtonGroup();
        // b1b2放在 同一个 按钮分组对象里 ,这样同一时间,只有一个 按钮 会被选中
        bg.add(b1);
        bg.add(b2);
        f.add(b1);
        f.add(b2);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

下拉框

JComboBox 下拉框 
使用getSelectedItem来获取被选中项 
使用setSelectedItem() 来指定要选中项

import javax.swing.JComboBox;
import javax.swing.JFrame;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(580, 240);
        f.setLayout(null);
        //下拉框出现的条目
        String[] heros = new String[] { "卡特琳娜", "库奇" };
        JComboBox cb = new JComboBox(heros);
        cb.setBounds(50, 50, 80, 30);
        f.add(cb);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

对话框

JOptionPane 用于弹出对话框

JOptionPane.showConfirmDialog(f, “是否使用外挂”); 
表示询问,第一个参数是该对话框以哪个组件对齐 
JOptionPane.showInputDialog(f, “
请输入yes,表明使用外挂后果自负”); 
接受用户的输入 
JOptionPane.showMessageDialog(f, “
你使用外挂被抓住!“); 
显示消息

mport javax.swing.JFrame;
import javax.swing.JOptionPane;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(580, 240);
        f.setLayout(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        int option = JOptionPane.showConfirmDialog(f, "是否 使用外挂 ?");
        if (JOptionPane.OK_OPTION == option) {
            String answer = JOptionPane.showInputDialog(f, "请输入yes,表明使用外挂后果自负");
            if ("yes".equals(answer))
                JOptionPane.showMessageDialog(f, "你使用外挂被抓住! 封号一年!");
        }
    }
}

文本框

JTextField 输入框 
setText 
设置文本 
getText 
获取文本 
JTextField 
是单行文本框,如果要输入多行数据,请使用JTextArea

tfPassword.grabFocus(); 表示让密码输入框获取焦点

import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(new FlowLayout());
        JLabel lName = new JLabel("账号:");
        // 输入框
        JTextField tfName = new JTextField("");
        tfName.setText("请输入账号");
        tfName.setPreferredSize(new Dimension(80, 30));
        JLabel lPassword = new JLabel("密码:");
        // 输入框
        JTextField tfPassword = new JTextField("");
        tfPassword.setText("请输入密码");
        tfPassword.setPreferredSize(new Dimension(80, 30));
        f.add(lName);
        f.add(tfName);
        f.add(lPassword);
        f.add(tfPassword);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        tfPassword.grabFocus();
    }
}

10 密码框

JPasswordField 密码框 
与文本框不同,获取密码框里的内容,推荐使用getPassword,该方法会返回一个字符数组,而非字符串

import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(new FlowLayout());
        JLabel l = new JLabel("密码:");
        // 密码框
        JPasswordField pf = new JPasswordField("");
        pf.setText("&48kdh4@#");
        pf.setPreferredSize(new Dimension(80, 30));
        // 与文本框不同,获取密码框里的内容,推荐使用getPassword,该方法会返回一个字符数组,而非字符串
        char[] password = pf.getPassword();
        String p = String.valueOf(password);
        System.out.println(p);
        f.add(l);
        f.add(pf);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

11 文本域

JTextArea:文本域。 
和文本框JTextField不同的是,文本域可以输入多行数据 
如果要给文本域初始文本,通过\n来实现换行效果 
JTextArea
通常会用到append来进行数据追加 
如果文本太长,会跑出去,可以通过setLineWrap(true)来做到自动换行

import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(new FlowLayout());
        JLabel l = new JLabel("文本域:");
        JTextArea ta = new JTextArea();
        ta.setPreferredSize(new Dimension(200, 150));
        //\n换行符
        ta.setText("抢人头!\n抢你妹啊抢!\n");
        //追加数据
        ta.append("我去送了了了了了了了了了了了了了了了了了了了了了了了了");
        //设置自动换行
        ta.setLineWrap(true);
        f.add(l);
        f.add(ta);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

12 进度条

import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JTextArea;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(new FlowLayout());
        JProgressBar pb = new JProgressBar();
        //进度条最大100
        pb.setMaximum(100);
        //当前进度是50
        pb.setValue(50);
        //显示当前进度
        pb.setStringPainted(true);
        f.add(pb);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

13 文件选择器

JFileChooser 表示文件选择器 
使用FileFilter用于仅选择.txt文件

fc.setFileFilter(new FileFilter() {
    public String getDescription() {
        return ".txt";
    }
    public boolean accept(File f) {
        return f.getName().toLowerCase().endsWith(".txt");
    }
});

fc.showOpenDialog(); 用于打开文件 
fc.showSaveDialog(); 
用于保存文件

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
public class TestGUI {
    public static void main(String[] args) {
        final JFrame f = new JFrame("LOL");
        f.setLayout(new FlowLayout());
        final JFileChooser fc = new JFileChooser();
        fc.setFileFilter(new FileFilter() {
            @Override
            public String getDescription() {
                // TODO Auto-generated method stub
                return ".txt";
            }
            @Override
            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".txt");
            }
        });
        JButton bOpen = new JButton("打开文件");
        JButton bSave = new JButton("保存文件");
        f.add(bOpen);
        f.add(bSave);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(250, 150);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        bOpen.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                 int returnVal =  fc.showOpenDialog(f);
                 File file = fc.getSelectedFile();
                 if (returnVal == JFileChooser.APPROVE_OPTION) {
                     JOptionPane.showMessageDialog(f, "计划打开文件:" + file.getAbsolutePath());
                 }
            }
        });
        bSave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int returnVal =  fc.showSaveDialog(f);
                File file = fc.getSelectedFile();
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    JOptionPane.showMessageDialog(f, "计划保存到文件:" + file.getAbsolutePath());
                }
            }
        });
    }

 
}

面板

基本面板

JPanel 即为基本面板 
面板和JFrame一样都是容器,不过面板一般用来充当中间容器,把组件放在面板上,然后再把面板放在窗体上。 
一旦移动一个面板,其上面的组件,就会全部统一跟着移动,采用这种方式,便于进行整体界面的设计

import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(null);
        JPanel p1 = new JPanel();
        // 设置面板大小
        p1.setBounds(50, 50, 300, 60);
        // 设置面板背景颜色
        p1.setBackground(Color.RED);
        // 这一句可以没有,因为JPanel默认就是采用的FlowLayout
        p1.setLayout(new FlowLayout());
        JButton b1 = new JButton("英雄1");
        JButton b2 = new JButton("英雄2");
        JButton b3 = new JButton("英雄3");
        // 把按钮加入面板
        p1.add(b1);
        p1.add(b2);
        p1.add(b3);
        JPanel p2 = new JPanel();
        JButton b4 = new JButton("英雄4");
        JButton b5 = new JButton("英雄5");
        JButton b6 = new JButton("英雄6");
        p2.add(b4);
        p2.add(b5);
        p2.add(b6);
        p2.setBackground(Color.BLUE);
        p2.setBounds(10, 150, 300, 60);
        // 把面板加入窗口
        f.add(p1);
        f.add(p2);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

2 ContentPanel

JFrame上有一层面板,叫做ContentPane 
平时通过f.add()JFrame增加组件,其实是向JFrame上的ContentPane加东西

import javax.swing.JButton;
import javax.swing.JFrame;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(null);
        JButton b = new JButton("一键秒对方基地挂");
        b.setBounds(50, 50, 280, 30);
        f.add(b);
        // JFrame上有一层面板,叫做ContentPane
        // 平时通过f.add()JFrame增加组件,其实是向JFrame上的 ContentPane加东西
        // f.add等同于f.getContentPane().add(b);
        f.getContentPane().add(b);
        // b.getParent()获取按钮b所处于的容器
        // 打印出来可以看到,实际上是ContentPane而非JFrame
        System.out.println(b.getParent());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

3 SplitPanel

创建一个水平JSplitPane,左边是pLeft,右边是pRight

import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(null);
        JPanel pLeft = new JPanel();
        pLeft.setBounds(50, 50, 300, 60);
        pLeft.setBackground(Color.RED);
        pLeft.setLayout(new FlowLayout());
        JButton b1 = new JButton("盖伦");
        JButton b2 = new JButton("提莫");
        JButton b3 = new JButton("安妮");
        pLeft.add(b1);
        pLeft.add(b2);
        pLeft.add(b3);
        JPanel pRight = new JPanel();
        JButton b4 = new JButton("英雄4");
        JButton b5 = new JButton("英雄5");
        JButton b6 = new JButton("英雄6");
        pRight.add(b4);
        pRight.add(b5);
        pRight.add(b6);
        pRight.setBackground(Color.BLUE);
        pRight.setBounds(10, 150, 300, 60);
        // 创建一个水平JSplitPane,左边是p1,右边是p2
        JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, pLeft, pRight);
        // 设置分割条的位置
        sp.setDividerLocation(80);
        // sp当作ContentPane
        f.setContentPane(sp);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

4 JScrollPanel

使用带滚动条的面板有两种方式 
1. 
在创建JScrollPane,把组件作为参数传进去

JScrollPane sp = new JScrollPane(ta);

希望带滚动条的面板现实其他组件的时候,调用setViewportView

sp.setViewportView(ta);

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(null);
        //准备一个文本域,在里面放很多数据
        JTextArea ta = new JTextArea();
        for (int i = 0; i < 1000; i++) {
            ta.append(String.valueOf(i));
        }
        //自动换行
        ta.setLineWrap(true);
        JScrollPane sp = new JScrollPane(ta);
        f.setContentPane(sp);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

5 TabbedPanel

import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("LoL");
        f.setSize(400, 300);
        f.setLocation(200, 200);
        f.setLayout(null);
        JPanel p1 = new JPanel();
        p1.setBounds(50, 50, 300, 60);
        p1.setBackground(Color.RED);
        p1.setLayout(new FlowLayout());
        JButton b1 = new JButton("英雄1");
        JButton b2 = new JButton("英雄2");
        JButton b3 = new JButton("英雄3");
        p1.add(b1);
        p1.add(b2);
        p1.add(b3);
        JPanel p2 = new JPanel();
        JButton b4 = new JButton("英雄4");
        JButton b5 = new JButton("英雄5");
        JButton b6 = new JButton("英雄6");
        p2.add(b4);
        p2.add(b5);
        p2.add(b6);
        p2.setBackground(Color.BLUE);
        p2.setBounds(10, 150, 300, 60);
        JTabbedPane tp = new JTabbedPane();
        tp.add(p1);
        tp.add(p2);
        // 设置tab的标题
        tp.setTitleAt(0, "红色tab");
        tp.setTitleAt(1, "蓝色tab");
        ImageIcon i = new ImageIcon("e:/project/j2se/j.png");
        tp.setIconAt(0,i );
        tp.setIconAt(1,i );
        f.setContentPane(tp);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

6 CardLayerout

CardLayerout 布局器很像TTabbedPanel ,在本例里面上面是一个下拉框,下面是一个CardLayerout JPanel 
这个JPanel里有两个面板,可以通过CardLayerout方便的切换

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TestGUI {
    public static void main(String[] args) {
        JFrame f = new JFrame("CardLayerout");
        JPanel comboBoxPane = new JPanel();
        String buttonPanel = "按钮面板";
        String inputPanel = "输入框面板";
        String comboBoxItems[] = { buttonPanel, inputPanel };
        JComboBox<String> cb = new JComboBox<>(comboBoxItems);
        comboBoxPane.add(cb);
        // 两个Panel充当卡片
        JPanel card1 = new JPanel();
        card1.add(new JButton("按钮 1"));
        card1.add(new JButton("按钮 2"));
        card1.add(new JButton("按钮 3"));
        JPanel card2 = new JPanel();
        card2.add(new JTextField("输入框", 20));
        JPanel cards; // a panel that uses CardLayout
        cards = new JPanel(new CardLayout());
        cards.add(card1, buttonPanel);
        cards.add(card2, inputPanel);
        f.add(comboBoxPane, BorderLayout.NORTH);
        f.add(cards, BorderLayout.CENTER);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(250, 150);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        cb.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent evt) {
                CardLayout cl = (CardLayout) (cards.getLayout());
                cl.show(cards, (String) evt.getItem());
            }
        });     
    }
}

(重要)单击按钮事件

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

 

//本类继承与JFrame窗体实现ActionListener接口

public class MyFrame extends JFrame implements ActionListener {

    JTextField jtf;//文本框

    JButton jbt;//按钮

 

    public MyFrame() {

        jtf = new JTextField(8);//文本框的初始化

        jbt = new JButton("按钮");//按钮的初始化

        jbt.addActionListener(this);//给按钮响应点击事件

        add(jtf);

        add(jbt);

        setLayout(new FlowLayout());

        setTitle("测试");

        setSize(300, 150);

        setLocationRelativeTo(null);//窗口居中

        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setVisible(true);//窗口可见

    }

 

    //重点重点是实现actionPerformed的方法

    public void actionPerformed(ActionEvent e) {

        if (jbt == e.getSource()) {//如果是jbt这个按钮被点击了,

            String str = jbt.getText();//那么取得按钮上的文字,

            jtf.setText(str);//把按钮的文字显示到文本框中.

        }

    }

 

    public static void main(String[] args) {

        new MyFrame(); // 创建窗口实例

    }

     

}

(重要)实例

package com.hotpot.main;
import 
javax.swing.*;
import 
java.awt.event.ActionEvent;
import 
java.awt.event.ActionListener;
public class 
main implements ActionListener{
    
//新建一个JFrame窗体
    
JFramejf new JFrame("电梯模拟器");
    
JButtonjba new JButton("↑")//初始化按钮
    
public static void main (String[] args) {
        main m = 
new main();
        
m.jf.setSize(400500);
        
m.jf.setLocationRelativeTo(null)//窗口居中
        
m.jf.setLayout(null);
        
m.jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)//点叉后关闭
        
m.jf.setVisible(true);
        
m.FrameA();
    
}
    
public void FrameA() {
        
jba.addActionListener(this);
        
jba.setBounds(100,40,50,30);
        
jf.add(jba);
    
}
    
public void actionPerformed(ActionEvent e) {
        
if (jba == e.getSource()) {
            System.
out.println("okay~");
        
}
    }
}
class Int2String {
    String 
ArgFloor "";
    public 
Int2String(int FloorInt) {
        
ArgFloor = FloorInt + "";
    
}
    String 
returnString() {
        
return ArgFloor;
    
}
    
voidsetInt(int FloorInt) {
        
ArgFloor = FloorInt + "";
    
}
}

运行结果(点击按钮控制台输出)

okay~

(重要)文本域滚动条

package com.hotpot.main;
import 
javax.swing.*;
import 
java.awt.event.ActionEvent;
import 
java.awt.event.ActionListener;
public class 
main implements ActionListener{
    
intflnow;
    
JTextAreajta new JTextArea();
    
Int2Stringin new Int2String(0)//初始化转换器
    
//新建一个JFrame窗体
    
JFramejf new JFrame("电梯模拟器");
    
JButtonjba new JButton("↑")//初始化按钮
    
JLabeljl new JLabel("当前楼层: ");
    
JLabelfloor new JLabel("")//楼层按钮
    
JScrollPanejsp new JScrollPane(jta)//状态栏的滚动条
    
public static void main (String[] args) {
        main m = 
new main();
        
m.jf.setSize(400500);
        
m.jf.setLocationRelativeTo(null)//窗口居中
        
m.jf.setLayout(null);
        
m.jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)//点叉后关闭
        
m.jf.setVisible(true);
        
m.FrameA();
    
}
    
public void FrameA() {
        
//文本
        
jl.setBounds(20,10,280,30);
        
jf.add(jl);
        
//楼层显示(初始化)
        
floor.setBounds(100,10,280,30);
        
flnow 1;
        
in.setInt(flnow);
        
floor.setText(in.returnString());
        
jf.add(floor);
        
//按钮
        
jba.addActionListener(this);
        
jba.setBounds(100,40,50,30);
        
jf.add(jba);
        
//文本域
       
// jta.setPreferredSize(new Dimension(200 ,150));
        
jsp.setBounds(210,20,150,200);
        
jsp.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        
//jta.setBounds(100,80,150,200);
        
jta.setEditable(false);
        
jta.setText("运行日志:\n");
        
jf.add(jsp);
        
jta.append("电梯已启动.\n");
    
}
    
public void actionPerformed(ActionEvent e) {
        
if (jba == e.getSource()) {
            
if (flnow 29) {
                System.
out.println("too high!");
            
else {
                
jta.append("接收到外部信号:上楼\n");
                
flnow++;
                
in.setInt(flnow);
                
floor.setText(in.returnString());
            
}
        }
    }
}
class Int2String {
    String 
ArgFloor "";
    public 
Int2String(int FloorInt) {
        
ArgFloor = FloorInt + "";
    
}
    String 
returnString() {
        
return ArgFloor;
    
}
    
voidsetInt(int FloorInt) {
        
ArgFloor = FloorInt + "";
    
}
}

JLable设置字体,大小,颜色

m.jl.setFont(new Font("微软雅黑"Font.BOLD13));

JFrame里的滚动条跟随内容自动滚动

public static void scrollAndSetCursor(JTextArea ta){ //自动滚动
    
ta.setSelectionStart(ta.getText().length());
}

(重要)创建/读取配置文件

新建一个配置文件”config.ini”并写入默认设置

Properties pro new Properties();

pro.put("GuestDefaultFloor""10");

pro.store(new BufferedOutputStream(new FileOutputStream("config.ini")),"Save Configs File.");

三个步骤:

new Properties 实例化

put放入配置

store保存

读取配置文件并转换为String

Properties pro new Properties();

pro.load(new BufferedInputStream(new FileInputStream("config.ini")));
String defaultGuestFloor = pro.getProperty("GuestDefaultFloor");

也是三个步骤:

new Properties 实例化

load加载配置

使用getProperty赋值给String

可以自动判断配置文件是否已经存在,如果不存在自动创建,如果存在直接读写的实例代码:

try {
    
pro.load(new BufferedInputStream(newFileInputStream("config.ini")));
catch (FileNotFoundException e) {
    
pro.put("GuestDefaultFloor""10");
    try 
{
        
pro.store(new BufferedOutputStream(new FileOutputStream("config.ini")),"Save Configs File.");
    
}catch (FileNotFoundException f) {
        f.printStackTrace()
;
   
catch (IOException i) {
        i.printStackTrace()
;
    
}
catch (IOException i) {
    i.printStackTrace()
;
finally {
    String defaultGuestFloor = 
pro.getProperty("GuestDefaultFloor");
    
guestFloor= Integer.parseInt(defaultGuestFloor);
}

JFrame表格

String[] colName = {"类型""文件名""大小"};
DefaultTableModel contactTableModel = (DefaultTableModel) jt.
        getModel()
;
contactTableModel.setColumnIdentifiers(colName);
jt.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(jsp);
jsp.setBounds(20,150,450,400);
DefaultTableModel tablemo = (DefaultTableModel) jt.getModel() ;
jt.setModel(tablemo);
String[] data = {"haha","wawa","yaya"};
tablemo.addRow(data);
String[] data2 = {"gaga""lala""kaka"};
tablemo.addRow(data2);






评论加载中...

+ 参与讨论