Как нарисовать пунктирную линию на белом фоне в JLabel? - Java
Формулировка задачи:
Хочу нарисовать пунктирную линию в JPanel. Однако рисовать прямо на JPanel не советуют (Кстати почему?). Говорят лучше на JPanel кинуть JLabel c нарисованным BufferedImage.
Я попытался:
В итоге получилось вот это(см. рисунок.jpg) на черном фоне/
Как сделать чтобы пунктирная линия была на белом фоне?
Листинг программы
- public class MainFrame extends JFrame {
- ... // метод main и т.п.
- public MainFrame() {
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setBounds(100, 100, 800, 800);
- contentPane = new JPanel();
- contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
- setContentPane(contentPane);
- contentPane.setLayout(null);
- JPanel menuPanel = new JPanel();
- menuPanel.setBackground(Color.LIGHT_GRAY);
- menuPanel.setBounds(10, 11, 250, 751);
- contentPane.add(menuPanel);
- JPanel gamePanel = new JPanel();
- gamePanel.setBackground(Color.WHITE);
- gamePanel.setBounds(270, 11, 512, 751);
- contentPane.add(gamePanel);
- gamePanel.setLayout(null);
- ImageIcon img = new ImageIcon(getImage());
- JLabel label = new JLabel(img);
- label.setForeground(Color.WHITE);
- label.setBounds(0, 0, 512, 751);
- gamePanel.add(label);
- }
- public BufferedImage getImage(){
- BufferedImage bi = new BufferedImage(gamePanel.getWidth(), gamePanel.getHeight() , BufferedImage.TYPE_INT_RGB);
- Graphics2D g2 = bi.createGraphics();
- g2.setColor(Color.red);
- float[] dashl = {5,5};
- BasicStroke pen = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_BEVEL,10,dashl,0);
- g2.setStroke(pen);
- g2.drawLine(0, 0, gamePanel.getWidth(), gamePanel.getHeight());
- return bi;
- }
- }
Решение задачи: «Как нарисовать пунктирную линию на белом фоне в JLabel?»
textual
Листинг программы
- public class ImageLabel extends JLabel {
- private int width, height;
- public ImageLabel(int width, int height){
- super("label");
- this.width = width;
- this.height = height;
- }
- @Override
- public void paint(Graphics g) {
- super.paint(g);
- Graphics2D f = (Graphics2D) g;
- f.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, new float[]{10f, 5f}, 0f));
- f.setColor(Color.RED);
- f.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- f.drawLine(0, 0, 200, 300);
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д