Как использовать разные цвета для разных форм - PullRequest
0 голосов
/ 04 июня 2018

Я пытаюсь использовать разные цвета для другой формы при щелчке мышью.Как я могу это сделать?

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.sql.*;
import java.util.Random;
import java.awt.geom.*;

public class DrawMap extends JFrame{
//private JLabel LabelTitle,MapNo;
//private JTextField MapField;
private final JButton Draw,Shape,Load,Back,Logout;
private final JPanel DrawPanel;
private String UserName,Password,City;
public boolean check;
private int r,g,b;
private int flag =0;
private Shape shape;
private final int w = 100;
private final int h = 200;

private Object lastButtonPressed;

public DrawMap(String UserName,String Password,String City){

setTitle("Draw Map");
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Random p = new Random();
r = p.nextInt(255);
g = p.nextInt(255);
b = p.nextInt(255);

this.UserName = UserName;
this.Password = Password;
this.City   = City;

final Container contentPane = getContentPane();

JPanel buttonPanel = new JPanel();
JPanel buttonPanel1 = new JPanel();

Draw = new JButton("Draw");
Shape = new JButton("Shape");
Load = new JButton("Load");
Back = new JButton("Back");
Logout = new JButton("Logout");

buttonPanel.add(Draw);
buttonPanel.add(Shape);
buttonPanel1.add(Load);
buttonPanel1.add(Back);
buttonPanel1.add(Logout);

contentPane.add(buttonPanel, BorderLayout.NORTH);
contentPane.add(buttonPanel1, BorderLayout.SOUTH);

DrawPanel = new JPanel(){
      public void paintComponent(Graphics g){

  Graphics2D g2d=(Graphics2D) g;
  Font font = new Font("Times New Roman", Font.BOLD, 16);
  g2d.setFont(font);
  g2d.drawString("Give Your Map ID And Click On Draw", 50, 100);

  if(shape != null){
      g2d.setColor(Color.BLACK);
      g2d.fill(shape);
  }

  if(check==true){
      String query = "SELECT `Room_Length`,`Room_Width` FROM `map` WHERE `map`.`UserName`='"+DrawMap.this.UserName+"'";
      Connection con = null;
      Statement stm = null;
      ResultSet rs = null;
      System.out.println(query);
      try{
          Class.forName("com.mysql.jdbc.Driver");
          con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Letsgo2","root","");
          stm = con.createStatement();
          rs = stm.executeQuery(query);

          while(rs.next()){
              int Room_Length = rs.getInt("Room_Length");
              int Room_Width = rs.getInt("Room_Width");

              int x1=30,x2=30;
              int y1=280,y2=280;

              for(int i=0;i<Room_Width;i++){
                  y1=y1+20;
                  y2=y2+20;
                  g.drawLine(50,y1,270,y2);
                }
                for(int j=0;j<Room_Length;j++){
                    x1=x1+20;
                    x2=x2+20;
                    g.drawLine(x1,300,x2,480);
                }
            }
        }
        catch(Exception ex){
            System.out.println("Exception : " +ex.getMessage());
        }
        finally{
            try{
                if(stm!=null){
                    stm.close();
                    System.out.println("Statement Closed");
                }
                if(con!=null){
                     con.close();
                     System.out.println("Connection Closed");
                }
            }
            catch(Exception ex){}
        }
    }
}
};

contentPane.add(DrawPanel, BorderLayout.CENTER);

final ActionListener buttonPressed = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            lastButtonPressed = event.getSource();
        }
    };

    Draw.addActionListener(buttonPressed);
    Shape.addActionListener(buttonPressed);
    Load.addActionListener(buttonPressed);
    Back.addActionListener(buttonPressed);
    Logout.addActionListener(buttonPressed);

    contentPane.addMouseListener(new MouseAdapter() {

        public void mouseClicked(MouseEvent e) {

            int x = e.getX();
            int y = e.getY();

            if(lastButtonPressed == Draw){
                check = true;
                DrawPanel.repaint();
            } 
            else if(lastButtonPressed == Shape){
                shape = new Rectangle2D.Double(x, y, w, w);
                echo("Square",x,y);
            } 
            else if (lastButtonPressed == Load){
                shape = new Rectangle2D.Double(x, y, w, w);
                echo("Square",x,y);

            } 
            else if (lastButtonPressed == Back){
                UserHome ush = new UserHome(UserName,Password,City);
                ush.setVisible(true);
                DrawMap.this.setVisible(false);
            } 
            else if (lastButtonPressed == Logout){
                Login L = new Login();
                L.setVisible(true);
                DrawMap.this.setVisible(false);
            } 

            DrawPanel.repaint();


        }

        private void echo(String shape, int x, int y){
            System.out.println(shape + " added at: " + x + "," + y);
        }

    });

  }

}

1 Ответ

0 голосов
/ 04 июня 2018

Я добавил цветовую переменную с именем "color" сверху:

    private  Color color=Color.BLACK;
    private final JButton Draw,Shape,Load,Back,Logout;

У вас уже определены переменные r, g, b.Я закрыл следующие строки генерации случайных чисел, потому что они вызывают застревание цвета.

    Random p = new Random();
    //r = p.nextInt(255);
    //g = p.nextInt(255);
    //b = p.nextInt(255);

Я изменил g2d.setColor, чтобы использовать переменную "color", которую я определил ранее.

    if(shape != null){
       g2d.setColor(color);
       g2d.fill(shape);
    }

Наконец, я переместил строки генерации случайных чисел в раздел, касающийся кнопки «Форма» внутри функции щелчка мыши, и добавил строку, чтобы создать новый цвет и присвоить его переменной «color»:

    else if(lastButtonPressed == Shape){
         shape = new Rectangle2D.Double(x, y, w, w);
         echo("Square",x,y);
         r = p.nextInt(255);
         g = p.nextInt(255);
         b = p.nextInt(255);
         color = new Color(r, g, b);
    }

Когда я выполнил вашкод после этих изменений, я могу наблюдать различные цветные фигуры / прямоугольники нарисованы.

...