0

当我设置背景时,我无法看到我的按钮,直到我将光标移过它们.. 我试图为按钮设置 setOpaque(true) 但它不起作用..

    final JFrame f1=new JFrame("Front Main");
    f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel p1=new JPanel(new GridBagLayout()){
    private Image img = ImageIO.read(new File("C:\\Users\\DELL\\Desktop\\football.jpg"));
    public void paint( Graphics g ) { 
           super.paintComponents(g);

           g.drawImage(img, 0,0,1366,730, null);
           }
    };
    GridBagConstraints g1= new GridBagConstraints();
    JButton b1=new JButton("Admin");
    JButton b2=new JButton("User");
    JLabel l1=new JLabel("Login as:");
    g1.insets=new Insets(3,3,0,0);
    g1.weightx=1;
    g1.ipadx=200;
    g1.anchor=GridBagConstraints.NORTH;
    g1.gridwidth=GridBagConstraints.RELATIVE;
    p1.add(b1,g1);
    g1.anchor=GridBagConstraints.NORTH;
    g1.gridwidth=GridBagConstraints.REMAINDER;
    p1.add(b2,g1);
    g1.weightx=3;
    g1.ipadx=0;
    p1.add(l1,g1);
    f1.add(p1);
    p1.setOpaque(false);
    f1.setSize(1366,730);
    f1.setVisible(true);
4

2 回答 2

0

由于JFrame管理其内容的方式,覆盖其paint方法通常不是一个好主意。使用 aJPanel代替:

JPanel panel = new JPanel() {
    private Image img = ImageIO.read(new File("C:\\Users\\DELL\\Desktop\\football.jpg"));
    @Override
    public void paintComponent(Graphics g) { 
        super.paintComponent(g);

        g.drawImage(img, 0,0,1366,730, this);
    }

    etc...
};

final JFrame f1 = new JFrame("Front Main");
f1.add(panel);
f1.setSize(1366,730);
f1.setVisible(true);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
于 2013-02-27T15:29:14.720 回答
0

在我将光标移过它们之前,我无法看到我的按钮

那是因为您在框架可见之后将组件添加到框架中。

f1.setSize(1366,730);
f1.setVisible(true);
....
JButton b1=new JButton("Admin");
JButton b2=new JButton("User");
...
p1.add(b1,g1);
p1.add(b2,g1);

代码应该是这样的:

....
JButton b1=new JButton("Admin");
JButton b2=new JButton("User");
...
p1.add(b1,g1);
p1.add(b2,g1);
...
f1.setSize(1366,730);
f1.setVisible(true);

此外,关于paint() 方法的所有其他评论都是有效的。您不应该覆盖paint() 方法。自定义绘制是通过覆盖 JPanel 或 JComponent 的 paintComponent() 方法来完成的。然后将此组件添加到框架中。

于 2013-02-27T16:14:40.093 回答