2013-10-07 3 views
3

Ниже представлен проект, над которым я работаю.Нарисуйте черную линию в java

Проблема заключается в методе Plotline(). Этот метод принимает три переменные и должен использовать эти переменные для рисования черной линии, которая не должна выходить за пределы ширины и длины JLable.

Я пытаюсь сделать это в цикле for, но я не знаю, как установить связь между переменными и объектами в этом проекте.

Проект проходит через другой класс, который NewJFrame.java

import java.awt.Color; 
import java.awt.image.BufferedImage; 
import javax.swing.ImageIcon; 
import javax.swing.JLabel; 

public class Image { 
    private JLabel   label; 
    private BufferedImage image; 
    private Color   color; 
    private Color[][]  color_array; 
    private Color[][]  temp_array; 

public Image(JLabel _label, Color _color) 
{ 
    label = _label; 
    image   = new bufferedImage(label.getHeight(),label.getWidth(),BufferedImage.TYPE_INT_ARGB); 
    color_array  = new Color[label.getWidth()][label.getHeight()];  
    color = _color; 
    Background(); 
    Draw(); 
} 

public void Background() 
{ 
    for(int i = 0; i < color_array.length ; i++) 
     for(int j = 0; j < color_array[i].length; j++) 
      color_array[i][j] = color; 

} 
public void Plotline(int _x1, int _x2, int _y) 
{ 
    Color tmp_color = new Color(0); 
    for(int i=0; i <color_array.length-1; i++){ 
     Draw(); 
    } 

} 

public void Draw() 
{ 
    for(int i = 0; i < color_array.length ; i++) 
     for(int j = 0; j < color_array.length; j++) 
      image.setRGB(i, j, color_array[i][j].getRGB()); 
    label.setIcon(new ImageIcon(image)); 
    label.repaint(); 
} 
} 
+3

Вы уже задали очень похожий вопрос о переполнении стека, и он был закрыт для его низкого качества. Такие вопросы не соответствуют теме Programmers.SE. –

+0

может подняться, подскажите, как улучшить качество моего вопроса? –

+0

Я отредактировал эту тему. это нормально? –

ответ

2

Вы правы. Связь между вашими переменными в разных методах отсутствует. Они должны подключаться через переменную параметра или класса. На самом деле это не должно быть так сложно. Одного метода достаточно, чтобы нарисовать вашу линию. Вот фиксированный код:

import java.awt.Color; 
import java.awt.image.BufferedImage; 

import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 

public class Test { 

    public Test() { 
     JFrame frame = new JFrame("Test"); 
     JLabel label = new JLabel("Hello, World!"); 
     frame.add(label); 

     frame.setSize(300, 200); 
     frame.setVisible(true); 

     new Image(label, Color.BLACK).Plotline(10, 90, 100); 
     frame.repaint(); 
    } 

    public static void main(String a[]) { 
     new Test(); 
    } 
} 

///
class Image { 
    private JLabel label; 
    private BufferedImage image; 
    private Color color; 
    private Color[][] color_array; 
    private Color[][] temp_array; 

    public Image(JLabel _label, Color _color) { 
     label = _label; 
     image = new BufferedImage(label.getHeight(), label.getWidth(), 
       BufferedImage.TYPE_INT_ARGB); 
     color_array = new Color[label.getWidth()][label.getHeight()]; 
     color = _color; 
     Background(); 
    } 

    public void Background() { 
     for (int i = 0; i < color_array.length; i++) { 
      for (int j = 0; j < color_array[i].length; j++) { 
       color_array[i][j] = color; 
      } 
     } 
    } 

    public void Plotline(int _x1, int _x2, int _y) { 
     int black_color = new Color(0).getRGB(); 
     for (int i = _x1; i < color_array.length - 1 && i < _x2; i++) { 
      if (_y >= 0 && _y < color_array[i].length) 
       image.setRGB(i, _y, black_color); 
     } 
     label.setIcon(new ImageIcon(image)); 
     label.repaint(); 
    } 
} 
+0

Спасибо Алекс за ваш ответ. Но я подумал, что поскольку color_array находится внутри класса Image, он называется переменной класса. Не правда ли? –

+0

Правильно. И у вас есть эти переменные. Вы просто не использовали их. Вы сделали это правильно в методе Фонового. Но ваши Draw и PlotLine не используют их. Особенно для внесения изменений в линию. – Alex

+0

Хорошо. Большое спасибо. Это была большая помощь. –

Смежные вопросы