将矩形添加到JPanel

时间:2014-10-25 16:01:06

标签: java swing paint

所以我做了一个 Rectangle ,但我想在面板中展示它,但我不知道我是怎么尝试过很多东西的,但显然还不够。我很感激这方面的帮助。我很新,所以请给我一步一步的答案或类似的东西。

此处包含Rectangle

的代码
import javax.swing.*;

import java.util.*;
import java.awt.*;

public class TestProjectDialog extends JPanel{

    static String name;
    public Rectangle  r;


    public String getName(){
        return name;
    }

    public void paintComponent(Graphics g){ 
        super.paintComponent(g);
         r = new Rectangle(430,50,250,400);
         g.setColor(jpp.bodyColour);
        g.fillRect((int)r.getX(),(int)r.getY(),(int)r.getHeight(),(int)r.getWidth());

    }

    TestProjectJPanel jpp = new TestProjectJPanel();

    public static void main(String[] args){



    JOptionPane.showMessageDialog(null, "Just about to draw a REALLY GOOD 2D car \n just need input please.");

     name= JOptionPane.showInputDialog("Imagine a car, what is it's name?");
    if(name == null || (name != null && ("".equals(name))))   
    {
        JOptionPane.showMessageDialog(null, "Invalid input/pressed cancel, closing program.");
      System.exit(0);
    }
    JOptionPane.showMessageDialog(null, "Ah okay, so it's name is " + name); 

    JFrame f = new JFrame(name);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TestProjectJPanel jpp = new TestProjectJPanel();


    jpp.setBackground(Color.WHITE);
    f.setSize(1440,900);
    f.add(jpp.panel, BorderLayout.CENTER);
    f.add(jpp.b, BorderLayout.SOUTH);

    f.setVisible(true);

    }

}

具有 panel 本身的代码

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


public class TestProjectJPanel extends JFrame {


    public JButton b;
    public Color color = (Color.WHITE);
    public JPanel panel;
    public Color bodyColour;
    public Color doorColour;
    public Color wheelColour;


    public TestProjectJPanel(){
        panel = new JPanel();
        panel.setBackground(color);

        // bodyColour button
        b = new JButton("Choose a colour for the body of the car");
        b.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent event){
                        bodyColour = JColorChooser.showDialog(null, "Pick the colour", bodyColour);
                        if(bodyColour==null) 
                            bodyColour = (Color.BLACK);


                    }
                }
                );

    }

        }

所以基本上,我想将Rectangle添加到panel,但我不知道如何。我在编程方面相当新,所以请答案很容易让初学者阅读。

编辑:我想要这个程序要做的,就是从提示要求输入名称开始,我将其存储在String名称中并将其设置为标题,然后我想要一个Panel来显示,您可以使用 Rectangle 选择JColorChooser的颜色。

1 个答案:

答案 0 :(得分:0)

您使用的是错误的面板。这就是全部。 将f.add(jpp.panel, BorderLayout.CENTER);更改为f.add(new TestProjectDialog(), BorderLayout.CENTER);,您应该感觉良好。

HTH,Jan