问题描述
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.JPanel;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
public class SpeedMathGoStartScreen extends JFrame{
JLabel background;
JLabel title;
JButton play;
JPanel playPanel;
JLabel playLabel;
JButton guide;
JPanel guidePanel;
public SpeedMathGoStartScreen() {
title = new JLabel("SPEED MATH GO");
title.setFont(new Font("Comic Sans",Font.BOLD,96));
title.setBounds(90,900,100);
this.add(title);
ImageIcon backgroundImage = new ImageIcon("C:\\Users\\chenr\\Documents\\Speed Math Go\\iconfinder_play-circle_2561292\\ttt.png");
background = new JLabel(backgroundImage);
background.setBounds(0,1000,700);
this.add(background);
ImageIcon playImage = new ImageIcon("C:\\Users\\chenr\\Documents\\Speed Math Go\\iconfinder_play-circle_2561292\\iconfinder_play-circle_2561292.png");
play = new JButton("Play",playImage);
playPanel = new JPanel();
playPanel.setLayout(null);
playPanel.setBounds(345,200,300,150);
play.setBounds(345,150);
play.setFont(new Font("Comic Sans",48));
play.setBackground(Color.RED);
play.setVisible(true);
playPanel.add(play);
this.add(playPanel);
ImageIcon guideImage = new ImageIcon("C:\\Users\\chenr\\Documents\\Speed Math Go\\iconfinder_play-circle_2561292\\iconfinder_thefreeforty_map_1243687.png");
guide = new JButton("Guide",guideImage);
guidePanel = new JPanel();
guidePanel.setLayout(null);
guidePanel.setBounds(320,400,350,150);
guide.setBounds(320,150);
guide.setFont(new Font("Comic Sans",48));
guide.setBackground(Color.CYAN);
guide.setVisible(true);
guidePanel.add(guide);
this.add(guidePanel);
//play.addActionListener(new ActionListener()
// {
// public void actionPerformed(ActionEvent e)
// {
// new SpeedMathGoGUI();
// }
// });
play.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new SpeedMathGoGUI();
dispose();
}
});
guide.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new SpeedMathGoGuide();
dispose();
}
}
);
setDefaultCloSEOperation(EXIT_ON_CLOSE);
setSize(1000,700);
setVisible(true);
}
}
如果在Eclipse上运行此命令,则仅显示指南按钮。当我注释掉第56行(应该是this.add(guidePanel))时,仅显示播放按钮。我必须对我的代码进行哪些调整才能使它们同时显示在JFrame上?我还想知道其他类是否可能会影响此错误,因为在按下按钮时会转换为其他两个类。
解决方法
不要使用空布局!!!不要使用setBounds()!!!
Swing旨在与布局管理器一起使用,因此您需要了解布局管理器如何工作。
仅显示向导按钮。
this.add(playPanel);
...
this.add(guidePanel);
默认情况下,JFrame的内容窗格使用BorderLayout
。
在上面的代码中,当您将组件添加到BorderLayout
且未指定约束时,将使用CENTER
约束。但是,“中心”中只能显示一个组件,因此您会看到最后添加的一个组件。
如何同时显示多个按钮
如果要在面板上使用两个按钮(或任何组件),请在面板上添加两个按钮。基本代码为:
JPanel buttonsPanel = new JPanel();
buttonsPanel.add( play );
buttonsPanel.add( guide );
this.add(buttonsPanel);
JPanel的默认布局管理器是FlowLayout
。这是一个简单的布局。组件显示在同一行上,添加组件时不需要任何约束。
阅读Layout Managers上Swing教程中的部分,以获取更多信息和其他布局管理器的工作示例。您可以根据需要选择适当的布局管理器。您始终可以使用不同的布局管理器来嵌套面板,以实现所需的布局。