我正在尝试使用按钮制作标题屏幕,并使用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
类替换它,并且它有效。
答案 0 :(得分:1)
不要将setVisible(true);
放在开头,或者之后需要repaint();
。
因为它有时间在底部更新这些添加,所以这就是你的程序是灰色或Java应用程序的默认颜色的原因。