Java語言程序設計課程實驗題目
第七次實驗
1. 在IDE中輸入並觀察以下代碼,分析該段程序的作用。
import java.awt.*;
public class TestMenu{
public static void main(String[] args) {
Frame f = new Frame("Menu");
MenuBar mb = new MenuBar();
f.setMenuBar(mb);
Menu m1 = new Menu("File");
Menu m2 = new Menu("Edit");
Menu m3 = new Menu("Help");
// add menu to menubar
mb.add(m1); mb.add(m2); mb.add(m3);
// set menuitem
MenuItem m11 = new MenuItem("New");
MenuItem m12 = new MenuItem("Save");
MenuItem m13 = new MenuItem("Load");
MenuItem m14 = new MenuItem("Quit");
// add menuitem into menu
m1.add(m11); m1.add(m12); m1.add(m13); m1.add(m14);
f.setSize(400,300); f.setVisible(true);
}
}
2. 在IDE中輸入並觀察以下代碼,分析該段程序的作用。
import java.awt.*;
import java.awt.event.*;
public class TestActionEvent {
public static void main(String args[]) {
Frame f = new Frame("Test");
Button b = new Button("Press Me!");
Monitor monitor = new Monitor();
b.addActionListener(monitor);
f.add(b,BorderLayout.CENTER);
f.setSize(300,200);
f.setVisible(true);
}
}
class Monitor implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("a button has been pressed");
}
}
3. 在IDE中輸入並觀察以下代碼,分析該段程序的作用。
import java.awt.*;
import java.awt.event.*;
public class TestMultiListener implements MouseMotionListener,MouseListener {
Frame f = new Frame("Multi Listener");
TextField tf = new TextField(30);
public TestMultiListener(){
f.add(new Label("Press mouse & drag"), "North");
f.add(tf, "South"); f.setBackground(new Color(120,175,175));
f.addMouseMotionListener(this);
f.addMouseListener(this); f.setSize(300, 200); f.setVisible(true);
}
public static void main(String args[]) {
TestMultiListener t = new TestMultiListener();
}
public void mouseDragged(MouseEvent e) {
String s = "Position: " + e.getX() + "," + e.getY();
tf.setText(s);
}
public void mouseEntered(MouseEvent e) {
String s = "Entering the window";
tf.setText(s);
}
public void mouseExited(MouseEvent e) {
String s = "Leaving the window";
tf.setText(s);
}
public void mouseMoved(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseClicked(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
}
4. 編寫程序。
構建如圖所示的應用程序,通過三個滑動條能夠動態調節應用程序的背景顏色。
提示:編寫程序過程中將涉及使用JSlider類,以及其中的屬性PaintTicks, MajorTickSpacing,MinorTickSpacing。
5. 編寫程序。
構建如圖所示的應用程序。實現以下需求:
(1)構建相同的用戶界面(佈局、排布、名稱、位置、比例關係);
(2)菜單、選擇框、按鈕均要有事件處理響應。在點擊相應菜單、選擇框、按鈕後,在計算機的計算顯示區域(紅色框線標記的區域)中顯示對應的事件內容,下一次點擊操作顯示的內容會將上一次的點擊操作顯示的內容替換。例如,點擊數字鍵“1”,則在計算顯示區中顯示“數字鍵1被點擊”(中英文即可,但要求必須單獨對應表示與每個控件特定的事件內容)。
(3)當點擊按鍵“C”時,則清空顯示區域中的內容,僅顯示“0”。
(4)窗體在拉伸情況下,各控件之間的相對位置關係要保持穩定,且顯示尺寸隨窗體尺寸相應變化。
1、
package org.cust.test7;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestMenu {
public static void main(String[] args) {
Frame f = new Frame("Menu");
MenuBar mb = new MenuBar();
f.setMenuBar(mb);
Menu m1 = new Menu("File");
Menu m2 = new Menu("Edit");
Menu m3 = new Menu("Help");
// add menu to menubar
mb.add(m1);
mb.add(m2);
mb.add(m3);
// set menuitem
MenuItem m11 = new MenuItem("New");
MenuItem m12 = new MenuItem("Save");
MenuItem m13 = new MenuItem("Load");
MenuItem m14 = new MenuItem("Quit");
// add menuitem into menu
m1.add(m11);
m1.add(m12);
m1.add(m13);
m1.add(m14);
f.setSize(400, 300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Window window = (Window) e.getComponent();
window.dispose();
}
});
//MenuBar是菜單欄,Menu是菜單,MenuItem是菜單項
}
}
2、
package org.cust.test7;
import java.awt.*;
import java.awt.event.*;
public class TestActionEvent {
public static void main(String args[]) {
Frame f = new Frame("Test");
Button b = new Button("Press Me!");
Monitor monitor = new Monitor();
b.addActionListener(monitor);
f.add(b, BorderLayout.CENTER);
f.setSize(300, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Window window = (Window) e.getComponent();
window.dispose();
}
});
}
}
class Monitor implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("a button has been pressed");
}
// 一個居中的按鈕,添加了監聽
// 點擊了就會控制檯輸出對應語句
}
3、
package org.cust.test7;
import java.awt.*;
import java.awt.event.*;
public class TestMultiListener implements MouseMotionListener, MouseListener {
Frame f = new Frame("Multi Listener");
TextField tf = new TextField(30);
public TestMultiListener() {
f.add(new Label("Press mouse & drag"), "North");
f.add(tf, "South");
f.setBackground(new Color(120, 175, 175));
f.addMouseMotionListener(this);
f.addMouseListener(this);
f.setSize(300, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Window window = (Window) e.getComponent();
window.dispose();
}
});
}
public static void main(String args[]) {
TestMultiListener t = new TestMultiListener();
}
public void mouseDragged(MouseEvent e) {
String s = "Position: " + e.getX() + "," + e.getY();
tf.setText(s);
}
public void mouseEntered(MouseEvent e) {
String s = "Entering the window";
tf.setText(s);
}
public void mouseExited(MouseEvent e) {
String s = "Leaving the window";
tf.setText(s);
}
public void mouseMoved(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
// 監控顯示鼠標何時進入以及離開窗口
// 以及點擊鼠標時能顯示位置(橫縱座標)
}
4、
package org.cust.test7.calculate;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class BinaryPanel extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
List<JPanel> bitPanelList = new ArrayList<JPanel>();
public BinaryPanel(){
setLayout(new GridBagLayout());
setBorder(BorderFactory.createEtchedBorder());
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 8; j++) {
if (i == 0 || i == 2) {
// 建立一個面板並設置爲左對齊的flowLayout,它容納4個label
JPanel bitPanel = new JPanel();
FlowLayout flowLayout = new FlowLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
flowLayout.setHgap(0);
bitPanel.setLayout(flowLayout);
bitPanel.setName(String.valueOf(bitPanelList.size()));
bitPanelList.add(bitPanel);
// 添加4個label
for (int k = 0; k < 4; k++) {
JLabel label = createBitLabel();
String buttonName = String.valueOf(k);
label.setName(buttonName);
//label.setText(buttonName);
bitPanel.add(label);
System.out.println("add createBitButton of "
+ buttonName);
}
// 將包含4個button的小面板作爲一個單元格添加到binaryPanel
add(bitPanel,
new GBC(j, i).setFill(GridBagConstraints.BOTH)
.setWeight(100, 100).setInsets(5));
} else if (i == 1) {
String[] texts = { "63", null, null, null, "47", null,
null, " 32" };
for (int k = 0; k < texts.length; k++) {
JLabel indexLabel = new JLabel();
if (texts[k] == null)
continue;
indexLabel.setText(texts[k]);
add(indexLabel, new GBC(k, i).setFill(GridBagConstraints.BOTH)
.setWeight(100, 100).setInsets(5));
}
} else if (i == 3) {
String[] texts = { "31", null, null, null, "15", null,
null, " 0" };
for (int k = 0; k < texts.length; k++) {
JLabel indexLabel = new JLabel();
if (texts[k] == null)
continue;
indexLabel.setText(texts[k]);
add(indexLabel,
new GBC(k, i).setFill(GridBagConstraints.BOTH)
.setWeight(100, 100).setInsets(5));
}
}
}
}
}
private JButton createBitButton() {
JButton bitButton = new JButton();
bitButton.setText("0");
bitButton.setEnabled(false);
return bitButton;
}
private JLabel createBitLabel() {
JLabel bitLabel = new JLabel();
bitLabel.setText("0");
// bitLabel.setEnabled(false);
return bitLabel;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new BinaryPanel());
frame.pack();
frame.setVisible(true);
}
}
效果圖:
4、
CalculatorUI類:
package org.cust.test7.calculate;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class CalculatorUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
JPanel contentPane;
private JMenuBar menuBar = new JMenuBar();// 菜單欄
private JMenu menu[] = new JMenu[3];
private JMenuItem menuItem[] = new JMenuItem[9];
protected JButton screenButton = new JButton("0");// 結果顯示欄
String[] menuNames = { "查看", "編輯", "幫助" };
String[] menuViewItemNames = { "標準型", "科學型", "程序員型", "複製", "粘貼", "剪切", "關於計算器", "幫助", "更新" };
public CalculatorUI() {
// 設置窗體屬性
setTitle("計算器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 添加菜單欄和菜單
setJMenuBar(menuBar);
for (int i = 0; i < menu.length; i++) {
menu[i] = new JMenu(menuNames[i]);
menuBar.add(menu[i]);
menu[i].addActionListener(this);
}
for (int j = 0; j < 3; j++) {
menuItem[j] = new JMenuItem(menuViewItemNames[j]);
menu[0].add(menuItem[j]);
menuItem[j].addActionListener(this);
}
for (int j = 3, i = 1; j < 6; j++) {
menuItem[j] = new JMenuItem(menuViewItemNames[j]);
menu[i].add(menuItem[j]);
menuItem[j].addActionListener(this);
}
for (int j = 6, i = 2; j < 9; j++) {
menuItem[j] = new JMenuItem(menuViewItemNames[j]);
menu[i].add(menuItem[j]);
menuItem[j].addActionListener(this);
}
}
public void setBasicPane() {
// 設爲窗體默認面板
contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
setContentPane(contentPane);
// 添加顯示按鈕
JPanel srceenPanel = new JPanel();
srceenPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
srceenPanel.setLayout(new BorderLayout());
srceenPanel.add(screenButton, BorderLayout.CENTER);
screenButton.setHorizontalAlignment(SwingConstants.RIGHT);// 文字右對齊
// 添加顯示面板
contentPane.add(srceenPanel, new GBC(0, 0).setFill(GridBagConstraints.BOTH).setWeight(100, 100));
}
public void setScitificMode(CalculatorUI frame) {
setBasicPane();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
ScitificFunctionPanel scitificFunctionPanel = new ScitificFunctionPanel(frame);
StandardNumPanel standardNumPanel = new StandardNumPanel(frame);
mainPanel.add(scitificFunctionPanel, new GBC(0, 0).setFill(GridBagConstraints.BOTH).setWeight(100, 100));
mainPanel.add(standardNumPanel, new GBC(1, 0).setFill(GridBagConstraints.BOTH).setWeight(100, 100));
getContentPane().add(mainPanel, new GBC(0, 1).setFill(GridBagConstraints.BOTH).setWeight(100, 100));
showFrame();
}
public void showFrame() {
pack();
this.setSize(700, 500);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
// TODO Auto-generated method stub
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
CalculatorUI frame = new CalculatorUI();
frame.setScitificMode(frame);
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
for (int h = 0; h < menuItem.length; h++) {
if (e.getSource() == menuItem[h]) {
screenButton.setText(menuViewItemNames[h]);
}
}
}
}
GBC類:
package org.cust.test7.calculate;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
public class GBC extends GridBagConstraints{
/**
*
*/
private static final long serialVersionUID = 1L;
/*
* constructs a GBC with a given gridx and gridy position and all other grid
* bag constraint values set to the default
* @param gridx the gridx position
* @param gridy the gridy position
*/
public GBC(int gridx, int gridy){
this.gridx = gridx;
this.gridy = gridy;
}
public GBC(int gridx, int gridy, int gridWidth, int gridHeight){
this.gridx = gridx;
this.gridy = gridy;
this.gridwidth = gridWidth;
this.gridheight = gridHeight;
}
/*
* sets the anchor
* @param anchor the anchor style
* @return this object for further modification
*/
public GBC setAnchor(int anchor){
this.anchor = anchor;
return this;
}
/*
* sets the fill direction
* @param fill the fill direction
* @return this object for further modification
*/
public GBC setFill(int fill){
this.fill = fill;
return this;
}
/*
* sets the cell weights
* @param weightx the cell weight in x direction
* @param weighty the cell weight in y direction
* @return this object for further modification
*/
public GBC setWeight(int weightx, int weighty){
this.weightx = weightx;
this.weighty = weighty;
return this;
}
/*
* sets the insets of this cell
* @param insets distance ths spacing to use in all directions
* @return this object for further modification
*/
public GBC setInsets(int distance){
this.insets = new Insets(distance, distance, distance, distance);
return this;
}
/*
* sets the insets of this cell
* @param top distance ths spacing to use on top
* @param bottom distance ths spacing to use on bottom
* @param left distance ths spacing to use to the left
* @param right distance ths spacing to use to the right
* @return this object for further modification
*/
public GBC setInsets(int top, int left,int bottom,int right){
this.insets = new Insets(top, left, bottom, right);
return this;
}
/*
* sets the Ipad of this cell
* @param Ipad distance ths spacing to use in all directions
* @return this object for further modification
*/
public GBC setIpad(int ipadx, int ipady){
this.ipadx = ipadx;
this.ipadx = ipadx;
return this;
}
}
ScitificFunctionPanel類:
package org.cust.test7.calculate;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class ScitificFunctionPanel extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private static int x;
private static int y;
private static JButton jb[][];
private CalculatorUI cu;
private String[][] strArray;
private static JRadioButton angelButton;
private static JRadioButton radianButton;
private static JRadioButton gradientButton;
public ScitificFunctionPanel(CalculatorUI cu) {
this.cu = cu;
// 設置窗體layout
setLayout(new GridBagLayout());
// 用於放置“度”、“弧度”、“梯度”這三個按鈕
JPanel angelPanel = new JPanel();
BoxLayout boxLayout = new BoxLayout(angelPanel, BoxLayout.X_AXIS);
angelPanel.setLayout(boxLayout);
angelPanel.setBorder(BorderFactory.createEtchedBorder());
angelButton = new JRadioButton("度");
radianButton = new JRadioButton("弧度");
gradientButton = new JRadioButton("梯度");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(angelButton);
buttonGroup.add(radianButton);
buttonGroup.add(gradientButton);
angelPanel.add(angelButton);
angelPanel.add(Box.createHorizontalGlue());
angelPanel.add(radianButton);
angelPanel.add(Box.createHorizontalGlue());
angelPanel.add(gradientButton);
// 添加角度面板
add(angelPanel, new GBC(0, 0, 5, 1).setFill(GridBagConstraints.BOTH).setInsets(5).setWeight(100, 100));
// 添加按鈕
String[][] btnStrings = { { "", "Inv", "In", "(", ")" }, { "Int", "sinh", "sin", "x^2", "n!" },
{ "dms", "cosh", "cos", "x^y", "y√x" }, { "π", "tanh", "tan", "x^3", "3√x" },
{ "F-E", "Exp", "Mod", "log", "10^x" } };
strArray = btnStrings;
x = btnStrings.length;
y = btnStrings[0].length;
jb = new JButton[x][y];
for (int i = 0; i < btnStrings.length; i++) {
for (int j = 0; j < btnStrings[0].length; j++) {
jb[i][j] = new JButton(btnStrings[i][j]);
jb[i][j].addActionListener(this);
add(jb[i][j],
new GBC(j, i + 1, 1, 1).setFill(GridBagConstraints.BOTH).setInsets(5).setWeight(100, 100));
if (i + j == 0)
jb[i][j].setEnabled(false);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (angelButton.isSelected()){
cu.screenButton.setText("切換到度");
}
else if (radianButton.isSelected()){
cu.screenButton.setText("切換到弧度");
}
else if (gradientButton.isSelected()){
cu.screenButton.setText("切換到梯度");
}
else if (e.getSource() == jb[i][j]) {
cu.screenButton.setText(strArray[i][j] + "被點擊");
}
}
}
}
}
StandardNumPanel類:
package org.cust.test7.calculate;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class StandardNumPanel extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private CalculatorUI cu;
private static int x;
private static int y;
private static String[][] strArray;
private static JButton[][] jb;
public StandardNumPanel(CalculatorUI cu) {
this.cu = cu;
// 設置窗體layout
setLayout(new GridBagLayout());
// add buttons
String[][] btnStrings = { { "MC", "MR", "MS", "M+", "M-" }, { "←", "CE", "C", "+-", "sqrt" },
{ "7", "8", "9", "/", "%" }, { "4", "5", "6", "*", "1/x" }, { "1", "2", "3", "-", "=" },
{ "0", "0", ".", "+", "=" } };
strArray = btnStrings;
x = btnStrings.length;
y = btnStrings[0].length;
jb = new JButton[x][y];
boolean isBtnEqualsNeedsAdded = true;
boolean isBtnPlusNeedsAdded = true;
for (int i = 0; i < btnStrings.length; i++) {
for (int j = 0; j < btnStrings[0].length; j++) {
if (btnStrings[i][j].equals("=") && isBtnEqualsNeedsAdded) {
jb[i][j] = new JButton(btnStrings[i][j]);
add(jb[i][j],
new GBC(j, i, 1, 2).setFill(GridBagConstraints.BOTH).setInsets(3).setWeight(100, 100));
jb[i][j].addActionListener(this);
isBtnEqualsNeedsAdded = false;
continue;
}
if (btnStrings[i][j].equals("0") && isBtnPlusNeedsAdded) {
jb[i][j] = new JButton(btnStrings[i][j]);
add(jb[i][j],
new GBC(j, i, 2, 1).setFill(GridBagConstraints.BOTH).setInsets(3).setWeight(100, 100));
isBtnPlusNeedsAdded = false;
jb[i][j].addActionListener(this);
continue;
}
jb[i][j] = new JButton(btnStrings[i][j]);
add(jb[i][j], new GBC(j, i, 1, 1).setFill(GridBagConstraints.BOTH).setInsets(3).setWeight(100, 100));
jb[i][j].addActionListener(this);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (e.getActionCommand().equals("C")) {
cu.screenButton.setText("0");
} else if (e.getSource() == jb[i][j]) {
cu.screenButton.setText(strArray[i][j] + "被點擊");
}
}
}
}
}
效果圖: