所以我做了一个 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
,但我不知道如何。我在编程方面相当新,所以请答案很容易让初学者阅读。
Panel
来显示,您可以使用 Rectangle
选择JColorChooser
的颜色。
答案 0 :(得分:0)
您使用的是错误的面板。这就是全部。
将f.add(jpp.panel, BorderLayout.CENTER);
更改为f.add(new TestProjectDialog(), BorderLayout.CENTER);
,您应该感觉良好。
HTH,Jan