对于JButton和JFrame,相同的颜色显示不同。我该如何解决?

时间:2013-11-17 18:03:22

标签: java swing jframe transparency jbutton

enter image description here

以下代码生成上面的图像。如您所见,相同的粉红色对于JFrame而言显示出与JButton不同的颜色。我可以做什么修复使它们颜色完全相同?

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.Border;
    import javax.swing.border.CompoundBorder;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.LineBorder;

    public class Testing extends JFrame {   
        public Testing() {
            super("hi");
            setBackground(Color.PINK);
            JPanel panel = new JPanel();

            JButton jb = new JButton();
            jb.setText("Here I am");
            Border line = new LineBorder(Color.PINK);
            Border margin = new EmptyBorder(5, 15, 5, 15);
            Border compound = new CompoundBorder(line, margin);
            jb.setOpaque(true);
            jb.setBorder(compound);
            jb.setBackground(Color.PINK);

            panel.add(jb);
            add(panel);
            setVisible(true);
        }

        public static void main(String[] args){
            Testing t = new Testing();  
        }
    }

2 个答案:

答案 0 :(得分:3)

为面板而不是框架设置背景颜色。问题解决了。

public Testing() {
    super("hi");
    setBackground(Color.PINK);
    JPanel panel = new JPanel();

    JButton jb = new JButton();
    jb.setText("Here I am");
    Border line = new LineBorder(Color.PINK);
    Border margin = new EmptyBorder(5, 15, 5, 15);
    Border compound = new CompoundBorder(line, margin);
    jb.setOpaque(true);
    jb.setBorder(compound);
    jb.setBackground(Color.PINK);
    panel.setBackground(Color.PINK);
    panel.add(jb);
    add(panel);
    setVisible(true);
}

答案 1 :(得分:3)

颜色 相同,但代码设置错误的粉红色。可见。

enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class ColorTest extends JFrame {

    public ColorTest() {
        super("hi");
        //setBackground(Color.PINK);
        JPanel panel = new JPanel();
        panel.setBackground(Color.PINK);

        JButton jb = new JButton();
        jb.setText("Here I am");
        Border line = new LineBorder(Color.RED, 5);
        Border margin = new EmptyBorder(5, 15, 5, 15);
        Border compound = new CompoundBorder(line, margin);
        jb.setOpaque(true);
        jb.setBorder(compound);
        jb.setBackground(Color.PINK);

        panel.add(jb);
        add(panel);
        pack();
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {
        ColorTest t = new ColorTest();
    }
}

另外

  1. 不要扩展框架,只使用一个实例。
  2. 应该启动Swing GUI并且在EDT更新。