Java 图形(颜色和字体)

Java graphic(color and font)

我正在从一本书中学习 java 图形。我写了这段代码,我希望它用 pinkColor 为背景着色,用 purpleColor 为 Button 的背景着色,但输出完全是紫色的。我该如何解决? 以及如何将 f1 应用到 a 以获得 HELLO 和字体 f1 在输出中。

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

public class First {
    public static void main(String[] args) {
        Color purpleColor = new Color(120, 78, 140);
        Color pinkColor = new Color(120, 13, 14);
        String a ="HELLO";
        Font f1 = new Font(a, Font.BOLD + Font.ITALIC + Font.CENTER_BASELINE, 25);
        JFrame f = new JFrame();
        f.setSize(900,600);
        JButton b = new JButton(a);
        b.setSize(400,200); 
        f.setBackground(pinkColor);
        b.setBackground(purpleColor);
        f.add(b);
        f.setVisible(true); 
    }
}

您需要确保将 JButton 设置为不透明。

b.setOpaque(true)

要设置 JButton 的字体,请使用 setFont 方法。

b.setFont(f1)

详情见代码注释。

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

public class First {
    public static void main(String[] args) {
        Color purpleColor = new Color(120, 78, 140);
        Color pinkColor = new Color(120, 13, 14);
        String a ="HELLO";
        // CENTER_BASELINE should not be included in a Font style!
        //Font f1 = new Font(a, Font.BOLD + Font.ITALIC + Font.CENTER_BASELINE, 25);
        Font f1 = new Font(a, Font.BOLD + Font.ITALIC, 25);
        JFrame f = new JFrame();
        // default layout for a frame is BorderLayout
        // a component added to BL with no constraint will end up in CENTER
        // a component in center will be stretched to available size
        f.setLayout(new GridBagLayout());
        f.setSize(300,200);
        JButton b = new JButton(a);
        // Must set the font! 
        b.setFont(f1);
        // will be (rightly) ignored by layout. Use setMargin(..)
        //b.setSize(400,200); 
        b.setMargin(new Insets(20,20,20,20));
        // Many calls relevant to the content pane of a frame were configured 
        // to pass directly through to it. The BG color was NOT one of them!
        //f.setBackground(pinkColor);
        f.getContentPane().setBackground(pinkColor);
        b.setBackground(purpleColor);
        // AFAIR, necessary for some PLAFs
        b.setContentAreaFilled(false);
        b.setOpaque(true);
        f.add(b);
        // Good practice
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setVisible(true); 
    }
}