我有2个面板(2个类,从JPanel扩展),1个框架(1个类,从JFrame扩展)
我的第一个面板 - WelcomePanel:
package caro;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class WelcomePanel extends JPanel {
public WelcomePanel() {
ImageIcon logoImage = new ImageIcon("/home/khanhpq/logo.png");
JButton playButton = new JButton("Play");
JButton exitButton = new JButton("Exit");
JLabel imageLabel = new JLabel(logoImage);
add(imageLabel);
add(playButton);
add(exitButton);
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int option = JOptionPane.showConfirmDialog(null, "Are you sure ?", "Warning", JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
}
}
我的第二个小组 - BoardPanel:
package caro;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class BoardPanel extends JPanel {
public BoardPanel() {
JPanel boardPanel = new JPanel();
Board board = new Board();
CellButton cellButton[] = new CellButton[144];
GridLayout gridLayout = new GridLayout(12, 12);
boardPanel.setLayout(gridLayout);
for (int i = 0; i < 144; i++) {
cellButton[i] = new CellButton();
boardPanel.add(cellButton[i]);
}
}
}
我的主框架 - MainFrame
package caro;
import javax.swing.JFrame;
public class MainFrame extends JFrame {
public MainFrame() {
add(new WelcomePanel());
setSize(360, 380);
setVisible(true);
}
public static void main(String[] args) {
MainFrame startFrame = new MainFrame();
}
}
我的问题:帮我在面板按钮上编写代码,addActionListener(材质示例) . 当我按下播放按钮(WelcomePanel)时,隐藏了WelcomePanel并显示了BoardPanel . 并且,当我退出BoardPanel(按下关闭按钮,或单击x按钮)时,将显示WelcomePanel . 我的朋友推荐使用Message和Handle,但我不知道 . 请帮我 . 谢谢 .
1 回答
最好将依赖项(像按钮,面板等组件......)声明为字段 . 通过这种方式,它们对于作为它们的控制器的第三类是可见的 . 在下一个例子中,我让MainFrame控制自己,只是一个例子 . 阅读演示模式以获得更好的实践 .
WelcomePanel.java
BoardPanel.java
MainFrame.java