我想创建一堵蓝线轮廓和黑色填充的墙。我现在只有一面蓝色的墙,我尝试了几种图形方法,但没有奏效。
public void paint(Graphics g) {
g.setColor(Color.blue);
g.fillRect(x, y, size, size);
}
我想创建一堵蓝线轮廓和黑色填充的墙。我现在只有一面蓝色的墙,我尝试了几种图形方法,但没有奏效。
public void paint(Graphics g) {
g.setColor(Color.blue);
g.fillRect(x, y, size, size);
}
用于Graphics#drawRect
绘制轮廓:-
g.setColor(Color.black);
g.fillRect(x, y, size, size);
g.setColor(Color.blue);
g.drawRect(x, y, size, size);
首先,覆盖paintComponent
,而不是paint
。其次,没有必要像那样重新发明轮子。相反,使用现有的 Swing 组件(例如JPanel
),
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(getWallComponent());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private static JPanel getWallComponent()
{
JPanel panel = new JPanel();
panel.setBackground(Color.black);
panel.setBorder(BorderFactory.createLineBorder(Color.blue, 5));
panel.setPreferredSize(new Dimension(200, 200)); // for demo purposes only
return panel;
}
}
只需在蓝色矩形上绘制另一个矩形,比蓝色矩形小,如下所示
public void paint(Graphics g) {
g.setColor(Color.blue);
g.fillRect(x, y, size, size);
g.setColor(Color.black);
g.fillRect(x-width/2,y-width/x,size-width,size-with);
}
package painting;
import java.awt.*;
import javax.swing.*;
public class RectangleOutline extends JPanel {
int x = 100;
int y = 200;
public void paintComponent(Graphics g) {
super.paintComponent(g);
outline(g);
}
public void outline(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(new Color(255, 0, 0));
g2.fillRect(x, y, 30, 30);
g2.setStroke(new BasicStroke(5));
g2.setColor(new Color(0, 0, 0));
g2.drawRect(x, y, 30, 30);
}
public static void main(String[] args){
JFrame f = new JFrame();
RectangleOutline graphics = new RectangleOutline();
f.add(graphics);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setSize(400, 400);
}
}