2015-11-15 4 views
1

Так вот мой код, который отображает 9x9 сетку:Рисование линии в определенной точке в JFrame

import javax.swing.*; 
import java.awt.*; 

public class SudokuGrid extends JFrame { 

private static final int ROWS = 9; 
private static final int COLUMNS = 9; 
int fontSize = 30; 

public static void main(String[] args) { 

    SudokuGrid makeSudokuGrid = new SudokuGrid(); 

} // end of main 

// constructor SudokuGrid 
public SudokuGrid() { 

    JTextField[][] inputBoxes = new JTextField[ROWS][COLUMNS]; 
    Font font = new Font("Helvetica", Font.BOLD, fontSize); 

    setLayout(new GridLayout(ROWS, COLUMNS)); 
    // set frame size 
    setSize(400, 400); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    // outer loop to create the rows 
    for (int rows = 0 ; rows < ROWS ; rows++) { 

    // inner loop to create the columns 
    for (int columns = 0 ; columns < COLUMNS ; columns++) { 

     // make text fields empty 
     inputBoxes[rows][columns] = new JTextField(""); 
     // add text fields to the frame 
     add(inputBoxes[rows][columns]); 
     // center text in each text box 
     inputBoxes[rows][columns].setHorizontalAlignment(JTextField.CENTER); 
     // apply font to each text box 
     inputBoxes[rows][columns].setFont(font); 

    } // end of columns loop 

    } // end of rows loop 

    // make frame visible 
    getContentPane().setBackground(Color.RED); 
    setVisible(true); 

} // end of constructor SudokuGrid 

} // end of class SudokuGrid 

То, что я пытаюсь сделать, это нарисовать линию каждый третий ряд. Поэтому в каждом третьем текстовом поле должна быть толстая строка, охватывающая все столбцы. Надеюсь, это имеет смысл.

Любая помощь очень ценится. Спасибо!

+0

Используйте 'LineBorder', использовать [' JSeparator'] (https://docs.oracle.com/javase/tutorial/uiswing/components/separator.html), написать компонент, который предназначен для рисования линии – MadProgrammer

ответ

3

Простой ответ, GridLayout не собирается делать то, что вы хотите, это просто не достаточно гибкой, а ...

Вы могли бы ...

Изменить менеджер компоновки и сделать использование из JSeparator

JSeparator

import java.awt.EventQueue; 
import java.awt.Font; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JSeparator; 
import javax.swing.JTextField; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class SudokuGrid { 

    public static void main(String[] args) { 
     new SudokuGrid(); 
    } 

    public SudokuGrid() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public static class TestPane extends JPanel { 

     private static final int ROWS = 9; 
     private static final int COLUMNS = 9; 
     int fontSize = 30; 

     public TestPane() { 
      JTextField[][] inputBoxes = new JTextField[ROWS][COLUMNS]; 
      Font font = new Font("Helvetica", Font.BOLD, fontSize); 

      setLayout(new GridBagLayout()); 

      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.fill = GridBagConstraints.BOTH; 
      gbc.weightx = 1; 
      gbc.weighty = 1; 
      gbc.gridy = 0; 

      GridBagConstraints split = new GridBagConstraints(); 
      split.fill = GridBagConstraints.BOTH; 
      split.weightx = 1; 
      split.gridx = 0; 
      split.gridwidth = GridBagConstraints.REMAINDER; 

      // outer loop to create the rows 
      for (int rows = 0; rows < ROWS; rows++) { 

       gbc.gridy++; 
       // inner loop to create the columns 
       for (int columns = 0; columns < COLUMNS; columns++) { 

        gbc.gridx = columns; 

        // make text fields empty 
        inputBoxes[rows][columns] = new JTextField(1); 
        // add text fields to the frame 
        add(inputBoxes[rows][columns], gbc); 
        // center text in each text box 
        inputBoxes[rows][columns].setHorizontalAlignment(JTextField.CENTER); 
        // apply font to each text box 
        inputBoxes[rows][columns].setFont(font); 

       } // end of columns loop 

       if ((rows + 1) % 3 == 0) { 
        System.out.println("Split"); 
        split.gridy = gbc.gridy + 1; 
        gbc.gridy += 2; 
        JSeparator sep = new JSeparator(JSeparator.HORIZONTAL); 
        add(sep, split); 
       } 

      } // end of rows loop 
     } 

    } 

} 

Вы могли бы ...

Сделать свой собственный "раздвоение" компонент за счет использования пользовательских живописи

Custom Split

public static class HorizontalSplit extends JPanel { 

    public HorizontalSplit() { 
     setOpaque(false); 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     return new Dimension(0, 3); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2d = (Graphics2D) g.create(); 
     int y = (getHeight() - 3)/2; 
     BasicStroke stroke = new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); 
     g2d.setStroke(stroke); 
     g2d.drawLine(0, y, getWidth(), y); 
     g2d.dispose(); 
    } 

} 

Что бы просто заменить JSeparator ...

if ((rows + 1) % 3 == 0) { 
    System.out.println("Split"); 
    split.gridy = gbc.gridy + 1; 
    gbc.gridy += 2; 
    JPanel sep = new HorizontalSplit(); 
    add(sep, split); 
} 

Вы могли бы ...

Используйте составную компоновку и MatteLayout ...

Compound Layout

import java.awt.Color; 
import java.awt.EventQueue; 
import java.awt.Font; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.GridLayout; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 
import javax.swing.border.MatteBorder; 

public class SudokuGrid { 

    public static void main(String[] args) { 
     new SudokuGrid(); 
    } 

    public SudokuGrid() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public static class TestPane extends JPanel { 

     private static final int ROWS = 9; 
     private static final int COLUMNS = 9; 
     int fontSize = 30; 

     public TestPane() { 
      JTextField[][] inputBoxes = new JTextField[ROWS][COLUMNS]; 
      Font font = new Font("Helvetica", Font.BOLD, fontSize); 

      setLayout(new GridBagLayout()); 

      GridBagConstraints groupContraint = new GridBagConstraints(); 
      groupContraint.fill = GridBagConstraints.BOTH; 
      groupContraint.weightx = 1; 
      groupContraint.weighty = 1; 
      groupContraint.gridwidth = GridBagConstraints.REMAINDER; 

      JPanel group = new JPanel(new GridLayout(3, COLUMNS)); 
      group.setBorder(new MatteBorder(0, 0, 1, 0, Color.BLACK)); 

      // outer loop to create the rows 
      for (int rows = 0; rows < ROWS; rows++) { 

       // inner loop to create the columns 
       for (int columns = 0; columns < COLUMNS; columns++) { 

        // make text fields empty 
        inputBoxes[rows][columns] = new JTextField(1); 
        // add text fields to the frame 
        group.add(inputBoxes[rows][columns]); 
        // center text in each text box 
        inputBoxes[rows][columns].setHorizontalAlignment(JTextField.CENTER); 
        // apply font to each text box 
        inputBoxes[rows][columns].setFont(font); 

       } // end of columns loop 

       if ((rows + 1) % 3 == 0) { 
        add(group, groupContraint); 
        group = new JPanel(new GridLayout(3, COLUMNS)); 
        group.setBorder(new MatteBorder(0, 0, 1, 0, Color.BLACK)); 
       } 

      } // end of rows loop 
     } 

    } 

} 
+0

Это замечательно, спасибо! – Lushmoney

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