Java paintComponent中的条件
我正在尝试创建一个应用程序,根据按下的按钮左右移动形状。我有一个int-shapesCond和int-colorsCond,它根据从JComboBox中选择的选项更改值 如果我只更改JComboBox的矩形选项中ShapeCond的值,而不更改圆形选项中的值,则会打印一个矩形。但是,如果我更改两个选项中的shapecond值或更改colorsCond值,我的paintComponentGraphics g方法将不会打印任何形状Java paintComponent中的条件,java,swing,if-statement,jcombobox,paintcomponent,Java,Swing,If Statement,Jcombobox,Paintcomponent,我正在尝试创建一个应用程序,根据按下的按钮左右移动形状。我有一个int-shapesCond和int-colorsCond,它根据从JComboBox中选择的选项更改值 如果我只更改JComboBox的矩形选项中ShapeCond的值,而不更改圆形选项中的值,则会打印一个矩形。但是,如果我更改两个选项中的shapecond值或更改colorsCond值,我的paintComponentGraphics g方法将不会打印任何形状 public class DrawShapes extends JF
public class DrawShapes extends JFrame {
public static final int CANVAS_WIDTH = 500;
public static final int CANVAS_HEIGHT = 300;
public static final Color CANVAS_BACKGROUND = Color.YELLOW;
private int x1 = CANVAS_WIDTH / 4;
private int y1 = CANVAS_HEIGHT / 4;
private int rectWidth = CANVAS_WIDTH / 2;
private int rectHeight = CANVAS_HEIGHT / 2;
private int x2 = CANVAS_WIDTH * (1/3);
private int y2 = CANVAS_HEIGHT * (2/5);
private int circWidth = CANVAS_WIDTH * (1/5);
private int circHeight = CANVAS_HEIGHT / 3;
private Color blue = new Color(0, 0, 225);
private int shapesCond = 0;
private int colorsCond = 0;
private CanvasDrawArea canvas;
public DrawShapes() {
JPanel btnPanel = new JPanel(new FlowLayout());
String[] shapeName = {"Rectangle", "Circle"};
JComboBox shapes = new JComboBox(shapeName);
shapes.setSelectedIndex(1);
btnPanel.add(shapes);
shapes.addActionListener(new ActionListener(){ //shapes combobox
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource(); //copies shapes combo box
String msg = (String)cb.getSelectedItem();
switch(msg){
case "Rectangle":
shapesCond = 1;
break;
case "Circle":
shapesCond = 2;
}//switch end
}
}); //action listener end
String[] colorName = {"Red", "Blue", "Green"};
JComboBox colors = new JComboBox(colorName); //colors combobox
colors.setSelectedIndex(1);
btnPanel.add(colors);
shapes.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource(); //copies shapes combo box
String msg = (String)cb.getSelectedItem();
switch(msg){
case "Red" :
colorsCond = 1;
break;
case "Blue" :
colorsCond = 2;
break;
case "Green" :
colorsCond = 3;
break;
}
}
});
canvas = new CanvasDrawArea();
canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas, BorderLayout.CENTER);
cp.add(btnPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Drawing Shapes: Moving Shapes");
pack();
setVisible(true);
requestFocus();
}//DrawShapes constructor end
class CanvasDrawArea extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (shapesCond == 1 && colorsCond == 1) { //red rectangle
g.setColor(Color.RED);
g.fillRect(x1, y1, rectWidth, rectHeight);
repaint();
}
if (shapesCond == 1 && colorsCond == 2) { //blue rectangle
g.setColor(Color.BLUE);
g.fillRect(x1, y1, rectWidth, rectHeight);
repaint();
}
if (shapesCond == 1 && colorsCond == 3) { //green rectangle
g.setColor(Color.GREEN);
g.fillRect(x1, y1, rectWidth, rectHeight);
repaint();
}
if (shapesCond == 2 && colorsCond == 1) { // red circle
g.setColor(Color.RED);
g.fillOval(x2, y2, circWidth, circHeight);
repaint();
}
if (shapesCond == 2 && colorsCond == 2) { //blue circle
g.setColor(Color.BLUE);
g.fillOval(x2, y2, circWidth, circHeight);
repaint();
}
if (shapesCond == 2 && colorsCond == 3) { //green circle
g.setColor(Color.GREEN);
g.fillOval(x2, y2, circWidth, circHeight);
repaint();
}
}//paintComponent method end
}//CanvasDrawArea class end
}//DrawShapes class end
这是我的主要方法。它在一个叫做Main的独立类中
CirchWidth是0…1/5是一个整数除法,这意味着后面的小数被删除,表示它等于0,所以0*任何东西都是0
您可以使用类似intCANVAS_WIDTH*1/5f的内容来代替
您正在将颜色组合框的ActionListener添加到形状组合框
JComboBox colors = new JComboBox(colorName); //colors combobox
colors.setSelectedIndex(1);
btnPanel.add(colors);
shapes.addActionListener(new ActionListener(){
最好放置形状。SetSelectedIndex 1;和颜色。设置选定的索引1;注册ActionListeners后,这将允许它们触发ActionListeners并初始化初始值
paintComponent方法中的if语句可以更改为更像
switch (colorsCond) {
case 1:
g.setColor(Color.RED);
break;
case 2:
g.setColor(Color.BLUE);
break;
case 3:
g.setColor(Color.GREEN);
break;
}
switch (shapesCond) {
case 1:
g.fillRect(x1, y1, rectWidth, rectHeight);
break;
case 2:
g.fillOval(x2, y2, circWidth, circHeight);
break;
}
这将减少代码混乱和重复,并使假设发生的事情变得更容易
在actionPerformed方法结束时,需要调用repaint
只是为了比较
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawShapes {
public static void main(String[] args) {
new DrawShapes();
}
public DrawShapes() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawingPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawingPane extends JPanel {
private JComboBox cbShape;
private JComboBox cbColor;
private CanvasPane canvasPane;
public DrawingPane() {
setLayout(new BorderLayout());
canvasPane = new CanvasPane();
JPanel controls = new JPanel();
cbShape = new JComboBox(new String[]{"Rectangle", "Circle"});
cbColor = new JComboBox(new ColorEntry[]{
new ColorEntry("Red", Color.RED),
new ColorEntry("Green", Color.GREEN),
new ColorEntry("Blue", Color.BLUE),
new ColorEntry("Magenta", Color.MAGENTA)});
cbColor.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
if (value instanceof ColorEntry) {
Color color = ((ColorEntry)value).getColor();
setBackground(color);
setOpaque(true);
}
return this;
}
});
JButton apply = new JButton("Apply");
apply.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CustomShape shape = null;
ColorEntry entry = (ColorEntry) cbColor.getSelectedItem();
Color color = entry == null ? null : entry.getColor();
if (color != null) {
int width = canvasPane.getWidth() / 2;
int height = canvasPane.getHeight() / 2;
switch (cbShape.getSelectedIndex()) {
case 0: {
int x = (canvasPane.getWidth() - width) / 2;
int y = (canvasPane.getHeight() - height) / 2;
shape = new CustomRectangle(x, y, width, height, color);
}
break;
case 1: {
int diameter = Math.min(width, height);
int x = (canvasPane.getWidth() - diameter) / 2;
int y = (canvasPane.getHeight() - diameter) / 2;
shape = new CustomCircle(x, y, diameter, color);
}
break;
}
}
canvasPane.setShape(shape);
}
});
controls.add(cbShape);
controls.add(cbColor);
controls.add(apply);
add(canvasPane);
add(controls, BorderLayout.SOUTH);
}
}
public class ColorEntry {
private String name;
private Color color;
public ColorEntry(String name, Color color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public Color getColor() {
return color;
}
@Override
public String toString() {
return getName();
}
}
public class CanvasPane extends JPanel {
private CustomShape shape;
public CanvasPane() {
}
public void setShape(CustomShape shape) {
this.shape = shape;
repaint();
}
public CustomShape getShape() {
return shape;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (shape != null) {
Graphics2D g2d = (Graphics2D) g;
shape.paint(g2d);
}
}
}
public interface CustomShape {
public Rectangle getBounds();
public Color getColor();
public void paint(Graphics2D g2d);
}
public abstract class AbstractCustomShape implements CustomShape {
private Rectangle bounds;
private Color color;
@Override
public Rectangle getBounds() {
return bounds;
}
@Override
public Color getColor() {
return color;
}
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
public void setColor(Color color) {
this.color = color;
}
}
public class CustomRectangle extends AbstractCustomShape {
public CustomRectangle(int x, int y, int width, int height, Color color) {
setBounds(new Rectangle(x, y, width, height));
setColor(color);
}
@Override
public void paint(Graphics2D g2d) {
g2d.setColor(getColor());
g2d.fill(getBounds());
}
}
public class CustomCircle extends AbstractCustomShape {
public CustomCircle(int x, int y, int diameter, Color color) {
setBounds(new Rectangle(x, y, diameter, diameter));
setColor(color);
}
@Override
public void paint(Graphics2D g2d) {
g2d.setColor(getColor());
Rectangle bounds = getBounds();
Ellipse2D circle = new Ellipse2D.Double(bounds.x, bounds.y, bounds.width, bounds.height);
g2d.fill(circle);
}
}
}
考虑提供一个说明你的问题的方法。这将导致更少的混乱和更好的响应-哦,不要从任何paint方法中调用repaint…您的代码毫无意义,您在方法之外拥有功能,没有明确的类边界定义,并且不可能理解逻辑流。重新发布一个可运行的示例好的,将代码复制并粘贴到IDE或文本文件中,看看是否可以使其编译…}//构造器结尾后面跟着一堆代码,后面跟着“}//DrawShapes构造器结尾”是非常令人担忧的…我的意思是,我们实际上在处理哪个构造器…@MadProgrammer那是我的错,我不知道为什么我有两个构造器结尾。我想我在编辑代码时一定忘了拿出一个。@peeskillet Yep,在OP中提到过,我还没能把它拖过这条线……谢谢你继续帮助我解决这个问题。我将CirchWidth和CirchHeight的值更改为实数。现在两种形状都打印得很完美。现在的问题是,您编写的代码更改了形状,但颜色都是灰色的。你知道为什么会这样吗?对不起,我对你的代码做了很多修改。您需要在actionPerformed方法的末尾添加重新绘制…我不太理解您编写的所有内容,但我非常感谢您花这么多时间帮助我解决这个问题。我一定会仔细检查这段代码,看看是否能弄明白你做了什么。我也不太明白;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawShapes {
public static void main(String[] args) {
new DrawShapes();
}
public DrawShapes() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawingPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawingPane extends JPanel {
private JComboBox cbShape;
private JComboBox cbColor;
private CanvasPane canvasPane;
public DrawingPane() {
setLayout(new BorderLayout());
canvasPane = new CanvasPane();
JPanel controls = new JPanel();
cbShape = new JComboBox(new String[]{"Rectangle", "Circle"});
cbColor = new JComboBox(new ColorEntry[]{
new ColorEntry("Red", Color.RED),
new ColorEntry("Green", Color.GREEN),
new ColorEntry("Blue", Color.BLUE),
new ColorEntry("Magenta", Color.MAGENTA)});
cbColor.setRenderer(new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
if (value instanceof ColorEntry) {
Color color = ((ColorEntry)value).getColor();
setBackground(color);
setOpaque(true);
}
return this;
}
});
JButton apply = new JButton("Apply");
apply.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CustomShape shape = null;
ColorEntry entry = (ColorEntry) cbColor.getSelectedItem();
Color color = entry == null ? null : entry.getColor();
if (color != null) {
int width = canvasPane.getWidth() / 2;
int height = canvasPane.getHeight() / 2;
switch (cbShape.getSelectedIndex()) {
case 0: {
int x = (canvasPane.getWidth() - width) / 2;
int y = (canvasPane.getHeight() - height) / 2;
shape = new CustomRectangle(x, y, width, height, color);
}
break;
case 1: {
int diameter = Math.min(width, height);
int x = (canvasPane.getWidth() - diameter) / 2;
int y = (canvasPane.getHeight() - diameter) / 2;
shape = new CustomCircle(x, y, diameter, color);
}
break;
}
}
canvasPane.setShape(shape);
}
});
controls.add(cbShape);
controls.add(cbColor);
controls.add(apply);
add(canvasPane);
add(controls, BorderLayout.SOUTH);
}
}
public class ColorEntry {
private String name;
private Color color;
public ColorEntry(String name, Color color) {
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public Color getColor() {
return color;
}
@Override
public String toString() {
return getName();
}
}
public class CanvasPane extends JPanel {
private CustomShape shape;
public CanvasPane() {
}
public void setShape(CustomShape shape) {
this.shape = shape;
repaint();
}
public CustomShape getShape() {
return shape;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (shape != null) {
Graphics2D g2d = (Graphics2D) g;
shape.paint(g2d);
}
}
}
public interface CustomShape {
public Rectangle getBounds();
public Color getColor();
public void paint(Graphics2D g2d);
}
public abstract class AbstractCustomShape implements CustomShape {
private Rectangle bounds;
private Color color;
@Override
public Rectangle getBounds() {
return bounds;
}
@Override
public Color getColor() {
return color;
}
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
public void setColor(Color color) {
this.color = color;
}
}
public class CustomRectangle extends AbstractCustomShape {
public CustomRectangle(int x, int y, int width, int height, Color color) {
setBounds(new Rectangle(x, y, width, height));
setColor(color);
}
@Override
public void paint(Graphics2D g2d) {
g2d.setColor(getColor());
g2d.fill(getBounds());
}
}
public class CustomCircle extends AbstractCustomShape {
public CustomCircle(int x, int y, int diameter, Color color) {
setBounds(new Rectangle(x, y, diameter, diameter));
setColor(color);
}
@Override
public void paint(Graphics2D g2d) {
g2d.setColor(getColor());
Rectangle bounds = getBounds();
Ellipse2D circle = new Ellipse2D.Double(bounds.x, bounds.y, bounds.width, bounds.height);
g2d.fill(circle);
}
}
}