在Java中,我的JButton不会居中,并且不会显示JButton左右两侧的图形

时间:2015-11-29 04:28:04

标签: java jbutton

当我尝试将Jbutton放在中心时,它不会显示在屏幕上。我想这可能是因为它出现在我的其他背景图形下。这是按钮的代码:

JFrame frame = new JFrame(title);
Dimension size = new Dimension(width, height);
frame.setPreferredSize(size);
frame.setMaximumSize(size);
frame.setMinimumSize(size);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);

JPanel p = new JPanel();
JButton start = new JButton("Start");
start.setVisible(true);
start.setFont(new Font("TimesNewRoman", Font.BOLD, 25));
p.add(start);
frame.add(p, BorderLayout.SOUTH);


frame.add(game, BorderLayout.CENTER);
frame.setVisible(true); 
game.start();

这是我的图形代码:

 `Graphics g = bs.getDrawGraphics();
    g.setColor(new Color(0,100,0));
    g.fillRect(0, 400, 950, 500);
    g.setColor(new Color(135,206,235));
    g.fillRect(0, 0, 950, 500);
    //Cloud display code 
    g.setColor(Color.WHITE);
    g.fillOval(newX, randY, randWidth, randHeight);
    newX++; 
    g.setColor(Color.WHITE);
    g.fillOval(newXi, randYi, randWidthi, randHeighti);     
    newXi++;
    g.setColor(Color.WHITE);
    g.fillOval(newXii, randYii, randWidthii, randHeightii);     
    newXii++;   
    g.setColor(Color.WHITE);
    g.fillOval(newXiii, randYiii, randWidthiii, randHeightiii);     
    newXiii++;  
    g.setColor(Color.WHITE);
    g.fillOval(newXiiii, randYiiii, randWidthiiii, randHeightiiii);     
    newXiiii++; 
    if (newX==width){
        newX=0-301;
    }
    if (newXi==width){
        newXi=0-301;
    }
    if (newXii==width){
        newXii=0-301;
    }
    if (newXiii==width){
        newXiii=0-301;
    }
    if (newXiiii==width){
        newXiiii=0-301;
    }
    g.setColor(Color.GREEN);
    g.fillRect(300, 140, 340, 100);
    g.setFont(new Font("TimesNewRoman", Font.BOLD, 50));
    g.setColor(Color.BLACK);
    g.drawString("Pen Hero", 360, 200 );
    g.dispose();
    bs.show();`

1 个答案:

答案 0 :(得分:1)

panel.setVisible(false);

这消除了你想要的那个空白区域,还有按钮。