我试图用按钮制作标题屏幕,并使用 JFrame
对象将背景作为图片(BufferedImage
)。但是,屏幕显示为灰色,仅在按钮上鼠标鼠标时才更新屏幕的部分。
JFrame
类:
//import statements
public class StartGame extends JFrame{
private JLabel title=new JLabel("Title");
private JButton start=new JButton("New Game");
private JButton quit=new JButton("Quit");
public static final int WIDTH = 1280;
public static final int HEIGHT = 720;
public static void main(String [] args){
StartGame g1=new StartGame();
g1.play();
}
public StartGame(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle( "Title" );
setResizable( false );
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setSize( WIDTH, HEIGHT );
setPreferredSize( new Dimension(WIDTH, HEIGHT) );
setLocation(dim.width/2-getSize().width/2, dim.height/2-getSize().height/2);
setUndecorated(true);
setVisible(true);
StartGamePanel sgp = new StartGamePanel();
sgp.setSize( StartGame.WIDTH,StartGame.HEIGHT );
sgp.setLayout( null );
sgp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
sgp.setVisible(true);
start.setBackground(Color.BLACK);
start.setBorder(BorderFactory.createEmptyBorder());
start.setBounds( WIDTH/2-105, HEIGHT/9*6, 210, 40 );
start.setForeground(Color.WHITE);
quit.setBackground(Color.BLACK);
quit.setBorder(BorderFactory.createEmptyBorder());
quit.setBounds( WIDTH/2-75, HEIGHT/9*8, 150, 40 );
quit.setForeground(Color.WHITE);
title.setBounds( WIDTH/2-216, HEIGHT/8*2, 432, 100 );
title.setForeground(Color.WHITE);
ButtonListener spy = new ButtonListener();
start.addActionListener( spy );
quit.addActionListener( spy );
sgp.add(title);
sgp.add(start);
sgp.add(quit);
getContentPane().add( sgp );
pack();
}
private void play(){
EventQueue.invokeLater(new Runnable() {
public void run() {
setVisible(true);
}
});
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(quit)) {
System.exit(0);
} else if (e.getSource().equals(start)){
//start
dispose();
}
}
}
}
和JPanel
类:
//import statements
public class StartGamePanel extends JPanel{
private BufferedImage bg;
public StartGamePanel(){
setBackground( Color.WHITE );
setSize( StartGame.WIDTH, StartGame.HEIGHT );
setPreferredSize( new Dimension(StartGame.WIDTH, StartGame.HEIGHT) );
setBorder(BorderFactory.createLineBorder(Color.BLACK));
setLayout( null );
try {
bg = ImageIO.read(new File("pics/SplashScreen.png"));
} catch (IOException e) {
System.out.println ( "No splash screen image in StartGamePanel" );
}
}
@Override
public void paintComponent( Graphics g ) {
super.paintComponent( g );
g.drawImage( bg, 0, 0, null );
}
private void play(){
EventQueue.invokeLater(new Runnable() {
public void run() {
setVisible(true);
}
});
}
}
我很确定问题在JPanel
类中,因为我能够从程序的另一部分中用另一个JPanel
类替换它,并且可以使用。
不在开始时放置 setVisible(true);
,或者您之后需要 repaint();
。
因为它有时间在底部更新这些添加,这就是为什么您的程序为灰色或Java应用程序的默认颜色。