您只需在您的
actionPerformed(...)方法中对此进行纠正:
public void actionPerformed(ActionEvent e){ if(e.getSource()==start) { //what to do here? CardLayout cardLayout = (CardLayout) Virus.thegame.getLayout(); cardLayout.next(Virus.thegame); }}正如@kleopatra(皇后乐队)本人所指出的那样,请不要替代
paint()您在
paintComponent(Graphicsg)any方法中的绘画内容
JPanel/JComponent。而且,
Jframe一旦实现大小,首先将组件添加到您的中,然后仅将其设置为Visible,而不是在此之前。而不是为
Jframe简单地覆盖
JPanel的方法设置大小,而是
getPreferredSize()使其返回一些有效的
DimensionObject。
下次观看代码时,请注意以下顺序:
public Virus(){ jf.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); jf.setResizable(false); thegame.add(start); thegame.add(game); jf.add(thegame); jf.pack(); jf.setLocationRelativeTo(null); jf.setVisible(true);}这是您的完整代码:
import javax.swing.Jframe;import javax.swing.JPanel;import java.awt.event.ActionListener;import java.awt.Dimension;import java.awt.Graphics;import java.awt.Font;import java.awt.Color;import javax.swing.JButton;import javax.swing.JLabel;import java.awt.Rectangle;import java.awt.event.ActionEvent;import java.awt.CardLayout;public class Virus extends Jframe{ private static final long serialVersionUID =1L; Jframe jf = new Jframe("Virus"); static JPanel thegame = new JPanel(new CardLayout()); JPanel game = new VirusGamePanel(); JPanel start = new StartScreen(); public Virus(){ jf.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); jf.setResizable(false); thegame.add(start); thegame.add(game); jf.add(thegame); jf.pack(); jf.setLocationRelativeTo(null); jf.setVisible(true); } public static void main(String[] args) { new Virus(); }}class StartScreen extends JPanel implements ActionListener{ private static final long serialVersionUID = 1L; JButton start = new JButton("Start"); public StartScreen(){ start.addActionListener(this); start.setBounds(new Rectangle(400,300,100,30)); this.add(start); } @Override protected void paintComponent(Graphics g){ super.paintComponent(g); g.setFont(new Font("Impact",Font.BOLD,72)); g.setColor(Color.MAGENTA); g.drawString("Virus",275,300); } @Override public Dimension getPreferredSize() { return (new Dimension(600, 600)); } public void actionPerformed(ActionEvent e) { if(e.getSource()==start) { //what to do here? CardLayout cardLayout = (CardLayout) Virus.thegame.getLayout(); cardLayout.next(Virus.thegame); } }}class VirusGamePanel extends JPanel{ public VirusGamePanel() { JLabel label = new JLabel("I am ON", JLabel.CENTER); add(label); } @Override public Dimension getPreferredSize() { return (new Dimension(600, 600)); }}


