題目
使用Swing實現一個窗口程序,窗口包括一個菜單欄,請按以下要求實現相應功能。
(1)窗口標題爲“GUI程序”,大小爲400X300, 居中顯示:窗口上有一個面板,面板背景色爲灰色;
(2)面板上有一個標籤,內容爲“河南城建學院”,字體爲“隸書”,字號“20”:菜單欄上有兩個菜單“字體”和“退出”, 菜單“字體”中有菜單項“宋體”和“楷體”, 菜單“退出”中有菜單項“關閉”;
(3)當點擊菜單項“宋體”時,標籤內容“河南城建學院”顯示宋體樣式:點擊菜單項“楷體”時,標籤內容“河南城建學院”顯示楷體樣式;點擊菜單項“關閉”時,退出應用程序。
參考答案
package onemore.study;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GuiDemo {
public static void main(String[] args) {
// 創建 "GUI程序" 窗口
JFrame frame = new JFrame("GUI程序");
// 設置窗口大小
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 創建面板
JPanel panel = new JPanel();
// 設置面板背景色爲灰色
panel.setBackground(Color.GRAY);
// 創建 "河南城建學院" 標籤
JLabel label = new JLabel("河南城建學院", JLabel.CENTER);
// 設置字體爲隸書,字號爲20
label.setFont(new Font("隸書", Font.PLAIN, 20));
panel.add(label);
frame.getContentPane().add(panel);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
// 創建 "字體" 菜單
JMenu menuFont = new JMenu("字體");
menuBar.add(menuFont);
// 創建 "退出" 菜單
JMenu menuExit = new JMenu("退出");
menuBar.add(menuExit);
// 創建 "宋體" 菜單項
JMenuItem song = new JMenuItem("宋體");
menuFont.add(song);
// 創建 "楷體" 菜單項
JMenuItem kai = new JMenuItem("楷體");
menuFont.add(kai);
// 創建 "關閉" 菜單項
JMenuItem close = new JMenuItem("關閉");
menuExit.add(close);
//處理 "宋體" 菜單項的動作事件
song.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setFont(new Font("宋體", Font.PLAIN, 20));
}
});
//處理 "楷體" 菜單項的動作事件
kai.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setFont(new Font("楷體", Font.PLAIN, 20));
}
});
//處理 "關閉" 菜單項的動作事件
close.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
// 設置界面可見
frame.setVisible(true);
}
}
運行效果: