都2021年了,还有人用JavaSwing?这只是我的一个爱好,我喜欢做界面开发,但是又只有Java还学的不错,大部分Java书籍中对JavaSwing介绍的都比较一般,我便找了《Java2图形设计卷IISwing》介绍的还算不错,正好中秋节有点时间,学习整理了一下,整本书约1000页,肯定没有全部记录,记录了一下我感觉比较好玩的,若你热爱JavaGUI编程,全部看下来一定有所收获
Swing组件类以J开头
Swing设置JFrame风格(必须在显示前调用)
String lookAndFeel = "javax.swing.plaf.metal.MetalLookAndFeel";
UIManager.setLookAndFeel(lookAndFeel);
String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
UIManager.setLookAndFeel(lookAndFeel);
String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel";
UIManager.setLookAndFeel(lookAndFeel);
String lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
UIManager.setLookAndFeel(lookAndFeel);
String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(lookAndFeel);
默认BorderLayout
add(new JButton("TEST"),BorderLayout.SOUTH);
关闭窗口事件
DO_NOTHING_ON_CLOSE
HIDE_ON_CLOSE
DISPOSE_ON_CLOSE
EXIT_ON_CLOSE
可以通过setPreferredSize设置JScrollPane显示的内容大小
myPanel.setPreferredSize(new Dimension(2000,2000));
添加使用子窗体
JInternalFrame frame = new JInternalFrame("内部窗体",true);
frame.setSize(100,100);
frame.setVisible(true);
JDesktopPane desktopPane = new JDesktopPane();
desktopPane.add(frame);
add(desktopPane);
desktopPane.getAllFrames();
desktopPane.getSelectedFrame();
Swing线程不安全
SwingUtilities工具类
SwingUtilities.invokeLater(() -> {
});
SwingUtilities.invokeAndWait(() -> {
});
监听组件属性变化
addPropertyChangeListener(evt -> {
System.out.println(evt.getPropertyName()+":"+evt.getOldValue()+"->"+evt.getNewValue());
});
addPropertyChangeListener("属性名", evt -> {
});
自定义UI组件
class MyButton extends JButton{
@Override
public boolean contains(int x, int y) {
return super.contains(x, y);
}
@Override
public void paint(Graphics g) {
super.paint(g);
}
@Override
public String getToolTipText(MouseEvent event) {
if(event.getX()<50){
return "PPPPPPPP";
}else {
return "OOOOOOOOOOOOO";
}
}
@Override
public Point getToolTipLocation(MouseEvent event) {
return new Point(0,0);
}
}
开启日志
myPanel.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION);
工具提示
list.setToolTipText("OKKKKKKKKKKKK");
JLabel按键事件
myPanel.setFocusable(true);
焦点切换
默认使用Tab切换焦点,Tab+Shift切换到上一个焦点
边框
setBorder(new TitledBorder("PPPP"));
自定义边框
class MyBorder extends AbstractBorder{
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
g.drawLine(x,y,x+width,y+height);
}
}
边框默认绘制在内容下面
自定义图标
class MyIcon implements Icon{
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.drawRect(x,y,64,64);
}
@Override
public int getIconWidth() {
return 64;
}
@Override
public int getIconHeight() {
return 64;
}
}
ImageIcon支持gif
JFrame重绘
validate();
repaint();
计时器
Timer timer = new Timer(1000, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("OKKKKKKKKKKK");
}
});
timer.setRepeats(false);
timer.start();
SwingUtilities常用方法
集合计算
坐标转换
事件辅助判断
BoxLayout(类似线性布局)
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
GridBagLayout网格布局
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill=GridBagConstraints.BOTH;
constraints.gridx=0;
constraints.gridy=0;
constraints.weightx=2;
constraints.weighty=2;
JButton button = new JButton("OK");
layout.setConstraints(button,constraints);
add(button);
ProgressMonitor
ProgressMonitor monitor = new ProgressMonitor(this, "进度", "OKKKK", 0, 100);
monitor.setProgress(i);
ProgressMonitorInputStream stream = new ProgressMonitorInputStream(this, "TEST",
new FileInputStream("E:\\IDEA\\MyTest3\\src\\main\\resources\\test.gif"));
undo与redo
UndoManager manager=new UndoManager();
MyEdit myEdit = new MyEdit();
myEdit.redo();
manager.addEdit(myEdit);
manager.undo();
manager.redo();
class MyEdit extends AbstractUndoableEdit{
@Override
public void undo() throws CannotUndoException {
System.out.println("undo");
}
@Override
public void redo() throws CannotRedoException {
System.out.println("redo");
}
}
UIManager(操作可以立即生效,动态修改)
UIManager.put("Tree.background",Color.BLACK);
Object o = UIManager.get("");
String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
UIManager.setLookAndFeel(lookAndFeel);
设置属性
button.putClientProperty("","");
JLabel设置文本与图片
JLabel label = new JLabel("TEST", new ImageIcon("E:\\IDEA\\MyTest3\\src\\main\\resources\\test.gif"),
SwingConstants.RIGHT);
label.setVerticalTextPosition(SwingConstants.BOTTOM);
label.setHorizontalTextPosition(SwingConstants.CENTER);
label.setIconTextGap(23);
为组件设置快捷键
button.setMnemonic('M');
JToggleButton使用
JToggleButton test = new JToggleButton("TEST");
test.addChangeListener(e -> {
});
按钮组
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < 5; i++) {
JToggleButton button = new JToggleButton("TEST" + i);
group.add(button);
add(button);
}
for (int i = 0; i < 5; i++) {
JCheckBox box = new JCheckBox("TEST");
group.add(box);
add(box);
}
for (int i = 0; i < 5; i++) {
JRadioButton button = new JRadioButton("TEST");
group.add(button);
add(button);
}
JMenuBar与JToolBar
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("TEST");
menu.addSeparator();
JMenuItem item = new JMenuItem("TEST1");
menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK));
menuBar.add(menu);
setJMenuBar(menuBar);
JToolBar toolBar = new JToolBar("TEST");
toolBar.add("TEST1",new JButton("TEST"));
add(toolBar);
右键弹出菜单
JPopupMenu popupMenu = new JPopupMenu("TEST");
popupMenu.add("TEST1");
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(e.getButton()==MouseEvent.BUTTON3){
popupMenu.show(Test5.this,e.getX(),e.getY());
}
}
});
Swing不是线程安全的
SwingUtilities.invokeLater();
JProgressBar
JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setValue(23);
progressBar.setStringPainted(true);
progressBar.setString(String.valueOf(i));
JSlider
JSlider slider = new JSlider(0, 100);
slider.setPaintLabels(true);
slider.setMajorTickSpacing(20);
button.setPreferredSize(new Dimension(i*5,20));
button.revalidate();
玻璃窗格
MyPanel my=new MyPanel();
setGlassPane(my);
button1.addChangeListener(e -> {
JToggleButton source = (JToggleButton) e.getSource();
my.setVisible(source.isSelected());
});
class MyPanel extends JPanel{
public My() {
setOpaque(false);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("OOOOOOOOOOO",100,100);
}
}
可以分层显示的Pane
JLayeredPane layeredPane = new JLayeredPane();
JButton button2 = new JButton("EEEE");
layeredPane.setLayer(button2,JLayeredPane.DRAG_LAYER);
layeredPane.add(button2);
add(layeredPane);
JTabbedPane选项卡使用
JTabbedPane tabbedPane = new JTabbedPane(SwingConstants.BOTTOM);
tabbedPane.add("TEST1",new JPanel());
add(tabbedPane);
JSplitPane使用
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setLeftComponent(new JPanel());
splitPane.setRightComponent(new JPanel());
splitPane.setDividerLocation(200);
JViewport使用(滚动视图的基础)
JViewport viewport = new JViewport();
MyPanel panel = new MyPanel();
panel.setPreferredSize(new Dimension(1000,1000));
viewport.setView(panel);
JButton button = new JButton("移动");
button.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
Point point = viewport.getViewPosition();
point.x+=5;
point.y+=5;
viewport.setViewPosition(point);
}
});
JScrollPane设置内容头信息
JScrollPane pane = new JScrollPane(panel);
pane.setColumnHeaderView(new JLabel(
new ImageIcon("E:\\IDEA\\MyTest3\\src\\main\\resources\\1.png")));
pane.setRowHeaderView(new JLabel(
new ImageIcon("E:\\IDEA\\MyTest3\\src\\main\\resources\\2.png")));
JTextArea设置自动换行
JTextArea area = new JTextArea("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
area.setLineWrap(true);
没有专门的状态条通过JLable实现
add(new JLabel("TEST"),BorderLayout.SOUTH);
JWindow使用
JWindow window = new JWindow();
window.add(new JLabel(new ImageIcon("E:\\IDEA\\MyTest3\\src\\main\\resources\\test.gif")));
window.setSize(300,300);
window.setVisible(true);
window.dispose();
JOptionPane工具类(会阻塞线程)
JOptionPane pane = new JOptionPane("AAAAAAAAAAAAAAA");
add(pane);
DefaultDesktopManager
调整组件触发窗口事件工具类
JFileChooser使用
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("txt"));
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setMultiSelectionEnabled(true);
chooser.setFileView(new FileView() {
@Override
public String getName(File f) {
return "TEST";
}
@Override
public Icon getIcon(File f) {
return super.getIcon(f);
}
});
设置预览
MyLabel label = new MyLabel();
chooser.setAccessory(label);
chooser.addPropertyChangeListener(label);
class MyLabel extends JLabel implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)){
System.out.println(evt.getNewValue());
}
}
}
JList
JList<String> list = new JList<>("aaa,a,a,a,a,,a,a,a,a,a,asds,a".split(","));
JScrollPane scrollPane = new JScrollPane(list);
list.setVisibleRowCount(3);
list.setCellRenderer((list1, value, index, isSelected, cellHasFocus) -> new JLabel(value));
list.setPrototypeCellValue("AAAAA");
JComboBox
JComboBox<String> box = new JComboBox<>("A,SD,DFG,SDF,SD,G,DSFG".split(","));
box.setEditable(true);
box.addItem("AAA");
box.removeAllItems();
box.setRenderer((list, value, index, isSelected, cellHasFocus) -> new JLabel(value));
box.setKeySelectionManager(new JComboBox.KeySelectionManager() {
@Override
public int selectionForKey(char key, ComboBoxModel model) {
return 0;
}
});
box.setEditor(new ComboBoxEditor() {
@Override
public Component getEditorComponent() {
return new JButton("TEST");
}
@Override
public void setItem(Object anObject) {
System.out.println(anObject);
}
@Override
public Object getItem() {
return null;
}
@Override
public void selectAll() {
System.out.println("selectAll");
}
@Override
public void addActionListener(ActionListener l) {
}
@Override
public void removeActionListener(ActionListener l) {
}
});
box.showPopup();
JTable使用
String[] headers={"TEST1","TEST2","TEST3","TEST4"};
Integer[][] data={
{12,345,456,34},
{12,345,456,34},
{12,345,456,34}
};
JTable table = new JTable(data, headers);
DefaultTableModel model=new DefaultTableModel();
String[] items = "TEST1,TEST2,TEST3,TEST4".split(",");
for (int i = 0; i < items.length; i++) {
model.addColumn(items[i]);
}
for (int i = 0; i < 10; i++) {
model.addRow("A,B,V,C".split(","));
}
JTable table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setDefaultRenderer(Integer.class, new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
return new JLabel(value.toString());
}
});
table.getColumnModel().setColumnMargin(12);
有各种操作表格的方法
还可以添加监听事件
class MyTableModel implements TableModel{
@Override
public int getRowCount() {
return 100;
}
@Override
public int getColumnCount() {
return 4;
}
@Override
public String getColumnName(int columnIndex) {
return "TEST"+columnIndex;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return Boolean.class;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return Boolean.TRUE;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
System.out.println("setValueAt");
}
@Override
public void addTableModelListener(TableModelListener l) {}
@Override
public void removeTableModelListener(TableModelListener l) {}
}
冻结首列的方法
创建两个表,作为首列的表通过scrollPane.setRowHeaderView();设置为固定头部
设置各种选择模式
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(true);
table.setCellSelectionEnabled(true);
为指定列设置渲染器与编辑器
TableColumn column = table.getColumnModel().getColumn(1);
column.setCellEditor(new TableCellEditor() {
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
return null;
}
@Override
public Object getCellEditorValue() {
return Boolean.FALSE;
}
@Override
public boolean isCellEditable(EventObject anEvent) {
return false;
}
@Override
public boolean shouldSelectCell(EventObject anEvent) {
return false;
}
@Override
public boolean stopCellEditing() {
return false;
}
@Override
public void cancelCellEditing() {
}
@Override
public void addCellEditorListener(CellEditorListener l) {
}
@Override
public void removeCellEditorListener(CellEditorListener l) {
}
});
column.setCellRenderer(new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
return null;
}
});
JTree的使用
DefaultMutableTreeNode root=new DefaultMutableTreeNode("ROOT");
for (int i = 0; i < 100; i++) {
root.add(new DefaultMutableTreeNode("TEST"+i));
}
JTree tree = new JTree(root);
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
}
});
tree.addTreeExpansionListener(new TreeExpansionListener() {
@Override
public void treeExpanded(TreeExpansionEvent event) {
}
@Override
public void treeCollapsed(TreeExpansionEvent event) {
}
});
tree.addTreeWillExpandListener(new TreeWillExpandListener() {
@Override
public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
}
@Override
public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
throw new ExpandVetoException(event,"不能展开");
}
});
提供了大量操作节点的方法
定制显示与编辑器
tree.setCellRenderer(new TreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
return null;
}
});
tree.setCellEditor(new TreeCellEditor() {
@Override
public Component getTreeCellEditorComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row) {
return null;
}
@Override
public Object getCellEditorValue() {
return null;
}
@Override
public boolean isCellEditable(EventObject anEvent) {
return false;
}
@Override
public boolean shouldSelectCell(EventObject anEvent) {
return false;
}
@Override
public boolean stopCellEditing() {
return false;
}
@Override
public void cancelCellEditing() {
}
@Override
public void addCellEditorListener(CellEditorListener l) {
}
@Override
public void removeCellEditorListener(CellEditorListener l) {
}
});
也可以使用默认的自己定制化
文本使用HTML
JLabel label = new JLabel("<html><h1>HelloWorld</h1></html>");
添加Keymap
JTextArea area = new JTextArea();
Keymap keymap = area.getKeymap();
keymap.addActionForKeyStroke(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK),
new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e);
}
});
设置文本域选择文本设置
获取Document对文本进行操作(可以获取,添加移除等)
Document document = area.getDocument();
area.setFont(new Font());
document.addUndoableEditListener(new UndoableEditListener() {
@Override
public void undoableEditHappened(UndoableEditEvent e) {
}
});
document.addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
}
@Override
public void removeUpdate(DocumentEvent e) {
}
@Override
public void changedUpdate(DocumentEvent e) {
}
});
area.setCaret(new DefaultCaret(){
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawString("OK",0,0);
}
});
area.setHighlighter(new DefaultHighlighter(){
@Override
public void paintLayeredHighlights(Graphics g, int p0, int p1, Shape viewBounds, JTextComponent editor, View view) {
super.paintLayeredHighlights(g, p0, p1, viewBounds, editor, view);
}
});
area.write();
area.read();
JPasswordField设置回显字符
JPasswordField password=new JPasswordField();
password.setEchoChar('?');
JEditorPane显示网页(不过效果较差)
JEditorPane editorPane = new JEditorPane();
editorPane.setPage("file:E:\\IDEA\\MyTest3\\src\\main\\resources\\一封家书1.html");
editorPane.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
}
});
JTextPane允许图文混排
JTextPane textPane = new JTextPane();
textPane.insertIcon(new ImageIcon("E:\\IDEA\\MyTest3\\src\\main\\resources\\1.png"));
Toolkit使用
Toolkit toolkit = Toolkit.getDefaultToolkit();
Cursor cursor = toolkit.createCustomCursor(ImageIO.read(new File("E:\\IDEA\\MyTest3\\src\\main\\resources\\2.png")),new Point(), "");
setCursor(cursor);
Image image = toolkit.createImage("");
Dimension screenSize = toolkit.getScreenSize();
Clipboard clipboard = toolkit.getSystemClipboard();
toolkit.beep();
使用系统托盘
if(SystemTray.isSupported()){
SystemTray tray = SystemTray.getSystemTray();
PopupMenu menu = new PopupMenu("TEST");
MenuItem item = new MenuItem("TEST1");
item.addActionListener(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e);
}
});
menu.add(item);
tray.add(new TrayIcon(ImageIO.read(
new File("E:\\IDEA\\MyTest3\\src\\main\\resources\\1.png")),"TEST",menu));
}
其他JFrame特性
setUndecorated(true);
setAlwaysOnTop(true);
setType(Type.UTILITY);
setBackground(new Color(0,0,0,0));
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image,x,y,null);
}
|