我想通过点击"PLAY ME"按钮转到连接四的另一帧,但我很困惑如何这样做。在这里,我有connectfour打开页面的代码,并在页面上设置了标签和按钮。下面是我的代码:
import java.awt.*;
import javax.swing.event.*;
import java.awt.Color.*;
import javax.swing.*;
import java.util.*;
public class Game implements ActionListener{
public Game(){
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(new Dimension(1000,1000));
frame.setTitle("Connect Four");
frame.setLayout(new BorderLayout());
JButton play = new JButton();
play.setPreferredSize(new Dimension(75,150));
play.setBackground(Color.RED);
play.setFont(new Font("Arial", Font.PLAIN, 40));
play.setForeground(Color.BLACK);
play.setText("CLICK ME TO PLAY");
frame.add(play, BorderLayout.SOUTH);
JPanel north = new JPanel(new BorderLayout());
JLabel title = new JLabel("Connect Four");
north.setBackground(Color.WHITE);
title.setFont(new Font("Arial", Font.PLAIN, 100));
title.setForeground(Color.RED);
title.setHorizontalAlignment(0);
title.setVerticalAlignment(1);
frame.add(north, BorderLayout.NORTH);
north.add(title);
JPanel intro = new JPanel(new GridLayout(10,1));
intro.setBackground(Color.WHITE);
JLabel instructions = new JLabel("Instructions");
instructions.setFont(new Font("Ariel", Font.PLAIN, 70));
JLabel instructionsPart1 = new JLabel("Both players will be assigned a color, either red or black.");
JLabel instructionsPart2 = new JLabel("Players will take turns placing the colored discs on to the board.");
JLabel instructionsPart3 = new JLabel("The OBJECTIVE is to get four of one colored discs in a row.");
instructionsPart1.setFont(new Font("Ariel", Font.PLAIN, 35));
instructionsPart2.setFont(new Font("Ariel", Font.PLAIN, 35));
instructionsPart3.setFont(new Font("Ariel", Font.PLAIN, 35));
intro.add(instructions);
intro.add(new JLabel(""));
intro.add(instructionsPart1);
intro.add(new JLabel(""));
intro.add(instructionsPart2);
intro.add(new JLabel(""));
intro.add(instructionsPart3);
intro.add(new JLabel(""));
frame.add(intro, BorderLayout.CENTER);
frame.add(intro);
}
}
隐藏第一帧并将第二帧的可见性设置为true
btnplay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
second_add second = new second_add();
setVisible(false); // Hide current frame
second.setVisible(true);
}
});
与其改变框架,不如改变面板。代替使用JFrame
的add()
方法,使用setContentPane(Container Container)
与其在框架中添加按钮之类的东西,不如创建另一个包装器面板,并在其上使用BorderLayout,然后将该面板添加到框架中:
的例子:
JPanel wrapper = new JPanel(new BorderLayout());
wrapper.add(play, BorderLayout.SOUTH);
//etc.
frame.setContentPane(wrapper);
然后,点击手柄按钮,实现ActionListener
接口。不要在主类中这样做——你需要不止一个。使用匿名内部类或lambda表达式。例子:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setContentPane(someOtherJPanel);
}
});