3

我想创建一堵蓝线轮廓和黑色填充的墙。我现在只有一面蓝色的墙,我尝试了几种图形方法,但没有奏效。

public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.fillRect(x, y, size, size);
}
4

4 回答 4

7

用于Graphics#drawRect绘制轮廓:-

g.setColor(Color.black);
g.fillRect(x, y, size, size);
g.setColor(Color.blue);
g.drawRect(x, y, size, size);
于 2012-11-29T15:38:15.930 回答
5

首先,覆盖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;
    }
}

在此处输入图像描述

于 2012-11-29T15:44:24.477 回答
3

只需在蓝色矩形上绘制另一个矩形,比蓝色矩形小,如下所示

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);
}
于 2012-11-29T15:37:53.113 回答
0
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);

    }
}
于 2015-10-17T11:30:14.943 回答