Как я могу изменить цвет моих линий в графическом интерфейсе рисования
Эй, у меня много проблем с тем, чтобы мои кнопки на панели инструментов изменили цвет линий, которые я рисую. Вот мой код:
public class PaintingGUI {
private static final int FRAME_WIDTH = 960;
private static final int FRAME_HEIGHT = 640;
private final static String NEWLINE = System.lineSeparator();
private JTextArea textArea = new JTextArea();
class MyButtonListener extends JPanel implements MouseListener,
MouseMotionListener, ActionListener {
private int mouseX1 = -1; // the mouse Coordinates when pressed
private int mouseY1 = -1;
private int mouseX2 = -1; // mouse coordinates when released
private int mouseY2 = -1;
Color c;
JButton red, green, blue, yellow, orange, black, pink, purple, dot, line, square, circle, ellipse, text;
public MyButtonListener() {
setOpaque(false);
}
public MyButtonListener(JButton red, JButton green, JButton blue, JButton yellow, JButton orange, JButton black, JButton pink, JButton purple,
JButton dot, JButton line, JButton square, JButton circle, JButton ellipse, JButton text){
// Need to communicate references to the buttons in this class
this.red = red;
this.green = green;
this.blue = blue;
this.yellow = yellow;
this.orange = orange;
this.black = black;
this.pink = pink;
this.purple = purple;
this.dot = dot;
this.line = line;
this.square = square;
this.circle = circle;
this.ellipse = ellipse;
this.text = text;
}
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
if(source == red) {
c = Color.RED;
System.out.println(c);
repaint();
}
if(source == green) {
c = Color.GREEN;
System.out.println("Colour is green");
repaint();
}
if(source == blue) {
c = Color.BLUE;
System.out.println("Colour is blue");
repaint();
}
if(source == yellow) {
c = Color.YELLOW;
System.out.println("Colour is yellow");
repaint();repaint();
}
if(source == orange) {
c = (new Color(255, 137, 0));
System.out.println("Colour is orange");
}
if(source == black) {
c = Color.BLACK;
System.out.println("Colour is black");
}
if(source == pink) {
c = Color.PINK;
System.out.println("Colour is pink");
}
if(source == purple) {
c = (new Color(153, 51, 255));
System.out.println("Colour is purple");
}
if(source == dot) {
}
if(source == line) {
}
if(source == square) {
}
if(source == circle) {
}
if(source == ellipse) {
}
if(source == text) {
}
}
@Override
public void mouseClicked(MouseEvent event)
{
int x = event.getX();
int y = event.getY();
}
@Override
public void mousePressed(MouseEvent event)
{
mouseX1 = event.getX();
mouseY1 = event.getY();
}
@Override
public void mouseReleased(MouseEvent event)
{
mouseX2 = event.getX();
mouseY2 = event.getY();
// trigger a call to paintComponent
repaint();
}
@Override
public void mouseDragged(MouseEvent event)
{
int x = event.getX();
int y = event.getY();
}
@Override
public void mouseEntered(MouseEvent event)
{
System.out.println("Enter");
}
@Override
public void mouseExited(MouseEvent event)
{
System.out.println("Exit");
}
@Override
public void mouseMoved(MouseEvent event)
{
int x = event.getX();
int y = event.getY();
}
@Override
public void paintComponent(Graphics g)
{
if (mouseX1 < 0 || mouseY1 < 0)
return;
Graphics2D g2 = (Graphics2D) g;
System.out.println("Drawing a line");
g2.setColor(c);
g2.drawLine(mouseX1, mouseY1, mouseX2, mouseY2);
}
}
public PaintingGUI createToolBar() {
JFrame frame = new JFrame("Drawing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawingMenu meMenu = new DrawingMenu();
frame.setJMenuBar(meMenu.createMenuBar());
MyButtonListener panel = new MyButtonListener();
panel.addMouseListener(panel);
panel.addMouseMotionListener(panel);
frame.setContentPane(panel);
panel.setLayout(new BorderLayout());
JToolBar toolBar = new JToolBar("Drag me!");
panel.add(toolBar, BorderLayout.PAGE_END);
// Make some buttons. Here we will paste an image icon on each
JButton red = new JButton("red");
red.setBackground(Color.RED);
red.setContentAreaFilled(false);
red.setOpaque(true);
JButton green = new JButton("gre");
green.setBackground(Color.GREEN);
green.setContentAreaFilled(false);
green.setOpaque(true);
JButton blue = new JButton("blu");
blue.setBackground(Color.BLUE);
blue.setContentAreaFilled(false);
blue.setOpaque(true);
JButton yellow = new JButton("yel");
yellow.setBackground(Color.YELLOW);
yellow.setContentAreaFilled(false);
yellow.setOpaque(true);
JButton orange = new JButton("ora");
orange.setBackground(new Color(255, 137, 0));
orange.setContentAreaFilled(false);
orange.setOpaque(true);
JButton black = new JButton("bla");
black.setBackground(Color.BLACK);
black.setContentAreaFilled(false);
black.setOpaque(true);
JButton pink = new JButton("pin");
pink.setBackground(Color.PINK);
pink.setContentAreaFilled(false);
pink.setOpaque(true);
JButton purple = new JButton("pur");
purple.setBackground(new Color(153, 51, 255));
purple.setContentAreaFilled(false);
purple.setOpaque(true);
ImageIcon temp = new ImageIcon("C:\\Java Programs\\drawing\\dot.JPG");
Image img = temp.getImage();
Image newimg = img.getScaledInstance(17,16, java.awt.Image.SCALE_SMOOTH);
ImageIcon dotpic = new ImageIcon(newimg);
JButton dot = new JButton(dotpic);
temp = new ImageIcon("C:\\Java Programs\\drawing\\line.JPG");
img = temp.getImage();
newimg = img.getScaledInstance(17,16, java.awt.Image.SCALE_SMOOTH);
ImageIcon linepic = new ImageIcon(newimg);
JButton line = new JButton(linepic);
temp = new ImageIcon("C:\\Java Programs\\drawing\\square.JPG");
img = temp.getImage();
newimg = img.getScaledInstance(17,16, java.awt.Image.SCALE_SMOOTH);
ImageIcon squarepic = new ImageIcon(newimg);
JButton square = new JButton(squarepic);
temp = new ImageIcon("C:\\Java Programs\\drawing\\circle.PNG");
img = temp.getImage();
newimg = img.getScaledInstance(17,16, java.awt.Image.SCALE_SMOOTH);
ImageIcon circlepic = new ImageIcon(newimg);
JButton circle = new JButton(circlepic);
temp = new ImageIcon("C:\\Java Programs\\drawing\\ellipse.JPG");
img = temp.getImage();
newimg = img.getScaledInstance(17,16, java.awt.Image.SCALE_SMOOTH);
ImageIcon ellipsepic = new ImageIcon(newimg);
JButton ellipse = new JButton(ellipsepic);
temp = new ImageIcon("C:\\Java Programs\\drawing\\text.PNG");
img = temp.getImage();
newimg = img.getScaledInstance(17,16, java.awt.Image.SCALE_SMOOTH);
ImageIcon textpic = new ImageIcon(newimg);
JButton text = new JButton(textpic);
// Add buttons to toolbar
toolBar.add(red);
toolBar.add(green);
toolBar.add(blue);
toolBar.add(yellow);
toolBar.add(orange);
toolBar.add(black);
toolBar.add(pink);
toolBar.add(purple);
toolBar.add(dot);
toolBar.add(line);
toolBar.add(square);
toolBar.add(circle);
toolBar.add(ellipse);
toolBar.add(text);
// Set a tooltip text for each button
red.setToolTipText("Colour is red");
green.setToolTipText("Colour is green");
blue.setToolTipText("Colour is blue");
yellow.setToolTipText("Colour is yellow");
orange.setToolTipText("Colour is orange");
black.setToolTipText("Colour is black");
pink.setToolTipText("Colour is pink");
purple.setToolTipText("Colour is purple");
dot.setToolTipText("Freehand line");
line.setToolTipText("Draw a straight line");
square.setToolTipText("Draw a Square");
circle.setToolTipText("draw a circle");
ellipse.setToolTipText("Draw an ellipse");
text.setToolTipText("Write something");
// Create an instance of the demo class
PaintingGUI demo = new PaintingGUI();
// Now we need to create an instance of our Button Listener class
MyButtonListener listener =
demo.new MyButtonListener(red, green, blue, yellow, orange, black, pink, purple, dot, line, square, circle, ellipse, text);
// Register action listener defined in the listener class
red.addActionListener(listener);
green.addActionListener(listener);
blue.addActionListener(listener);
yellow.addActionListener(listener);
orange.addActionListener(listener);
black.addActionListener(listener);
pink.addActionListener(listener);
purple.addActionListener(listener);
dot.addActionListener(listener);
line.addActionListener(listener);
square.addActionListener(listener);
circle.addActionListener(listener);
ellipse.addActionListener(listener);
text.addActionListener(listener);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setVisible(true);
return demo;
}
}
Я перепробовал много разных подходов и везде искал решение, я новичок в Java, поэтому любая помощь будет оценена.
1 ответ
Вы создали два разных экземпляра MyButtonListener. Один, который используется в качестве слушателя JPanel и мыши, а другой - в качестве слушателя действия, добавляемого к кнопкам.
Когда кнопка нажата, второй экземпляр обрабатывает ее и правильно устанавливает ее цвет, однако первый экземпляр MyButtonListener, который выполняет рисование, все равно будет иметь цвет NULL.
Попробуйте использовать тот же экземпляр MyButtonListener. Вам нужно будет использовать второй конструктор, но слегка изменить его, чтобы он вызывал setOpaque(true) как конструктор no arg.