这是我的代码,我如何在其中添加背景,我尝试了所有可能的解决方案,但图片不会在背景中显示。
我该怎么办,谁能帮助我?
public class Triangle {
JLabel l1;
public static void main(String[] args) {
new Triangle();
}
public Triangle() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.setSize(400,400);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Polygon poly;
{
poly = new Polygon(
new int[]{110, 150, 50},
new int[]{200, 0, 0},
3);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.blue);
g2.fill(poly);
g2.setColor(Color.red);
g2.fillRect(0,0,25,75);
g2.setColor(Color.green);
g2.fillOval(200,100,100,50);
g2.setColor(Color.green);
g2.fillOval(300,300,250,250);
}
}
}
这是我的代码,我如何在其中添加背景,我尝试了所有可能的解决方案,但图片不会在背景中显示。
我该怎么办,谁能帮助我?
将背景色设置为JPanel
尝试一下:
TestPane myPane = new TestPane();
myPane.setBackground(Color.green);
frame.add(myPane);