我正試圖爲遊戲創建一個基本的遊戲菜單。我現在只是測試菜單,而我寫的大部分選項只是爲了測試菜單是否真正起作用。所以我有一個Menu類和一個OptionPanel類。我在哪裏搞砸了創建遊戲菜單?
這是菜單類:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
JPanel cardPanel;
public Main(String title) {
super(title);
setBounds(100, 100, 800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cardPanel = new JPanel();
CardLayout cl = new CardLayout();
cardPanel.setLayout(cl);
OptionPanel panel1 = new OptionPanel(this);
Board panel2 = new Board();
Rules panel3 = new Rules();
cardPanel.add(panel1,"1");
cardPanel.add(panel2,"2");
cardPanel.add(panel3,"3");
add(cardPanel);
setVisible(true);
}
public static void main(String[] args)
{
Main w = new Main("AP Animation Demo");
}
public void changePanel() {
((CardLayout)cardPanel.getLayout()).next(cardPanel);
requestFocus();
}
}
,這裏是我的選項面板類:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class OptionPanel extends JPanel implements ActionListener {
Main w;
public OptionPanel(Main w) {
this.w = w;
JButton button = new JButton("Press me!");
button.addActionListener(this);
add(button);
JButton button2 = new JButton("Game rules");
button2.addActionListener(this);
add(button2);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(Color.BLACK);
}// Call JPanel's paintComponent method to paint the background
public void actionPerformed(ActionEvent e) {
w.changePanel();
}
}
我如何使它所以當菜單彈出時,我可以點擊一個按鈕導致遊戲,當點擊另一個按鈕時,鏈接到另一個屏幕。我認爲它與actionPerformed的事情有關,所以我嘗試添加if(e.getSource ==按鈕)和類似的東西,但它找不到任何按鈕變量。任何建議/反饋?
我建議每創造1個按鈕的動作監聽,每做一個特定的任務 –
那麼像......如果(e.getSource ==按鈕) – user2397837
如果是所有'的paintComponent(圖形)'不,刪除它並在構造函數中放置'setBackground(Color.BLACK);'。 –