柯侧耳倾听者 - 云代码空间
—— 翱翔在Java世界的海洋之上
Swing编程(2学时)
一、实验目的与要求
1. Swing基本组件的用法
2. java7新增的Swing功能
3. 创建进度条
4. 使用JList、JComboBox创建列表框
5. 创建树
6.使用JTable创建表格
二、实验原理
Java中使用AWT和Swing类来完成图形用户界面编程,其中AWT的全称是抽象窗口工具集,他是Sum最早提供的GUI库,这个GUI库提供了一些基本功能但这个GUI库功能有限,所以又提供了Swing库,通1. Swing基本组件的用法
过AWT和Swing提供的的图形界面组件库,java的图形用户界面非常简单,程序依次创建所需的图形组件,并以合适的方式将这些组件组织在一起,就可以开发出非常美观的用户界面。
三、预习与准备
1. Swing基本组件的用法
2. java7新增的Swing功能
3. 创建进度条
4. 使用JList、JComboBox创建列表框
5. 创建树
6.使用JTable创建表格
四、实验内容
1. Swing基本组件的用法
2. java7新增的Swing功能
3. 创建进度条
4. 使用JList、JComboBox创建列表框
5. 创建树
6.使用JTable创建表格
五、实验过程
1. Swing基本组件的用法
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingComponent
{
JFrame f = new JFrame("测试");
Icon okIcon = new ImageIcon("ico/ok.png");
JButton ok = new JButton("确认" , okIcon);
JRadioButton male = new JRadioButton("男" , true);
JRadioButton female = new JRadioButton("女" , false);
ButtonGroup bg = new ButtonGroup();
JCheckBox married = new JCheckBox("是否已婚?" , false);
String[] colors = new String[]{"红色" , "绿色" , "蓝色"};
JComboBox<String> colorChooser = new JComboBox<>(colors);
JList<String> colorList = new JList<>(colors);
JTextArea ta = new JTextArea(8, 20);
JTextField name = new JTextField(40);
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("文件");
JMenu edit = new JMenu("编辑");
Icon newIcon = new ImageIcon("ico/new.png");
JMenuItem newItem = new JMenuItem("新建" , newIcon);
Icon saveIcon = new ImageIcon("ico/save.png");
JMenuItem saveItem = new JMenuItem("保存" , saveIcon);
Icon exitIcon = new ImageIcon("ico/exit.png");
JMenuItem exitItem = new JMenuItem("退出" , exitIcon);
JCheckBoxMenuItem autoWrap = new JCheckBoxMenuItem("自动换行");
JMenuItem copyItem = new JMenuItem("复制"
, new ImageIcon("ico/copy.png"));
JMenuItem pasteItem = new JMenuItem("粘贴"
, new ImageIcon("ico/paste.png"));
JMenu format = new JMenu("格式");
JMenuItem commentItem = new JMenuItem("注释");
JMenuItem cancelItem = new JMenuItem("取消注释");
JPopupMenu pop = new JPopupMenu();
ButtonGroup flavorGroup = new ButtonGroup();
JRadioButtonMenuItem metalItem = new JRadioButtonMenuItem("Metal风格" , true);
JRadioButtonMenuItem nimbusItem = new JRadioButtonMenuItem("Nimbus风格");
JRadioButtonMenuItem windowsItem = new JRadioButtonMenuItem("Windows风格");
JRadioButtonMenuItem classicItem = new JRadioButtonMenuItem("Windows经典风格");
JRadioButtonMenuItem motifItem = new JRadioButtonMenuItem("Motif风格");
public void init()
{
JPanel bottom = new JPanel();
bottom.add(name);
bottom.add(ok);
f.add(bottom , BorderLayout.SOUTH);
JPanel checkPanel = new JPanel();
checkPanel.add(colorChooser);
bg.add(male);
bg.add(female);
checkPanel.add(male);
checkPanel.add(female);
checkPanel.add(married);
Box topLeft = Box.createVerticalBox();
JScrollPane taJsp = new JScrollPane(ta);
topLeft.add(taJsp);
topLeft.add(checkPanel);
Box top = Box.createHorizontalBox();
top.add(topLeft);
top.add(colorList);
f.add(top);
newItem.setAccelerator(KeyStroke.getKeyStroke('N'
, InputEvent.CTRL_MASK));
newItem.addActionListener(e -> ta.append("用户单击了“新建”菜单\n"));
file.add(newItem);
file.add(saveItem);
file.add(exitItem);
edit.add(autoWrap);
edit.addSeparator();
edit.add(copyItem);
edit.add(pasteItem);
commentItem.setToolTipText("将程序代码注释起来!");
format.add(commentItem);
format.add(cancelItem);
edit.add(new JMenuItem("-"));
edit.add(format);
mb.add(file);
mb.add(edit);
f.setJMenuBar(mb);
flavorGroup.add(metalItem);
flavorGroup.add(nimbusItem);
flavorGroup.add(windowsItem);
flavorGroup.add(classicItem);
flavorGroup.add(motifItem);
pop.add(metalItem);
pop.add(nimbusItem);
pop.add(windowsItem);
pop.add(classicItem);
pop.add(motifItem);
ActionListener flavorListener = e -> {
try
{
switch(e.getActionCommand())
{
case "Metal风格":
changeFlavor(1);
break;
case "Nimbus风格":
changeFlavor(2);
break;
case "Windows风格":
changeFlavor(3);
break;
case "Windows经典风格":
changeFlavor(4);
break;
case "Motif风格":
changeFlavor(5);
break;
}
}
catch (Exception ee)
{
ee.printStackTrace();
}
};
metalItem.addActionListener(flavorListener);
nimbusItem.addActionListener(flavorListener);
windowsItem.addActionListener(flavorListener);
classicItem.addActionListener(flavorListener);
motifItem.addActionListener(flavorListener);
ta.setComponentPopupMenu(pop);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
private void changeFlavor(int flavor)throws Exception
{
switch (flavor)
{
case 1:
UIManager.setLookAndFeel(
"javax.swing.plaf.metal.MetalLookAndFeel");
break;
case 2:
UIManager.setLookAndFeel(
"javax.swing.plaf.nimbus.NimbusLookAndFeel");
break;
case 3:
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
break;
case 4:
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
break;
case 5:
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel");
break;
}
SwingUtilities.updateComponentTreeUI(f.getContentPane());
SwingUtilities.updateComponentTreeUI(mb);
SwingUtilities.updateComponentTreeUI(pop);
}
public static void main(String[] args)
{
new SwingComponent().init();
}
}
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import javax.swing.*;
public class JToolBarTest
{
JFrame jf = new JFrame("测试工具条");
JTextArea jta = new JTextArea(6, 35);
JToolBar jtb = new JToolBar();
JMenuBar jmb = new JMenuBar();
Clipboard clipboard = Toolkit.getDefaultToolkit()
.getSystemClipboard();
Action pasteAction = new AbstractAction("粘贴"
, new ImageIcon("ico/paste.png"))
{
public void actionPerformed(ActionEvent e)
{
if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))
{
try
{
String content = (String)clipboard.getData
(DataFlavor.stringFlavor);
jta.replaceRange(content , jta.getSelectionStart()
, jta.getSelectionEnd());
}
catch (Exception ee)
{
ee.printStackTrace();
}
}
}
};
Action copyAction = new AbstractAction("复制"
, new ImageIcon("ico/copy.png"))
{
public void actionPerformed(ActionEvent e)
{
StringSelection contents = new StringSelection(
jta.getSelectedText());
clipboard.setContents(contents, null);
if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor))
{
pasteAction.setEnabled(true);
}
}
};
public void init()
{
pasteAction.setEnabled(false); // ①
jf.add(new JScrollPane(jta));
JButton copyBn = new JButton(copyAction);
JButton pasteBn = new JButton(pasteAction);
JPanel jp = new JPanel();
jp.add(copyBn);
jp.add(pasteBn);
jf.add(jp , BorderLayout.SOUTH);
jtb.add(copyAction);
jtb.addSeparator();
jtb.add(pasteAction);
edit.add(copyAction);
edit.add(pasteAction);
jmb.add(edit);
jf.setJMenuBar(jmb);
jtb.setMargin(new Insets(20 ,10 , 5 , 30));
jf.add(jtb , BorderLayout.NORTH);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setVisible(true);
}
public static void main(String[] args)
{
new JToolBarTest().init();
}
}
2. java7新增的Swing功能
import java.beans.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
import java.awt.geom.Point2D;
class FirstLayerUI extends LayerUI<JComponent>
{
public void paint(Graphics g, JComponent c)
{
super.paint(g, c);
Graphics2D g2 = (Graphics2D) g.create();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, .5f));
g2.setPaint(new GradientPaint(0 , 0 , Color.RED
, 0 , c.getHeight() , Color.BLUE));
g2.fillRect(0, 0, c.getWidth(), c.getHeight());
g2.dispose();
}
}
class BlurLayerUI extends LayerUI<JComponent>
{
private BufferedImage screenBlurImage;
private BufferedImageOp operation;
public BlurLayerUI()
{
float ninth = 1.0f / 9.0f;
float[] blurKernel = {
ninth, ninth, ninth,
ninth, ninth, ninth,
ninth, ninth, ninth
};
operation = new ConvolveOp(
new Kernel(3, 3, blurKernel),
ConvolveOp.EDGE_NO_OP, null);
}
public void paint(Graphics g, JComponent c)
{
int w = c.getWidth();
int h = c.getHeight();
if (w == 0 || h == 0)
return;
if (screenBlurImage == null
|| screenBlurImage.getWidth() != w
|| screenBlurImage.getHeight() != h)
{
screenBlurImage = new BufferedImage(w
, h , BufferedImage.TYPE_INT_RGB);
}
Graphics2D ig2 = screenBlurImage.createGraphics();
ig2.setClip(g.getClip());
super.paint(ig2, c);
ig2.dispose();
Graphics2D g2 = (Graphics2D)g;
g2.drawImage(screenBlurImage, operation, 0, 0);
}
}
class SpotlightLayerUI extends LayerUI<JComponent>
{
private boolean active;
private int cx, cy;
public void installUI(JComponent c)
{
super.installUI(c);
JLayer layer = (JLayer)c;
layer.setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK
| AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
public void uninstallUI(JComponent c)
{
JLayer layer = (JLayer)c;
layer.setLayerEventMask(0);
super.uninstallUI(c);
}
public void paint(Graphics g, JComponent c)
{
Graphics2D g2 = (Graphics2D)g.create();
super.paint (g2, c);
if (active)
{
Point2D center = new Point2D.Float(cx, cy);
float radius = 72;
float[] dist = {0.0f, 1.0f};
Color[] colors = {Color.YELLOW , Color.BLACK};
RadialGradientPaint p = new RadialGradientPaint(center
, radius , dist , colors);
g2.setPaint(p);
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, .6f));
g2.fillRect(0, 0, c.getWidth(), c.getHeight());
}
g2.dispose();
}
public void processMouseEvent(MouseEvent e, JLayer layer)
{
if (e.getID() == MouseEvent.MOUSE_ENTERED)
active = true;
if (e.getID() == MouseEvent.MOUSE_EXITED)
active = false;
layer.repaint();
}
public void processMouseMotionEvent(MouseEvent e, JLayer layer)
{
Point p = SwingUtilities.convertPoint(
e.getComponent(), e.getPoint(), layer);
cx = p.x;
cy = p.y;
layer.repaint();
}
}
public class JLayerTest
{
public void init()
{
JFrame f = new JFrame("JLayer测试");
JPanel p = new JPanel();
ButtonGroup group = new ButtonGroup();
JRadioButton radioButton;
p.add(radioButton = new JRadioButton("网购购买", true));
group.add(radioButton);
p.add(radioButton = new JRadioButton("书店购买"));
group.add(radioButton);
p.add(radioButton = new JRadioButton("图书馆借阅"));
group.add(radioButton);
p.add(new JCheckBox("疯狂Java讲义"));
p.add(new JCheckBox("疯狂Android讲义"));
p.add(new JCheckBox("疯狂Ajax讲义"));
p.add(new JCheckBox("轻量级Java EE企业应用"));
JButton orderButton = new JButton("投票");
p.add(orderButton);
LayerUI<JComponent> layerUI = new SpotlightLayerUI();
JLayer<JComponent> layer = new JLayer<JComponent>(p, layerUI);
f.add(layer);
f.setSize(300, 170);
f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
f.setVisible (true);
}
public static void main(String[] args)
{
new JLayerTest().init();
}
}
import java.beans.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
class WaitingLayerUI extends LayerUI<JComponent>
{
private boolean isRunning;
private Timer timer;
private int angle;
public void paint(Graphics g, JComponent c)
{
super.paint(g, c);
int w = c.getWidth();
int h = c.getHeight();
if (!isRunning)
return;
Graphics2D g2 = (Graphics2D)g.create();
Composite urComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, .5f));
g2.fillRect(0, 0, w, h);
g2.setComposite(urComposite);
int s = Math.min(w , h) / 5;
int cx = w / 2;
int cy = h / 2;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING
, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke( new BasicStroke(s / 2
, BasicStroke.CAP_ROUND , BasicStroke.JOIN_ROUND));
g2.setPaint(Color.BLUE);
g2.rotate(Math.PI * angle / 180, cx, cy);
for (int i = 0; i < 12; i++)
{
float scale = (11.0f - (float)i) / 11.0f;
g2.drawLine(cx + s, cy, cx + s * 2, cy);
g2.rotate(-Math.PI / 6, cx, cy);
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, scale));
}
g2.dispose();
}
public void start()
{
if (isRunning)
return;
isRunning = true;
timer = new Timer(100, e -> {
if (isRunning)
{
firePropertyChange("crazyitFlag", 0 , 1);
angle += 6;
if (angle >= 360)
angle = 0;
}
});
timer.start();
}
public void stop()
{
isRunning = false;
firePropertyChange("crazyitFlag", 0 , 1);
timer.stop();
}
public void applyPropertyChange(PropertyChangeEvent pce
, JLayer layer)
{
if (pce.getPropertyName().equals("crazyitFlag"))
{
layer.repaint();
}
}
}
public class WaitingJLayerTest
{
public void init()
{
JFrame f = new JFrame("转动的“齿轮”");
JPanel p = new JPanel();
ButtonGroup group = new ButtonGroup();
JRadioButton radioButton;
p.add(radioButton = new JRadioButton("网购购买", true));
group.add(radioButton);
p.add(radioButton = new JRadioButton("书店购买"));
group.add(radioButton);
p.add(radioButton = new JRadioButton("图书馆借阅"));
group.add(radioButton);
p.add(new JCheckBox("疯狂Java讲义"));
p.add(new JCheckBox("疯狂Android讲义"));
p.add(new JCheckBox("疯狂Ajax讲义"));
p.add(new JCheckBox("轻量级Java EE企业应用"));
JButton orderButton = new JButton("投票");
p.add(orderButton);
final WaitingLayerUI layerUI = new WaitingLayerUI();
JLayer<JComponent> layer = new JLayer<JComponent>(p, layerUI);
final Timer stopper = new Timer(4000, ae -> layerUI.stop());
stopper.setRepeats(false);
orderButton.addActionListener(ae -> {
layerUI.start();
if (!stopper.isRunning())
{
stopper.start();
}
});
f.add(layer);
f.setSize(300, 170);
f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
f.setVisible (true);
}
public static void main(String[] args)
{
new WaitingJLayerTest().init();
}
}
3. 创建进度条
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JProgressBarTest
{
JFrame frame = new JFrame("测试进度条");
JProgressBar bar = new JProgressBar(JProgressBar.VERTICAL );
JCheckBox indeterminate = new JCheckBox("不确定进度");
JCheckBox noBorder = new JCheckBox("不绘制边框");
public void init()
{
Box box = new Box(BoxLayout.Y_AXIS);
box.add(indeterminate);
box.add(noBorder);
frame.setLayout(new FlowLayout());
frame.add(box);
frame.add(bar);
bar.setMinimum(0);
bar.setMaximum(100);
bar.setStringPainted(true);
noBorder.addActionListener(event ->
bar.setBorderPainted(!noBorder.isSelected()));
indeterminate.addActionListener(event -> {
bar.setIndeterminate(indeterminate.isSelected());
bar.setStringPainted(!indeterminate.isSelected());
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
for (int i = 0 ; i <= 100 ; i++)
{
bar.setValue(i);
try
{
Thread.sleep(100);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
new JProgressBarTest().init();
}
}
4. 使用JList、JComboBox创建列表框
import java.util.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class ListTest
{
private JFrame mainWin = new JFrame("测试列表框");
String[] books = new String[]
{
"疯狂Java讲义"
, "轻量级Java EE企业应用实战"
, "疯狂Android讲义"
, "疯狂Ajax讲义"
, "经典Java EE企业应用实战"
};
JList<String> bookList = new JList<>(books);
JComboBox<String> bookSelector;
JPanel layoutPanel = new JPanel();
ButtonGroup layoutGroup = new ButtonGroup();
JPanel selectModePanel = new JPanel();
ButtonGroup selectModeGroup = new ButtonGroup();
JTextArea favoriate = new JTextArea(4 , 40);
public void init()
{
bookList.setVisibleRowCount(3);
bookList.setSelectionInterval(2, 4);
addLayoutButton("纵向滚动", JList.VERTICAL);
addLayoutButton("纵向换行", JList.VERTICAL_WRAP);
addLayoutButton("横向换行", JList.HORIZONTAL_WRAP);
addSelectModelButton("无限制", ListSelectionModel
.MULTIPLE_INTERVAL_SELECTION);
addSelectModelButton("单选", ListSelectionModel
.SINGLE_SELECTION);
addSelectModelButton("单范围", ListSelectionModel
.SINGLE_INTERVAL_SELECTION);
Box listBox = new Box(BoxLayout.Y_AXIS);
listBox.add(new JScrollPane(bookList));
listBox.add(layoutPanel);
listBox.add(selectModePanel);
bookList.addListSelectionListener(e -> {
List<String> books = bookList.getSelectedValuesList();
favoriate.setText("");
for (String book : books )
{
favoriate.append(book + "\n");
}
});
Vector<String> bookCollection = new Vector<>();
bookCollection.add("疯狂Java讲义");
bookCollection.add("轻量级Java EE企业应用实战");
bookCollection.add("疯狂Android讲义");
bookCollection.add("疯狂Ajax讲义");
bookCollection.add("经典Java EE企业应用实战");
bookSelector = new JComboBox<>(bookCollection);
bookSelector.addItemListener(e -> {
Object book = bookSelector.getSelectedItem();
favoriate.setText(book.toString());
});
bookSelector.setEditable(true);
bookSelector.setMaximumRowCount(4);
JPanel p = new JPanel();
p.add(bookSelector);
Box box = new Box(BoxLayout.X_AXIS);
box.add(listBox);
box.add(p);
mainWin.add(box);
JPanel favoriatePanel = new JPanel();
favoriatePanel.setLayout(new BorderLayout());
favoriatePanel.add(new JScrollPane(favoriate));
favoriatePanel.add(new JLabel("您喜欢的图书:")
, BorderLayout.NORTH);
mainWin.add(favoriatePanel , BorderLayout.SOUTH);
mainWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWin.pack();
mainWin.setVisible(true);
}
private void addLayoutButton(String label, final int orientation)
{
layoutPanel.setBorder(new TitledBorder(new EtchedBorder()
, "确定选项布局"));
JRadioButton button = new JRadioButton(label);
layoutPanel.add(button);
if (layoutGroup.getButtonCount() == 0)
button.setSelected(true);
layoutGroup.add(button);
button.addActionListener(event ->
bookList.setLayoutOrientation(orientation));
}
private void addSelectModelButton(String label, final int selectModel)
{
selectModePanel.setBorder(new TitledBorder(new EtchedBorder()
, "确定选择模式"));
JRadioButton button = new JRadioButton(label);
selectModePanel.add(button);
if(selectModeGroup.getButtonCount() == 0)
button.setSelected(true);
selectModeGroup.add(button);
button.addActionListener(event ->
bookList.setSelectionMode(selectModel));
}
public static void main(String[] args)
{
new ListTest().init();
}
}
5. 创建树
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class EditJTree
{
JFrame jf;
JTree tree;
DefaultTreeModel model;
DefaultMutableTreeNode root = new DefaultMutableTreeNode("中国");
DefaultMutableTreeNode guangdong = new DefaultMutableTreeNode("广东");
DefaultMutableTreeNode guangxi = new DefaultMutableTreeNode("广西");
DefaultMutableTreeNode foshan = new DefaultMutableTreeNode("佛山");
DefaultMutableTreeNode shantou = new DefaultMutableTreeNode("汕头");
DefaultMutableTreeNode guilin = new DefaultMutableTreeNode("桂林");
DefaultMutableTreeNode nanning = new DefaultMutableTreeNode("南宁");
TreePath movePath;
JButton addSiblingButton = new JButton("添加兄弟节点");
JButton addChildButton = new JButton("添加子节点");
JButton deleteButton = new JButton("删除节点");
JButton editButton = new JButton("编辑当前节点");
public void init()
{
guangdong.add(foshan);
guangdong.add(shantou);
guangxi.add(guilin);
guangxi.add(nanning);
root.add(guangdong);
root.add(guangxi);
jf = new JFrame("可编辑节点的树");
tree = new JTree(root);
model = (DefaultTreeModel)tree.getModel();
tree.setEditable(true);
MouseListener ml = new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
TreePath tp = tree.getPathForLocation(
e.getX() , e.getY());
if (tp != null)
{
movePath = tp;
}
}
public void mouseReleased(MouseEvent e)
{
TreePath tp = tree.getPathForLocation(
e.getX(), e.getY());
if (tp != null && movePath != null)
{
if (movePath.isDescendant(tp) && movePath != tp)
{
JOptionPane.showMessageDialog(jf,
"目标节点是被移动节点的子节点,无法移动!","非法操作", JOptionPane.ERROR_MESSAGE );
return;
}
else if (movePath != tp)
{
((DefaultMutableTreeNode)tp.getLastPathComponent())
.add((DefaultMutableTreeNode)movePath
.getLastPathComponent());
movePath = null;
tree.updateUI();
}
}
}
};
tree.addMouseListener(ml);
JPanel panel = new JPanel();
addSiblingButton.addActionListener(event -> {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (selectedNode == null) return;
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)
selectedNode.getParent();
if (parent == null) return;
DefaultMutableTreeNode newNode = new
DefaultMutableTreeNode("新节点");
int selectedIndex = parent.getIndex(selectedNode);
model.insertNodeInto(newNode, parent, selectedIndex + 1);
TreeNode[] nodes = model.getPathToRoot(newNode);
TreePath path = new TreePath(nodes);
tree.scrollPathToVisible(path);
});
panel.add(addSiblingButton);
addChildButton.addActionListener(event -> {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (selectedNode == null) return;
DefaultMutableTreeNode newNode = new
DefaultMutableTreeNode("新节点");
selectedNode.add(newNode);
TreeNode[] nodes = model.getPathToRoot(newNode);
TreePath path = new TreePath(nodes);
tree.scrollPathToVisible(path);
tree.updateUI();
});
panel.add(addChildButton);
deleteButton.addActionListener(event -> {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)
tree.getLastSelectedPathComponent();
if (selectedNode != null && selectedNode.getParent() != null)
{
model.removeNodeFromParent(selectedNode);
}
});
panel.add(deleteButton);
editButton.addActionListener(event -> {
TreePath selectedPath = tree.getSelectionPath();
if (selectedPath != null)
{
tree.startEditingAtPath(selectedPath);
}
});
panel.add(editButton);
jf.add(new JScrollPane(tree));
jf.add(panel , BorderLayout.SOUTH);
jf.pack();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
public static void main(String[] args)
{
new EditJTree().init();
}
}
6. 使用JTable创建表格
import javax.swing.*;
public class SimpleTable
{
JFrame jf = new JFrame("简单表格");
JTable table;
Object[][] tableData =
{
new Object[]{"李清照" , 29 , "女"},
new Object[]{"苏格拉底", 56 , "男"},
new Object[]{"李白", 35 , "男"},
new Object[]{"弄玉", 18 , "女"},
new Object[]{"虎头" , 2 , "男"}
};
Object[] columnTitle = {"姓名" , "年龄" , "性别"};
public void init()
{
table = new JTable(tableData , columnTitle);
jf.add(new JScrollPane(table));
jf.pack();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
public static void main(String[] args)
{
new SimpleTable().init();
}
}
六、实验效果
1. Swing基本组件的用法
2. java7新增的Swing功能
3. 创建进度条
4. 使用JList、JComboBox创建列表框
5. 创建树
6.使用JTable创建表格
七、实验总结与体会
通过这次课的学习,初步掌握了java中Swing的基本用法和一些常用的方法,也发现了自身的一些问题,比如不注重细节,导致程序无法运行,同时也发现要与同学进行交流与合作,及时发现问题并解决问题,也使自己了解到自身的不足,所以在今后的学习中,要更加认真学习,并多与同学和老师交流,这样能够更好的学好Java,同时我们要多敲代码,只有这样,我们才能熟悉代码,做到熟能生巧,才能更好的学好java,敲好java代码。