2017-02-16 35 views
0

Мне сложно определить, как я могу изменить цвет компонента краски в DrawPanel.Как изменить компонент paint в JPanel с панели кнопок в java

Метод, который нам нужно использовать, заключается в том, что цвет компонента краски можно изменить с помощью ButtonPanel.

Проблема в том, что я не могу найти способ заставить обработчика распознать панель и изменить ее цвет.

Как изменить paintcomponent в JPanel из кнопок панели в Java

main.java

import javax.swing.SwingUtilities; 

public class main { 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
       public void run() { 
       new Window(); 
      }   
     });  
    } 
} 

Window.java

import javax.swing.JFrame; 
import java.awt.BorderLayout; 
import java.awt.Dimension; 

public class Window extends JFrame { 

    public Window() { 
     // `super ' calls a function inherited from the parent class (JFrame) 
     super(); 
     setTitle("Callbacks"); 
     setSize (new Dimension(420, 350)); 

     // Make sure the window appears in the middle of your screen 
     setLocationRelativeTo(null); 

     // Determines what should happen when the frame is closed 
     setDefaultCloseOperation (EXIT_ON_CLOSE); 

     // Chooses a certain layout type for the elements in this frame 
     getContentPane().setLayout (new BorderLayout()); 

     // TODO : add elements to the content pane 
     DrawPanel dp = new DrawPanel(); 
     ButtonPanel bp = new ButtonPanel(); 

     // Places the DrawPanel in the center of the frame 
     getContentPane(). add (dp , BorderLayout . CENTER); 
     // Places the ButtonPanel in the top of the frame 
     getContentPane(). add (bp , BorderLayout . NORTH); 


     // Set the window to visible ! Yup ... This is necessary 
     setVisible (true); 
    } 
} 

DrawPanel.java

import java.awt.Color; 
import java.awt.Graphics; 

import javax.swing.*; 

public class DrawPanel extends JPanel { 

    private Color color; 

    public DrawPanel(){ 
     super(); 
     color = Color.BLACK ; 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.setColor(getColor()); 
     g.fillRect(100 , 30, 200 , 200); 
    } 

} 

ButtonPanel.java

import javax.swing.JButton; 
import javax.swing.JPanel; 

public class ButtonPanel extends JPanel { 


    public ButtonPanel() { 
     super(); 
     // Add a button to the panel . The argument to the JButton constructor 
     // will become the text on the button . 
     JButton b = new JButton ("Change color!"); 
     JButton c = new JButton ("Test"); 
     add (b); 
     add (c); 
     b.addActionListener(new InputHandler()); 

    } 
} 

InputHandler

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Random; 

import com.sun.prism.paint.Color; 

public class InputHandler implements ActionListener { 

    public InputHandler() { 
     // TODO Auto-generated constructor stub 
    } 

    public void actionPerformed (ActionEvent e) { 
     // TODO : add code here that will 
     // be ran when the button is clicked 
    } 
} 

Надеется, что вы, ребята, можете мне помочь или отправить меня в правильном направлении.

+1

Основная проблема заключается в том, что код расширяет компоненты, когда нет реальной необходимости делать это. Это относится как к «Window», так и к ButtonPanel (хотя существует логический пример расширения «DrawPanel»). –

+0

Да, это часть задания, над которым я работаю. Когда я искал ответы, они тоже не распространялись. – Danton

+0

Свяжите два вместе через взаимный договор (то есть «интерфейс»), который представляет данные, которые вы хотите разделить, предоставить шаблон наблюдателя в контракте, чтобы заинтересованные стороны могли следить за изменениями данных и сами обновлять – MadProgrammer

ответ

0

сделать их друзьями друг с другом так, что Listener будет знать Panel:

// Window 
DrawPanel dp = new DrawPanel(); 
ButtonPanel bp = new ButtonPanel (dp); // pass panel to button 

затем:

public class ButtonPanel extends JPanel {  
    public ButtonPanel (DrawPanel d) { 
     super(); 
     // Add a button to the panel . The argument to the JButton constructor 
     // will become the text on the button . 
     JButton b = new JButton ("Change color!"); 
     JButton c = new JButton ("Test"); 
     add (b); 
     add (c); 
     b.addActionListener(new InputHandler(d)); // pass panel to listener  
    } 
} 

и:

public class InputHandler implements ActionListener { 
    DrawPanel d; 
    public InputHandler(DrawPanel d) { 
     this.d = d; 
    }  
    public void actionPerformed (ActionEvent e) { 
     d.setColor(Color.BLUE); // whatever 
     d.repaint(); // force painting 
    } 
} 

затем:

public class DrawPanel extends JPanel { 
    private Color color;  
    public DrawPanel(){ 
     super(); 
     color = Color.BLACK ; 
    } 
    public void setColor(Color c) { 
     this.color = c; 
    } 
    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.setColor(getColor()); 
     g.fillRect(100 , 30, 200 , 200); 
    }  
} 
+0

Большое спасибо ! Последний вопрос относительно этого проекта, можно ли изменить форму нажатием кнопки? Должен ли я использовать компонент краски? – Danton

+0

Конечно, тогда форма должна быть описана снаружи 'paintComponent' –