当我运行下面的代码时,我无法看到背景颜色为红色。它显示的是默认的。我有什么要加到这些线上的吗?
import java.awt.*;
import java.awt.Graphics;
import javax.swing.*;
public class gfix extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(80, 100, 150, 75);
}
public static void main(String[] args){
gfix gg=new gfix();
JFrame frame = new JFrame("RISK");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);
JButton button = new JButton("test");
button.setBounds(100, 100, 150, 150);
panel.add(button);
frame.setVisible(true);
}
}发布于 2020-05-04 00:07:24

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class gfix {
public static void main(String[] args) {
JFrame frame = new JFrame("RISK");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
frame.add(panel);
JButton button = new JButton("test");
// adjust numbers as needed
button.setMargin(new Insets(20,40,20,40));
panel.add(button);
// adjust numbers as needed
panel.setBorder(new EmptyBorder(10,40,50,200));
frame.pack();
frame.setVisible(true);
}
}其他贴士:
,EachWordUpperCaseClass,firstWordLowerCaseMethod(),firstWordLowerCaseAttribute,除非是UPPER_CASE_CONSTANT),然后使用它
发布于 2020-05-03 16:04:31
您将在painGraphics()类中重写gfix类对象,因此将gfix类对象添加到您的框架中,而不是gfix提供的JPanel类对象。
gfix gg=new gfix();
JFrame frame = new JFrame("RISK");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel panel = new JPanel(); Not needed
//panel.setLayout(null);
frame.add(gg);
JButton button = new JButton("test");
button.setBounds(100, 100, 150, 150);
gg.add(button);
frame.setVisible(true);对于g.fillRect(80, 100, 150, 75);,给出适当的面板边界来填充完整的面板背景。或者在int width = getWidth(); int height = getHeight();中使用paintGraphics获取实际高度和宽度。
https://stackoverflow.com/questions/61577436
复制相似问题