Java GUI:重新绘制()或类交互问题
因此,我正在创建一个海龟图形项目,当给定命令输入时,我很难让海龟移动。下面是两个交互类,处理用户输入的my TextPanel类和包含可绘制的“canvas”等的GraphicsPanel 由于我目前没有收到任何错误,我想知道我是否正确调用了GraphicsPanel类,或者我使用的是repaint(),而它是错误的方法?我不知所措,需要一双新眼睛。谢谢你抽出时间Java GUI:重新绘制()或类交互问题,java,swing,class,user-interface,repaint,Java,Swing,Class,User Interface,Repaint,因此,我正在创建一个海龟图形项目,当给定命令输入时,我很难让海龟移动。下面是两个交互类,处理用户输入的my TextPanel类和包含可绘制的“canvas”等的GraphicsPanel 由于我目前没有收到任何错误,我想知道我是否正确调用了GraphicsPanel类,或者我使用的是repaint(),而它是错误的方法?我不知所措,需要一双新眼睛。谢谢你抽出时间 public class TextPanel extends JPanel implements ActionListener {
public class TextPanel extends JPanel implements ActionListener {
private JTextArea textArea;
private JScrollPane scrollPane;
private JTextField commField;
private JButton enterBut;
private TextListener textListener;
private GraphicsPanel graphicsPanel;
//***********//
//CONSTRUCTOR//
//***********//
public TextPanel() {
textArea = new JTextArea();
scrollPane = new JScrollPane ( textArea );
enterBut = new JButton("Execute");
commField = new JTextField(10);
graphicsPanel = new GraphicsPanel();
textArea.setLineWrap(true); //stops text from going outside
textArea.setWrapStyleWord(true); //panel boundaries
//**********************//
//COMMAND IMPLEMENTATION//
//**********************//
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(commField.getText().contains("penup")) {
GraphicsPanel.penUp();
}
else if(commField.getText().contains("pendown")) {
GraphicsPanel.penDown();
}
else if(commField.getText().contains("turnright")) {
GraphicsPanel.turnRight();
}
else if(commField.getText().contains("turnleft")) {
GraphicsPanel.turnLeft();
}
else if(commField.getText().startsWith("forward")) { //getText method retrives user input from JTextField
String cForward = commField.getText(); //<startsWith> searches string for desired command
String[] cForwardArray = cForward.split("\\s+"); //string array created and split with " " as split
try {
int distance = Integer.parseInt(cForwardArray[1]); //parseInt takes the integer from string split
GraphicsPanel.forward(distance); //GraphicsPanel command called + distance integer
textArea.append(cForward + "\n"); //test for variable values
GraphicsPanel.validate();
GraphicsPanel.repaint(); //canvas is repainted
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().startsWith("backward")) {
String cBackward = commField.getText();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
GraphicsPanel.backward(distance);
textArea.append(cBackward +"\n");
GraphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("black")) {
GraphicsPanel.black(Color.black);
}
else if(commField.getText().contains("green")) {
GraphicsPanel.green(Color.green);
}
else if(commField.getText().contains("red")) {
GraphicsPanel.red(Color.red);
}
else if(commField.getText().contains("reset")) {
GraphicsPanel.clear();
}
else {
JOptionPane.showMessageDialog(textArea, "Invalid command, try again");
}
commField.setText("");
GraphicsPanel.repaint();
}
});
//****************//
//PANEL DIMENSIONS//
//****************//
setBackground(Color.black);
Dimension dim = getPreferredSize(); //sets dimensions of panel
dim.width = 250;
setPreferredSize(dim);
//setBorder(BorderFactory.createTitledBorder("Enter Commands here: "));
//setTitleColor(Color.white); //not sure why this doesnt change the text colour
//**************//
//GRIDBAG LAYOUT//
//**************//
setLayout(new GridBagLayout());
GridBagConstraints constraint = new GridBagConstraints();
add(commField, constraint);
constraint.fill = GridBagConstraints.HORIZONTAL;
constraint.ipady = 20;
constraint.ipadx = 60;
constraint.insets = new Insets(10, 5, 0, 0);
constraint.weightx = 1;
constraint.weighty = 0;
constraint.gridx = 0; //grid position
constraint.gridy = 0;
add(commField, constraint);
//***********************//
constraint.fill = GridBagConstraints.HORIZONTAL;
constraint.ipady = 15;
constraint.ipadx = 25;
constraint.anchor = GridBagConstraints.PAGE_END; //anchors to bottom of GUI
constraint.insets = new Insets(10, 0, 0, 0); //inserts gap
constraint.weightx = 0;
constraint.weighty = 0;
constraint.gridx = 1;
constraint.gridy = 0;
add(enterBut, constraint);
//*************************//
constraint.fill = GridBagConstraints.BOTH; //option how to fill 'cell'
constraint.ipady = 150; //dim of component
constraint.ipadx = 150;
constraint.insets = new Insets(0, 5, 0, 0);
constraint.gridwidth = 3; //how many grid cell it spans
constraint.weightx = 1; //precedent for space
constraint.weighty = 1;
constraint.gridx = 0; //grid position
constraint.gridy = 1;
add(new JScrollPane(textArea), constraint); //adds component
//and JSCrollPane
//************************//
//**NOTES****************************//
//next time use smaller variable name//
//***********************************//
}
private void setTitleColor(Color white) {
}
public void appendText(String text) {
}
@Override
public void actionPerformed(ActionEvent e) {
}
public void setTextListener(textListener listener) {
this.TextListener = listener;
}
}
公共类TextPanel扩展JPanel实现ActionListener{
私人JTEXTEXTAREA textArea;
私有JScrollPane滚动窗格;
私有JTextField commField;
私人JButton enterBut;
私有文本监听器;
专用图形面板GraphicsPanel;
//***********//
//建造师//
//***********//
公共文本面板(){
textArea=新的JTextArea();
scrollPane=新的JScrollPane(textArea);
enterBut=新的JButton(“执行”);
commField=新的JTextField(10);
graphicsPanel=新的graphicsPanel();
textArea.setLineWrap(true);//阻止文本向外移动
textArea.setWrapStyleWord(true);//面板边界
//**********************//
//命令执行//
//**********************//
commField.addActionListener(新ActionListener(){
已执行的公共无效操作(操作事件e){
if(commField.getText()包含(“penup”)){
GraphicsPanel.penUp();
}
else if(commField.getText()包含(“pendown”)){
GraphicsPanel.penDown();
}
else if(commField.getText()包含(“右转”)){
图形spanel.turnRight();
}
else if(commField.getText()包含(“左转”)){
图形spanel.左转();
}
else if(commField.getText().startsWith(“forward”){//getText方法从JTextField检索用户输入
String cForward=commField.getText();//在字符串中搜索所需的命令
String[]cForwardArray=cForward.split(\\s+”);//创建字符串数组并将“”作为拆分进行拆分
试一试{
int distance=Integer.parseInt(cForwardArray[1]);//parseInt从字符串拆分中获取整数
GraphicsPanel.forward(distance);//GraphicsPanel命令称为+distance整数
textArea.append(cForward+“\n”);//测试变量值
GraphicsPanel.validate();
GraphicsPanel.repaint();//画布已重新绘制
}
捕获(例外ev){
JOptionPane.showMessageDialog(文本区域,
Invaild或缺少参数,请检查“帮助”部分\n
+“有关命令的更多信息”);
}
}
else if(commField.getText().startsWith(“向后”)){
字符串cBackward=commField.getText();
字符串[]cBackwardArray=cBackward.split(\\s+);
试一试{
int distance=Integer.parseInt(cBackwardArray[1]);
图形向后(距离);
textArea.append(cBackward+“\n”);
GraphicsPanel.repaint();
}
捕获(例外ev){
JOptionPane.showMessageDialog(文本区域,
Invaild或缺少参数,请检查“帮助”部分\n
+“有关命令的更多信息”);
}
}
else if(commField.getText()包含(“黑色”)){
图形面板。黑色(颜色。黑色);
}
else if(commField.getText()包含(“绿色”)){
图形。绿色(颜色。绿色);
}
else if(commField.getText()包含(“红色”)){
图形。红色(颜色。红色);
}
else if(commField.getText()包含(“重置”)){
GraphicsPanel.clear();
}
否则{
showMessageDialog(文本区域,“无效命令,请重试”);
}
commField.setText(“”);
GraphicsPanel.repaint();
}
});
//****************//
//面板尺寸//
//****************//
挫折背景(颜色:黑色);
Dimension dim=getPreferredSize();//设置面板的尺寸
尺寸宽度=250;
设置首选大小(dim);
//setBordOrder(BorderFactory.createTitledBorder(“在此处输入命令:”);
//setTitleColor(Color.white);//不确定为什么这不会更改文本颜色
//**************//
//网格布局//
//**************//
setLayout(新的GridBagLayout());
GridBagConstraints constraint=新的GridBagConstraints();
添加(commField,constraint);
constraint.fill=gridbagsconstraints.HORIZONTAL;
constraint.ipady=20;
constraint.ipadx=60;
constraint.insets=新的插入(10,5,0,0);
constraint.weightx=1;
constraint.weighty=0;
constraint.gridx=0;//网格位置
constraint.gridy=0;
添加(commField,constraint);
//***********************//
constraint.fill=gridbagsconstraints.HORIZONTAL;
constraint.ipady=15;
constraint.ipadx=25;
constraint.anchor=GridBagConstraints.PAGE_END;//定位到GUI底部
constraint.insets=新插入(10,0,0,0);//插入间隙
constraint.weightx=0;
constraint.weighty=0;
constraint.gridx=1;
constraint.gridy=0;
添加(输入、约束);
//*************************//
constraint.fill=GridBagConstraints.BOTH;//选项如何填充“单元格”
constraint.ipady=150;
@SuppressWarnings("serial") //Represents the graphics display panel
//panel within the turtle program.
public class GraphicsPanel extends JPanel { //This panel contains an image which
//is updated to reflect user commands.
//background colour image
private final static Color BACKGROUND_COL = Color.DARK_GRAY;
private final static int TURTLE_X_SIZE = 20, TURTLE_Y_SIZE = 20;
private TextPanel TextPanel;
//private JTextField getTextField();
private BufferedImage image, turtleDisplay; //The underlying image used
//for drawing. This is required
//Djm added
private Color PenColour = Color.GREEN; //so any previous drawing activity is
private boolean penDown = false; //is persistent on the panel.
private int xPos=325, yPos=180;
private int direction = 180; //robot pointing down the screen;
//change drawLine colour
public void black(Color color) {
color = Color.black;
}
public void green(Color color) {
color = Color.green;
}
public void red(Color color) {
color = Color.red;
}
public void drawLine(Color color, int x1, int y1, int x2, int y2) {
Graphics g = image.getGraphics();
g.setColor(color);
g.drawLine(x1, y1, x2, y2);
}
public void penDown() {
penDown = true;
}
//***********************************//
public void penUp() {
penDown = false;
}
//***********************************//
public void turnRight() {
direction +=90;
if (direction >= 360)
direction = 0;
}
//***********************************//
public void turnLeft() {
direction -=90;
if (direction < 0)
direction = 270;
}
//***********************************//
//sends the turtle forward
public void forward(int distance) {
//Graphics g = image.getGraphics();
int x=xPos,y=yPos;
//stored xPos and yPos are current location
if (direction == 0) { //robot facing up the screen, so forward subtracts y
y = yPos-distance;
}
else if (direction == 90) { //robot facing right so forward add x
x = xPos + distance;
}
else if (direction == 180) { //robot facing down the screen, so forwards adds to y
y = yPos + distance;
}
else if (direction == 270) { //robot facing left, so forwards subtracts from x
x = xPos - distance;
}
else {
System.out.println("strange, shouldn't get here");
}
if (penDown) {
//x=400; y=400;
drawLine(PenColour, xPos, yPos, x, y);
//g.drawLine(xPos,yPos,x,y);
}
//now robot has moved to the new position
xPos = x;
yPos = y;
}
//***********************************//
//sends the turtle backwards
public void backward(int distance) {
int x=xPos,y=yPos;
//stored xPos and yPos are current location
if (direction == 0) { //robot facing up the screen, so forward adds y
y = yPos + distance;
}
else if (direction == 90) { //robot facing right so forward subtract x
x = xPos - distance;
}
else if (direction == 180) { //robot facing down the screen, so forwards subtracts to y
y = yPos - distance;
}
else if (direction == 270) { //robot facing left, so forwards adds from x
x = xPos + distance;
}
else {
System.out.println("strange, shouldn't get here");
}
if (penDown) {
//x=400; y=400;
drawLine(PenColour, xPos, yPos, x, y);
//g.drawLine(xPos,yPos,x,y);
}
//now robot has moved to the new position
xPos = x;
yPos = y;
}
//***********************************//
//Clears the image contents.
public void clear() {
Graphics g = image.getGraphics();
g.setColor(BACKGROUND_COL);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
}
//***********************************//
public void setTurtleColour(Color col) {
Graphics g = turtleDisplay.getGraphics();
g.setColor(col);
g.fillRect(0, 0, turtleDisplay.getWidth(), turtleDisplay.getHeight());
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// render the image on the panel.
g.drawImage(image, 0, 0, null);
g.drawImage(turtleDisplay, xPos-TURTLE_X_SIZE/2, yPos-TURTLE_Y_SIZE/2, null);
}
//***********//
//CONSTRUCTOR//
//***********//
public GraphicsPanel() {
//main drawing area
image = new BufferedImage(650, 400, BufferedImage.TYPE_INT_RGB);
//small image to display on top of drawing area to represent the turtle
turtleDisplay = new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB);
//set up turtle
setTurtleColour(PenColour);
// Set max size of the panel, so that is matches the max size of the image.
setMaximumSize(new Dimension(image.getWidth(), image.getHeight()));
setSize(800,400);
setVisible(true);
clear();
}