我正在从一本书中学习Java图形。我写了这段代码,希望它用pinkColor为背景着色,Button的背景为PurpleColor,但是输出是完全紫色的。我该如何解决? 以及如何将 f1 应用于 a 以在输出中包含带有 f1 字体的 HELLO 。
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);
}
}
答案 0 :(得分:1)
您需要确保将JButton设置为不透明。
b.setOpaque(true)
要设置JButton的字体,请使用setFont方法。
b.setFont(f1)
答案 1 :(得分:1)
有关详细信息,请参见代码中的注释。
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);
}
}