GridBagLayout组件位置错误

时间:2018-09-01 12:33:31

标签: java image containers jbutton gridbaglayout

我的代码本意是将JButton放在顶部,但是当我添加图像时,它位于图像的顶部,这很好,但不是位于顶部,而是位于中间,并且您无法获得值对于网格状,所以我不知道如何使其达到顶部。我在Container上有很多按钮,但是我只想放一个代码以缩短它,但是如果您需要完整的代码,我会提供它。谢谢这是我的代码

public void add(Container pane){
setBackground(Color.black);

    pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

    URL resource = getClass().getResource("Graphitebackground.v2.jpg");

    ImageIcon i2 = new ImageIcon(resource);
    URL resource3 = getClass().getResource("Graphitebackground.v4.jpg");

    ImageIcon i3 = new ImageIcon(resource3);
    URL resource1 = getClass().getResource("Graphitebackground.v3.jpg");
    ImageIcon i1 = new ImageIcon(resource1);  
    JLabel background = new JLabel(i2);
    background.setSize(new Dimension(1000,1000));

    background.setVisible(true);
    background.setLayout(new GridBagLayout());
    JButton button;
    pane.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();

    //natural height, maximum width
    c.fill = GridBagConstraints.HORIZONTAL;           

    JButton label2 = new JButton(i1);

    c.weightx = 0.5;

    label2.setText("Level1");
    label2.setPreferredSize(new Dimension(100,100));

    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    label2.setForeground(Color.RED);
    label2.setFont(new Font("Arial", Font.BOLD,100));
    label2.setHorizontalTextPosition(JButton.CENTER);
    label2.setVerticalTextPosition(JButton.CENTER);
    label2.setBorderPainted(false);
      label2.addMouseListener(new java.awt.event.MouseAdapter(){
         public void mouseEntered(java.awt.event.MouseEvent evt){
            label2.setBorderPainted(true);
            label2.setBorder(BorderFactory.createLineBorder(Color.red,3)); 
        }
        public void mouseExited(java.awt.event.MouseEvent evt){
             label2.setBorderPainted(false); 
        }
        });
        background.add(label2,c);
        pane.add(background);
}

0 个答案:

没有答案