我想在我的java菜單中將ActionListener添加到JMenuItem中。如何將ActionListener添加到JMenuItem?
這是菜單的截圖:
我想添加的ActionListener爲「矩形」的JMenuItem爲了在點擊「矩形」菜單項的矩形形狀出現。我多次嘗試添加ActionListener,但每次都失敗。
這裏是我的代碼:
級 「menubar.java」:
import javax.swing.*;
public class menubar extends JFrame{
public menubar(){
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu shape = new JMenu("Shape");
menubar.add(shape);
JMenuItem rect = new JMenuItem("Rectangle");
shape.add(rect);
JMenuItem star = new JMenuItem("Star");
shape.add(star);
JMenu color = new JMenu("Color");
menubar.add(color);
JMenuItem black = new JMenuItem("Black");
color.add(black);
JMenuItem orange = new JMenuItem("Orange");
color.add(orange);
}
public static void main(String[] args) {
menubar gui = new menubar();
gui.setTitle("Menu Bar");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
shapes SPS = new shapes();
gui.add(SPS);
gui.setSize(500,300);
gui.setVisible(true);
gui.setLocationRelativeTo(null);
}
}
級 「shapes.java」:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class shapes extends JPanel{
int midX = 220;
int midY = 90;
int radius[] = {60,20,50,20};
int nPoints = 16;
int[] X = new int[nPoints];
int[] Y = new int[nPoints];
public void paintComponent(Graphics gphcs){
super.paintComponent(gphcs);
this.setBackground(Color.WHITE);
gphcs.setColor(Color.BLUE);
gphcs.fillRect(20,35,100,30);
gphcs.setColor(Color.RED);
gphcs.drawString("Welcome to Java", 20, 20);
for (int i=0; i < nPoints; i++) {
double x = Math.cos(i * ((2 * Math.PI)/nPoints)) * radius[i % 4];
double y = Math.sin(i * ((2 * Math.PI)/nPoints)) * radius[i % 4];
X[i] = (int) x + midX;
Y[i] = (int) y + midY;
}
gphcs.setColor(Color.GREEN);
gphcs.fillPolygon(X, Y, nPoints);
}
}
,我會很感激,如果有人幫我與這個問題。
感謝您的時間..
我沒有看到你試圖調用'addActionListener(...)'到任何東西。你看過Swing菜單教程嗎?它在那裏都是拼寫出來的,所以我們真的沒有必要讓這裏的信息反覆出現,因爲它在那裏是爲了提問。谷歌會幫你找到它 - 或者我也可以:[如何使用菜單](http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html) – 2013-05-02 03:13:25
認真?你看過你的上一個問題中鏈接的[如何使用菜單](http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html)?投票關閉 – MadProgrammer 2013-05-02 03:20:15
@MadProgrammer:我知道,它也讓我感到吃驚,我不知道他已經獲得了鏈接!對於原來的海報,如果您之前已經看過教程並且讓您感到困惑,那麼請告訴我們您的問題到底是什麼讓您感到困惑,但是請告訴我們您至少在嘗試解決問題之前先解決問題,而不會顯示努力的證據。請告訴我們你並不是在懶惰,而是讓其他人爲你解決問題。 – 2013-05-02 03:21:47