如何在JPanel 2D中绘制圆



你好,我是JAVA的新手,最近学习了图形,但被困在如何画一个圆(我通过谷歌自己学习),如果你帮助我下面的代码行,我会很高兴(不要参考背景子按钮)

public class Panel_ {
static JPanel panel1 = new JPanel();
public static Color randomColor() {
int r = (int) Math.round(Math.random() * 255 - 1);
int g = (int) Math.round(Math.random() * 255 - 1);
int b = (int) Math.round(Math.random() * 255 - 1);
Color R_col = new Color(r, g, b);
System.out.println(R_col);
return R_col;
}
public static void Panel() {
var color_changer = new JButton("To change color");
color_changer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel1.setBackground(randomColor());
}
});
var Panel = new JPanel();
Panel.add(color_changer);
Panel.setBackground(Color.blue);
panel1.setBackground(Color.black);
panel1.setPreferredSize(new Dimension(400, 430));
var frame = new JFrame("Color changer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel1, BorderLayout.NORTH);
frame.getContentPane().add(Panel, BorderLayout.SOUTH);
frame.pack();
frame.setSize(500, 500);
frame.setBackground(Color.blue);
frame.setVisible(true);
}
public void paintCircle(Graphics g) {
g.setColor(Color.blue);
g.fillOval(60, 80, 100, 100);
}
public static void main(String args[]) {
Panel();
}
}

使用paintComponent对于panel1,我在下面的可运行代码中将其名称更改为topPanel:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Panel extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel topPanel;
private JPanel panel;
private JButton color_changer;


public Panel() {
initializeForm();
}

private void initializeForm() {
setAlwaysOnTop(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.blue);

color_changer = new JButton("To change color");
color_changer.addActionListener((ActionEvent e) -> {
topPanel.setBackground(randomColor());
});
topPanel = new JPanel() {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.fillOval(60, 80, 100, 100);
};
};

panel = new JPanel();
panel.add(color_changer);
panel.setBackground(Color.blue);
topPanel.setBackground(Color.black);
topPanel.setOpaque(true);
topPanel.setPreferredSize(new Dimension(400, 430));

getContentPane().add(topPanel, BorderLayout.NORTH);
getContentPane().add(panel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
}

public static void main(String[] args) {
java.awt.EventQueue.invokeLater(() -> {
new Panel().setVisible(true);
});
}

public static Color randomColor() {
int r = (int) Math.round(Math.random() * 255 - 1);
int g = (int) Math.round(Math.random() * 255 - 1);
int b = (int) Math.round(Math.random() * 255 - 1);
Color R_col = new Color(r, g, b);
System.out.println(R_col);
return R_col;
}

}

相关内容

  • 没有找到相关文章

最新更新