Swing代码

更新时间:2024-05-10 00:34:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

例 6-1 GetContentPaneDemo.java

import java.awt.*; import javax.swing.*;

public class GetContentPaneDemo { public static void main(String[] args) { JFrame f = new JFrame(\ Container c = f.getContentPane(); // JFrame组件获取容器Content Pane

c.setLayout(new BorderLayout());

JButton btn = new JButton(\c.add(btn, BorderLayout.NORTH);

// 组件添加到容器Content Pane上,而非直接加到JFrame组件上

f.setVisible(true); f.setSize(200,100); f.validate(); } }

例 6-2 NewJFrame.java

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class NewJFrame extends JFrame implements ActionListener { JButton btn = new JButton(\ public NewJFrame() { Container c = this.getContentPane(); c.add(btn); this.setTitle(\ this.pack(); this.setVisible(true); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); btn.addActionListener(this); }// end method NewJFrame public void actionPerformed(ActionEvent e) { JFrame newFrame = new JFrame(\ newFrame.setVisible(true); newFrame.setSize(200, 100); } public static void main(String[] args) {

new NewJFrame(); }

}// end class NewJFrame

例 6-2 修改版 NewJFrame2.java

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class NewJFrame2 extends JFrame implements ActionListener { JButton btn = new JButton(\ public NewJFrame2() { Container c = this.getContentPane(); c.add(btn); this.setTitle(\ this.pack(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); btn.addActionListener(this); }// end method NewJFrame2 public void actionPerformed(ActionEvent e) { JFrame newFrame = new JFrame(\ newFrame.setVisible(true); newFrame.setSize(200, 100); newFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public static void main(String[] args) { new NewJFrame2(); }

}// end class NewJFrame2

例6-3 JDialogDemo.java

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class JDialogDemo extends JFrame implements ActionListener { JButton bQuery = new JButton(\查询\ JButton bQuit = new JButton(\退出\

public JDialogDemo() { Container c = this.getContentPane(); bQuery.addActionListener(this);

bQuit.addActionListener(this); this.setTitle(\成绩查询系统\

this.setSize(240, 60); c.setLayout(new GridLayout(1, 2, 20, 10)); c.add(bQuery); c.add(bQuit); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.validate(); this.setVisible(true); }

public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals(\查询\

new LoginDialog(this); } else if (cmd.equals(\退出\

System.exit(0); } } public static void main(String[] args) { new JDialogDemo(); } }

//定制的登陆对话框类

class LoginDialog extends JDialog { JLabel bj = new JLabel(\班级\ JLabel xm = new JLabel(\姓名\ JLabel xh = new JLabel(\学号\

JTextField txtBj = new JTextField(30); JTextField txtXm = new JTextField(30); JTextField txtXh = new JTextField(30); JButton confirm = new JButton(\确定\JButton cancel = new JButton(\取消\public LoginDialog(Frame owner) { Container c = this.getContentPane(); c.setLayout(new GridLayout(4, 2, 5, 5)); c.add(bj); c.add(txtBj); c.add(xm); c.add(txtXm); c.add(xh); c.add(txtXh); c.add(confirm); c.add(cancel);

this.setTitle(\查询对话框\

this.setSize(160, 160); this.validate(); this.setVisible(true); } }

例 6-4 JOptionPaneDemo.java

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class JOptionPaneDemo extends JFrame implements ActionListener { JButton msgDlg = new JButton(\消息对话框\ JButton inDlg1 = new JButton(\输入对话框1\ JButton inDlg2 = new JButton(\输入对话框2\ JButton cnfDlg = new JButton(\确认对话框\ JButton optDlg = new JButton(\选项对话框\

public JOptionPaneDemo() { Container c = this.getContentPane(); c.setLayout(new GridLayout(5, 1, 0, 10)); c.add(msgDlg); c.add(inDlg1); c.add(inDlg2); c.add(cnfDlg); c.add(optDlg); this.setTitle(\ this.setSize(200, 240); this.setLocation(300, 300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.validate(); this.setVisible(true); msgDlg.addActionListener(this); inDlg1.addActionListener(this); inDlg2.addActionListener(this); cnfDlg.addActionListener(this); optDlg.addActionListener(this); }

public static void main(String[] args) { new JOptionPaneDemo(); }

// 事件处理

public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(\消息对话框\

JOptionPane.showMessageDialog(this, \消息对话框常用于显示文本信息\ \消息对话框\

JOptionPane.INFORMATION_MESSAGE); } else if (e.getActionCommand().equals(\输入对话框1\ JOptionPane.showInputDialog(this, \请输入你的姓名:\ \输入文本的对话框\ JOptionPane.INFORMATION_MESSAGE); } else if (e.getActionCommand().equals(\输入对话框2\ String[] sex = { \男\女\ JOptionPane.showInputDialog(this, \你的性别?\ \进行选择的输入对话框\ JOptionPane.QUESTION_MESSAGE, null, sex, sex[0]);

} else if (e.getActionCommand().equals(\确认对话框\ JOptionPane.showConfirmDialog(this, \今天心情好吗?\ \确认对话框\ JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, new ImageIcon(\

} else if (e.getActionCommand().equals(\选项对话框\ String[] option = { \好\不好\取消\ JOptionPane.showOptionDialog(this, \今天心情好吗?\ \选项对话框\

JOptionPane.YES_NO_CANCEL_OPTION,

JOptionPane.INFORMATION_MESSAGE, new ImageIcon(\ } } }

例 6-5 JAppletDemo.java

import java.awt.*; import javax.swing.*;

public class JAppletDemo extends JApplet { JLabel msg = new JLabel(\这是JApplet示例...\ JTextField msg2 = new JTextField(\中可以使用Swing组件\

public void init() { Container c = getContentPane(); c.setLayout(new GridLayout(2, 1)); add(msg); add(msg2); }

}

例 6-6 JPanelDemo.java

import java.awt.*; import javax.swing.*;

public class JPanelDemo extends JFrame { JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(new GridLayout(2, 2)); JLabel msg1 = new JLabel(\这是面板P1,只包含本JLabel\ JLabel msg2 = new JLabel(\这是面板P2,其中包含了面板P3,P3中含4个按钮\ }

JButton[] btn = new JButton[4]; public JPanelDemo() { Container c = this.getContentPane(); for (int i = 0; i < 4; i++) { btn[i] = new JButton(\ } p1.add(msg1); for (int i = 0; i < 4; i++) { p3.add(btn[i]); } p2.add(msg2); p2.add(p3); c.setLayout(null); p1.setBounds(0, 0, 320, 30); p2.setBounds(0, 30, 320, 120); msg2.setBounds(0, 30, 320, 30); p3.setBounds(0, 60, 320, 90); c.add(p1); c.add(p2); this.setTitle(\ this.setSize(320, 150); this.setLocation(300, 300); this.validate(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

public static void main(String[] args) { new JPanelDemo(); }

例6-7 JScrollPaneDemo.java

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class JScrollPaneDemo extends JFrame implements ActionListener { JLabel img = new JLabel(new ImageIcon(\ JButton b1 = new JButton(\显示垂直滚动条\ JButton b2 = new JButton(\不显示垂直滚动条\ JButton b3 = new JButton(\必要时显示垂直滚动条\

JScrollPane sp = new JScrollPane(img);

JPanel p = new JPanel(new GridLayout(1, 3)); public JScrollPaneDemo() { Container c = this.getContentPane(); c.add(sp, \ c.add(p, \ p.add(b1); p.add(b2); p.add(b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); this.setTitle(\ this.setSize(500, 300); this.setLocation(300, 300); this.validate(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

public static void main(String[] args) { new JScrollPaneDemo(); }

public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); if (s.equals(\显示垂直滚动条\

sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); } else if (s.equals(\不显示垂直滚动条\

sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); } else if (s.equals(\必要时显示垂直滚动条\

sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); } }

}

例6-8 JSplitPaneDemo.java

import java.awt.*; import javax.swing.*;

public class JSplitPaneDemo extends JFrame { JLabel left = new JLabel(\这是左侧显示区!\ JLabel right = new JLabel(\这是右侧显示区!\

JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false, left,right); public JSplitPaneDemo() { Container c = this.getContentPane(); c.add(sp); this.setTitle(\ this.setSize(300, 200); this.setLocation(300, 300); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new JSplitPaneDemo(); } }

例6-9 JInternalFrameDemo.java

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class JInternalFrameDemo extends JFrame implements ActionListener { JDesktopPane dPane = new JDesktopPane(); JButton btn = new JButton(\点击创建一个内部窗口\

public JInternalFrameDemo() { Container c = this.getContentPane(); c.add(dPane, \ c.add(btn, \ btn.addActionListener(this); this.setTitle(\ this.setSize(300, 300); this.setLocation(300, 300); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main(String[] args) { new JInternalFrameDemo(); }

public void actionPerformed(ActionEvent e) { JInternalFrame inf = new JInternalFrame(\内部窗口\

inf.setLocation(20, 20); inf.setSize(260, 200); inf.setVisible(true);

JLabel msg = new JLabel(\这是内部面板中的JLabel\

Container c = inf.getContentPane(); c.add(msg); dPane.add(inf); } }

例6-10 JLabelWithIcon.java

import java.awt.*; import javax.swing.*;

public class JLabelWithIcon extends JFrame { Icon icon = new ImageIcon(\ JLabel lb1 = new JLabel(\文本标签\ }

JLabel lb2 = new JLabel(icon);

JLabel lb3 = new JLabel(\文本内容\public JLabelWithIcon() { Container c = this.getContentPane(); c.setLayout(new GridLayout(1, 3)); c.add(lb1); c.add(lb2); c.add(lb3); lb3.setVerticalTextPosition(JLabel.BOTTOM); lb3.setHorizontalTextPosition(JLabel.CENTER); this.setTitle(\ this.setSize(400, 200); this.setLocation(300, 300); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

public static void main(String[] args) { new JLabelWithIcon(); }

例6-11 CommonComponent.java

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

import javax.swing.event.*;

public class CommonComponent extends JFrame { JLabel msg = new JLabel(\ JLabel lName = new JLabel(\ JLabel lSex = new JLabel(\ JLabel lWeight = new JLabel(\ JLabel lInterest = new JLabel(\ JLabel lCity = new JLabel(\ JButton bSubmit = new JButton(\ JButton bReset = new JButton(\ JTextField tName = new JTextField(100); JRadioButton male = new JRadioButton(\ JRadioButton female = new JRadioButton(\ ButtonGroup bgSex = new ButtonGroup(); JPasswordField tWeight = new JPasswordField(100); JCheckBox read = new JCheckBox(\ JCheckBox tour = new JCheckBox(\ JCheckBox sport = new JCheckBox(\ JCheckBox game = new JCheckBox(\ String[] sCity = { \ JComboBox goCity = new JComboBox(sCity); BtnListener blsn = new BtnListener(this); TxtListener tlsn = new TxtListener(this); String name, sex, weight, city; String[] interest = new String[4]; public CommonComponent() { Container c = this.getContentPane(); c.setLayout(null); JPanel p = new JPanel(new GridLayout(1, 1)); JPanel p1 = new JPanel(new GridLayout(5, 2, 10, 10)); JPanel p2 = new JPanel(new GridLayout(1, 2)); JPanel p3 = new JPanel(new GridLayout(2, 2)); JPanel p4 = new JPanel(); p.setBounds(0, 0, 300, 40); p1.setBounds(0, 40, 300, 180); p4.setBounds(0, 220, 300, 50); c.add(p); c.add(p1);

c.add(p4); p.add(msg); p1.add(lName); p1.add(tName); p1.add(lSex); p1.add(p2);

bgSex.add(male); bgSex.add(female); p2.add(male); p2.add(female); p1.add(lWeight); p1.add(tWeight); p1.add(lInterest); p1.add(p3); p3.add(read); p3.add(tour); p3.add(sport); p3.add(game); p1.add(lCity); p1.add(goCity);

p4.setLayout(new BoxLayout(p4, BoxLayout.X_AXIS)); p4.add(Box.createHorizontalStrut(20)); p4.add(bSubmit);

p4.add(Box.createHorizontalStrut(30)); p4.add(bReset);

bSubmit.setMaximumSize(new Dimension(120, 32)); bReset.setMaximumSize(new Dimension(120, 32)); bSubmit.setActionCommand(\bReset.setActionCommand(\// 为按钮和文本框注册监听器

bSubmit.addActionListener(blsn); bReset.addActionListener(blsn); tName.addCaretListener(tlsn); tWeight.addCaretListener(tlsn); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle(\ this.setSize(320, 300); this.setLocation(200, 200); this.setVisible(true); } public static void main(String[] args) { new CommonComponent(); }

}// end class CommonComponent

// BtnListener监听器类,用于处理点击按钮的事件

class BtnListener implements ActionListener { CommonComponent ob; public BtnListener(CommonComponent ob) { this.ob = ob; } public void actionPerformed(ActionEvent e) { String src = e.getActionCommand(); if (src.equals(\ JFrame outFrame = new JFrame(\ Container c = outFrame.getContentPane(); String output = \ if (ob.female.isSelected()) { ob.sex = \ } if (ob.male.isSelected()) { ob.sex = \ } int i = 0; if (ob.read.isSelected()) { ob.interest[i++] = \ } if (ob.tour.isSelected()) { ob.interest[i++] = \ } if (ob.sport.isSelected()) { ob.interest[i++] = \ } if (ob.game.isSelected()) { ob.interest[i++] = \ } ob.city = (String) (ob.goCity.getSelectedItem()); output += \ output += \ output += \ output += \ for (int j = 0; j < i; j++) { output += ob.interest[j]; } output += \ JTextArea ta = new JTextArea(output, 30, 100); ta.setEditable(false); c.add(ta);

outFrame.setSize(300, 200); outFrame.setVisible(true); outFrame.setLocation(300, 300); } else if (src.equals(\ ob.tName.setText(\ ob.tWeight.setText(\ ob.male.setSelected(true); ob.read.setSelected(false); ob.tour.setSelected(false); ob.sport.setSelected(false); ob.game.setSelected(false); ob.goCity.setSelectedIndex(0); } }

}// end class BtnListener

// TxtListener监听器类,用于处理文本框和密文框上的事件 class TxtListener implements CaretListener { CommonComponent ob; public TxtListener(CommonComponent ob) { this.ob = ob; } public void caretUpdate(CaretEvent e) { Object src = e.getSource(); if (src == ob.tName) { ob.name = ob.tName.getText(); } else if (src == ob.tWeight) { ob.weight = new String(ob.tWeight.getPassword()); } }

}// end class TxtListener

例6-12 JTextAreaDemo.java

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class JTextAreaDemo extends JFrame implements ActionListener { JTextArea ta = new JTextArea(5, 10); JButton bCut = new JButton(\ JButton bCopy = new JButton(\ JButton bPaste = new JButton(\ public JTextAreaDemo() { Container c = this.getContentPane();

c.setLayout(new BorderLayout()); JScrollPane sp = new JScrollPane(ta); JPanel p = new JPanel(); p.setLayout(new GridLayout(1, 3, 20, 0)); p.add(bCut); p.add(bCopy); p.add(bPaste); bCut.addActionListener(this); bCopy.addActionListener(this); bPaste.addActionListener(this); c.add(sp, \ c.add(p, \ this.setTitle(\ this.pack(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String args[]) { new JTextAreaDemo(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == bCut) { ta.cut(); } if (e.getSource() == bCopy) { ta.copy(); } if (e.getSource() == bPaste) { ta.paste(); } } }

例6-13 JTextPaneDemo.java import javax.swing.*; import javax.swing.text.*; import java.awt.event.*; import java.awt.*;

public class JTextPaneDemo { JTextPane tp = new JTextPane();

public JTextPaneDemo() { tp.setBackground(Color.white); tp.setEditable(false); }

public void setBlue_Bold(String str) { SimpleAttributeSet sas = new SimpleAttributeSet(); StyleConstants.setForeground(sas, Color.blue); StyleConstants.setBold(sas, true); StyleConstants.setFontSize(sas, 18); insert(str, sas); }

public void setRed_Italic(String str) { SimpleAttributeSet sas = new SimpleAttributeSet(); StyleConstants.setForeground(sas, Color.red); StyleConstants.setItalic(sas, true); StyleConstants.setFontSize(sas, 18); insert(str, sas); }

public void setCyan_UnderLine(String str) { SimpleAttributeSet sas = new SimpleAttributeSet(); StyleConstants.setForeground(sas, Color.cyan); StyleConstants.setUnderline(sas, true); StyleConstants.setFontSize(sas, 18); insert(str, sas); }

public void insert(String str, AttributeSet as) { Document docs = tp.getDocument(); str += \ try { docs.insertString(docs.getLength(), str, as); } catch (BadLocationException e) { e.printStackTrace(); } }

public Component getComponent() { return tp; }

public static void main(String[] args) { JTextPaneDemo tPane = new JTextPaneDemo(); tPane.setBlue_Bold(\ tPane.setRed_Italic(\ tPane.setCyan_UnderLine(\ JFrame f = new JFrame(\ f.getContentPane().add(tPane.getComponent());

showImg.setIcon(imgs[counter]); counter++; showImg.repaint(); } } }

例6-16 TimerAndJProgressBar.java

import javax.swing.*; import java.awt.*;

import java.awt.event.*; import javax.swing.event.*;

public class TimerAndJProgressBar extends JFrame implements ActionListener, ChangeListener { JPanel p = new JPanel(); JLabel msg = new JLabel(\ JProgressBar pgbar = new JProgressBar(); Timer timer = new Timer(100, this); JButton start = new JButton(\开始\ JButton stop = new JButton(\停止\

public TimerAndJProgressBar() { Container c = this.getContentPane(); Box hbox = Box.createHorizontalBox(); p.add(hbox); hbox.add(start); hbox.add(hbox.createHorizontalStrut(20)); hbox.add(stop); c.add(p, BorderLayout.NORTH); c.add(pgbar, BorderLayout.CENTER); c.add(msg, BorderLayout.SOUTH); pgbar.setStringPainted(true); pgbar.setString(\ pgbar.setPreferredSize(new Dimension(200, 30)); pgbar.setBorderPainted(false); pgbar.setBackground(Color.white); pgbar.setForeground(Color.black); pgbar.addChangeListener(this); start.addActionListener(this); stop.addActionListener(this); this.setTitle(\ this.setBounds(200, 200, 300, 140); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true);

}

public static void main(String[] args) { new TimerAndJProgressBar(); }

public void actionPerformed(ActionEvent e) { if (e.getSource() == start) { timer.start(); } else if (e.getSource() == stop) { timer.stop(); } else if (e.getSource() == timer) { int value = pgbar.getValue(); if (value < 100) { value++; pgbar.setValue(value); } else { timer.stop(); pgbar.setValue(0); } } }

public void stateChanged(ChangeEvent e) { int value = pgbar.getValue();

if (e.getSource() == pgbar) { msg.setText(\目前已完成:\

}

} }

例6-17 JFileChooserDemo.java

import java.awt.*;

import java.awt.event.*; import javax.swing.*; import java.io.*;

public class JFileChooserDemo extends JFrame implements ActionListener { JLabel msg = new JLabel(\ JTextArea ta = new JTextArea(); JFileChooser fc = new JFileChooser(); JButton openf = new JButton(\ JButton savef = new JButton(\ JPanel p = new JPanel(); JScrollPane sp = new JScrollPane(ta); public JFileChooserDemo() {

Container c = this.getContentPane(); sp.setPreferredSize(new Dimension(350, 300)); openf.addActionListener(this); savef.addActionListener(this); p.add(openf); p.add(savef); c.add(msg, \ c.add(sp, \ c.add(p, \ this.setTitle(\ this.setBounds(200, 200, 300, 200); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

public static void main(String[] args) { new JFileChooserDemo(); }

public void actionPerformed(ActionEvent e) { File file = null; int result; FileInputStream fileInStream = null; FileOutputStream fileOutStream = null; int readbyte; if (e.getSource() == openf) { fc.setApproveButtonText(\确定\ fc.setDialogTitle(\打开文件\

result = fc.showOpenDialog(this); ta.setText(\

if (result == JFileChooser.APPROVE_OPTION) { file = fc.getSelectedFile(); msg.setText(\您选择打开的文件名称为:\} else if (result == JFileChooser.CANCEL_OPTION) { msg.setText(\您没有选择任何文件\}

if (file != null) { try { fileInStream = new FileInputStream(file); } catch (FileNotFoundException fe) { msg.setText(\ return; }

try { while ((readbyte = fileInStream.read()) != -1) {

ta.append(String.valueOf((char) readbyte)); }

} catch (IOException ioe) { msg.setText(\读取文件错误\

} finally {

try { if (fileInStream != null) fileInStream.close(); } catch (IOException ioe2) { } } } }

if (e.getSource() == savef) { result = fc.showSaveDialog(this); file = null; String fileName; if (result == JFileChooser.APPROVE_OPTION) { file = fc.getSelectedFile(); msg.setText(\您选择存储的文件名称为:\

} else if (result == JFileChooser.CANCEL_OPTION) { msg.setText(\您没有选择任何文件\}

if (file != null) { try { fileOutStream = new FileOutputStream(file); } catch (FileNotFoundException fe) { msg.setText(\ return; }

String content = ta.getText();

try { fileOutStream.write(content.getBytes()); } catch (IOException ioe) { msg.setText(\写入文件错误\} finally { try { if (fileOutStream != null) fileOutStream.close(); } catch (IOException ioe2) { }

} } } } }

例6-18 JTreeDemo.java

import java.awt.*; import javax.swing.*; import javax.swing.tree.*; import javax.swing.event.*; import java.io.*;

public class JTreeDemo extends JFrame implements TreeSelectionListener { JTextPane tp = new JTextPane(); public JTreeDemo() { Container c = this.getContentPane(); DefaultMutableTreeNode root = new DefaultMutableTreeNode(\例题代码浏览器\

DefaultMutableTreeNode node = new DefaultMutableTreeNode(\ root.add(node); node = new DefaultMutableTreeNode(\ root.add(node); node = new DefaultMutableTreeNode(\ root.add(node); JTree tree = new JTree(root); JScrollPane spTree = new JScrollPane(tree); JScrollPane spShow = new JScrollPane(tp); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, spTree, spShow); tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addTreeSelectionListener(this); c.add(splitPane); this.setTitle(\ this.setBounds(200, 100, 700, 400); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }

public static void main(String[] args) { new JTreeDemo(); }

public void valueChanged(TreeSelectionEvent e) {

JTree tree = (JTree) e.getSource();

DefaultMutableTreeNode selectionNode = (DefaultMutableTreeNode) tree .getLastSelectedPathComponent(); String nodeName = selectionNode.toString();

if (selectionNode.isLeaf()) { String filepath = \ + System.getProperty(\ try { tp.setPage(filepath); } catch (IOException ex) {

System.out.println(\找不到此文件\

}

} } }

相关知识链接 PaintDemo.java

import java.awt.*; import javax.swing.*;

class MyPanel extends JPanel{ protected void paintComponent(Graphics g){ g.drawString(\组件使用paintComponent 绘制\ } }

public class PaintDemo extends JFrame{ public PaintDemo(String title){ super(title); this.setBounds(200,200,220,100); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MyPanel p = new MyPanel(); this.add(p); this.validate(); } public static void main(String[] args){ new PaintDemo(\ } }

例题 6-1 简单计算器

import java.awt.*;

import java.awt.event.*; import javax.swing.*;

public class SimpleCalculator extends JFrame implements ActionListener { // 声明GUI组件及相关变量

JPanel p, p1, p2; JTextField tResult; JButton btnBK, btnC;

JButton[] btnNumber = new JButton[10];

JButton btnAdd, btnSub, btnMul, btnDiv, btnEqual, btnDot, btnSign; JButton btnSqrt, btnMod, btnReciprocal; boolean canClick; double memd; int memi;

double tempResult, result; short op = 0;

// 构造方法,建立GUI,为组件注册监听器

public SimpleCalculator() { canClick = true; result = 0; tResult = new JTextField(15); tResult.setEditable(false); tResult.setBackground(Color.WHITE); btnBK = new JButton(\ btnC = new JButton(\ for (int i = 0; i < 10; i++) btnNumber[i] = new JButton(Integer.toString(i)); btnAdd = new JButton(\ btnSub = new JButton(\ btnMul = new JButton(\ btnDiv = new JButton(\ btnMod = new JButton(\ btnSqrt = new JButton(\ btnReciprocal = new JButton(\ btnEqual = new JButton(\ btnDot = new JButton(\ btnSign = new JButton(\ Container c = this.getContentPane(); p1 = new JPanel(new FlowLayout(FlowLayout.RIGHT)); p2 = new JPanel(new GridLayout(4, 5, 3, 3)); c.add(tResult, BorderLayout.NORTH);

c.add(p1, BorderLayout.CENTER); c.add(p2, BorderLayout.SOUTH); p1.add(btnBK); p1.add(btnC);

p2.add(btnNumber[7]); p2.add(btnNumber[8]); p2.add(btnNumber[9]); p2.add(btnDiv); p2.add(btnSqrt);

p2.add(btnNumber[4]); p2.add(btnNumber[5]); p2.add(btnNumber[6]); p2.add(btnMul); p2.add(btnMod);

p2.add(btnNumber[1]); p2.add(btnNumber[2]); p2.add(btnNumber[3]); p2.add(btnSub);

p2.add(btnReciprocal); p2.add(btnNumber[0]); p2.add(btnSign); p2.add(btnDot); p2.add(btnAdd); p2.add(btnEqual);

for (int i = 0; i < 10; i++) btnNumber[i].addActionListener(this); btnBK.addActionListener(this); btnC.addActionListener(this); btnAdd.addActionListener(this); btnSub.addActionListener(this); btnMul.addActionListener(this); btnDiv.addActionListener(this); btnMod.addActionListener(this); btnSqrt.addActionListener(this);

btnReciprocal.addActionListener(this); btnEqual.addActionListener(this); btnDot.addActionListener(this); btnSign.addActionListener(this); this.setTitle(\简单计算器\

this.setLocation(200, 200); this.pack();

this.setVisible(true); this.setResizable(false);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

// 实现ActionListener接口,进行事件处理 public void actionPerformed(ActionEvent ae) { Object eSrc = ae.getSource(); // 事件源

for (int i = 0; i < 10; i++) { if (eSrc == btnNumber[i] && canClick == true) tResult.setText(tResult.getText() + Integer.toString(i)); }

if (eSrc == btnDot && canClick == true) { boolean hasDot = false; String s = tResult.getText(); if (s.length() == 0) hasDot = true; for (int i = 0; i < s.length(); i++) if (s.charAt(i) == '.') { hasDot = true; break; } if (hasDot == false) tResult.setText(s + \}

// 四种基本运算

if ((eSrc == btnAdd || eSrc == btnSub || eSrc == btnMul || eSrc == btnDiv) && canClick == true) { // “+” if (eSrc == btnAdd) { tempResult = Double.parseDouble(tResult.getText()); tResult.setText(\ op = 1; } // “-” if (eSrc == btnSub) { tempResult = Double.parseDouble(tResult.getText()); tResult.setText(\ op = 2; } // “*” if (eSrc == btnMul) { tempResult = Double.parseDouble(tResult.getText()); tResult.setText(\ op = 3; } // “/” if (eSrc == btnDiv) {

if (Double.parseDouble(tResult.getText()) == 0) { tResult.setText(\注意:除数不可为0\

canClick = false;

} else tempResult = Double.parseDouble(tResult.getText()); tResult.setText(\ op = 4; }

}// end 基本运算

// “=”

if (eSrc == btnEqual && canClick == true) { if (op == 1) { result = tempResult + Double.parseDouble(tResult.getText()); tResult.setText(Double.toString(result)); } if (op == 2) { result = tempResult - Double.parseDouble(tResult.getText()); tResult.setText(Double.toString(result)); } if (op == 3) { result = tempResult * Double.parseDouble(tResult.getText()); tResult.setText(Double.toString(result)); } if (op == 4) { if (Double.parseDouble(tResult.getText()) == 0) { tResult.setText(\除数不能为零\ canClick = false; } else { result = tempResult / Double.parseDouble(tResult.getText()); tResult.setText(Double.toString(result)); } } tempResult = 0; }

// “%”

if (eSrc == btnMod && canClick == true) { String s = tResult.getText(); boolean hasDot = false; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '.') { hasDot = true; break; } }

if (hasDot == true) { double temp = Double.parseDouble(s); temp = temp / 100.0; tResult.setText(Double.toString(temp)); } else { if (Integer.parseInt(s) % 100 == 0) { int itemp = Integer.parseInt(s); itemp = itemp / 100; tResult.setText(Integer.toString(itemp)); } else { double dtemp = Double.parseDouble(s); dtemp = dtemp / 100.0; tResult.setText(Double.toString(dtemp)); } } } // Sqrt

if (eSrc == btnSqrt && canClick == true) { String s = tResult.getText(); if (s.charAt(0) == '-') { tResult.setText(\注意:负数不可开根号\ canClick = false; } else tResult.setText(Double.toString(Math .sqrt(Double.parseDouble(s)))); }

// 求倒数

if (eSrc == btnReciprocal && canClick == true) { String s = tResult.getText(); if (s.charAt(0) == '0' && s.length() == 1) { tResult.setText(\注意:0不能求倒数\

canClick = false; } else { boolean hasDot = false; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '.') { hasDot = true; break; } } if (hasDot == true) { double dtemp = Double.parseDouble(s); dtemp = 1.0 / dtemp; tResult.setText(Double.toString(dtemp));

} else { int itemp = Integer.parseInt(s); double dtemp = 1.0 / (double) itemp; tResult.setText(Double.toString(dtemp)); } } }

// “+/-”

if (eSrc == btnSign && canClick == true) { boolean isNum = true; String s = tResult.getText(); for (int i = 0; i < s.length(); i++) { if (!(s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == '.' || s.charAt(i) == '-')) { isNum = false; break; } } if (isNum == true) { if (s.charAt(0) == '-') { tResult.setText(\ for (int i = 1; i < s.length(); i++) { char ch = s.charAt(i); tResult.setText(tResult.getText() + ch); } } else tResult.setText(\ } }

// “BackSpace”

if (eSrc == btnBK && canClick == true) { String s = tResult.getText(); tResult.setText(\ for (int i = 0; i < s.length() - 1; i++) { char ch = s.charAt(i); tResult.setText(tResult.getText() + ch); } } // “C”

if (eSrc == btnC) { tempResult = 0; result = 0; tResult.setText(\ canClick = true;

}

}

}//end method actionPerformed

public static void main(String[] args) { new SimpleCalculator(); }

本文来源:https://www.bwwdw.com/article/6p8g.html

Top