2012-03-07 16 views
1

Так что для этого класса в Java, вот мой кодРадиокнопка вопрос

import java.awt.*; 
import java.awt.event.*; 
import java.util.Random; 
import javax.swing.*; 
import javax.swing.border.*; 

public class RadioSelection extends JFrame implements ActionListener 
{ 
private ActionListener action; 
private JButton[][] button; 
private JPanel bottomPanel; 
private LineBorder lineBorder; 

private int randomRowLimit; 
private int randomColumnLimit; 
private Random random; 
private int size; 
JLabel label = new JLabel("Select the no. of Grid"); 
public RadioSelection() 
{ 
    randomRowLimit = 0; 
    randomColumnLimit = 0; 
    random = new Random(); 
    size = 0; 

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setLocationByPlatform(true); 

    lineBorder = new LineBorder(Color.BLUE.darker()); 


    JPanel topPanel = new JPanel(); 
    topPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); 

    bottomPanel = new JPanel(); 

    final JRadioButton threeSquareButton = new JRadioButton("3 X 3", false); 
    final JRadioButton fourSquareButton = new JRadioButton("4 X 4", false); 
    final JRadioButton fiveSquareButton = new JRadioButton("5 X 5", false); 

    threeSquareButton.setBorder(lineBorder); 
    fourSquareButton.setBorder(lineBorder); 
    fiveSquareButton.setBorder(lineBorder); 
    label.setFont(null); 
    action = new ActionListener() 
    { 
     public void actionPerformed(ActionEvent ae) 
     { 

      if (ae.getSource() == threeSquareButton) 
      { 
       remove(bottomPanel); 
       bottomPanel = getCenterPanel(3); 
       add(bottomPanel, BorderLayout.CENTER); 
      } 
      else if (ae.getSource() == fourSquareButton) 
      { 
       remove(bottomPanel); 
       bottomPanel = getCenterPanel(4); 
       add(bottomPanel, BorderLayout.CENTER); 
      } 
      else if (ae.getSource() == fiveSquareButton) 
      { 

       remove(bottomPanel); 
       bottomPanel = getCenterPanel(5); 
       add(bottomPanel, BorderLayout.CENTER); 
      } 


      invalidate(); // If you are using JDK 1.7 + 
      //getContentPane().revalidate(); // if you using JDK 1.6 or lower 
       repaint(); 
      } 
     }; 

    threeSquareButton.addActionListener(action); 
    fourSquareButton.addActionListener(action); 
    fiveSquareButton.addActionListener(action); 

    ButtonGroup bg = new ButtonGroup(); 
    bg.add(threeSquareButton); 
    bg.add(fourSquareButton); 
    bg.add(fiveSquareButton); 


    topPanel.add(label); 
    topPanel.add(threeSquareButton); 
    topPanel.add(fourSquareButton); 
    topPanel.add(fiveSquareButton); 

    add(topPanel, BorderLayout.PAGE_START); 

    add(bottomPanel, BorderLayout.CENTER); 

    setSize(300, 300); 
    //pack(); 
    setVisible(true); 
} 
private JPanel getCenterPanel(int size) 
{ 
    JPanel bottomPanel = new JPanel(new GridLayout(size, size)); 
    button = new JButton[size][size]; 
    this.size = size; 

    for (int row = 0; row < size; row++) 
    { 
     for (int column = 0; column < size; column++) 
     { 
      button[row][column] = new JButton(); 
      button[row][column].setBorder(lineBorder); 
      button[row][column].setMargin(new Insets(2, 2, 2, 2)); 
      button[row][column].addActionListener(this); 
      bottomPanel.add(button[row][column]); 
     } 
    } 

    randomRowLimit = random.nextInt(size); 
    randomColumnLimit = random.nextInt(size); 
    button[randomRowLimit][randomColumnLimit].setText("mouse"); 

    return bottomPanel; 
} 

public void actionPerformed(ActionEvent ae) 
{ 
    JButton button = (JButton) ae.getSource(); 

    if ((button.getText()).equals("mouse")) 
    { 
     randomRowLimit = random.nextInt(size); 
     randomColumnLimit = random.nextInt(size); 
     System.out.println("Row : " + randomRowLimit); 
     System.out.println("Column : " + randomColumnLimit); 
     button.setText(""); 
     this.button[randomRowLimit][randomColumnLimit].setText("mouse");    
    } 
    else 
    { 
    JOptionPane.showMessageDialog(this, "Catch the mouse!", "Small Game : ",      JOptionPane.ERROR_MESSAGE); 
    } 
} 

public static void main(String... args) 
{ 
    SwingUtilities.invokeLater(new Runnable() 
    { 
     public void run() 
     { 

      new RadioSelection(); 
     } 
    }); 
} 

}

Это один работает, но если вы заметили, я invalidate(); здесь. Если это revalidate();, он не будет работать. Тем не менее, моя озабоченность здесь заключается в том, когда щелкает радиокнопку (например, 3х3), кнопка не будет отображаться автоматически. Перед тем, как появятся поясные кнопки, рамку необходимо отрегулировать. Как я могу работать с этим?

+2

What/Где 3x3 и 4x4 кнопки радио? –

+1

Что вы хотите делать??!? – hurtledown

+0

Вы случайно забыли домашнюю домашнюю бирку :-) – kleopatra

ответ

3

Попробуйте свои руки этот код:

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

public class RadioSelection extends JFrame 
{ 
    private ActionListener action; 
    private JPanel bottomPanel; 
    private LineBorder lineBorder ; 

    public RadioSelection() 
    { 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setLocationByPlatform(true); 

     lineBorder = new LineBorder(Color.BLUE.darker()); 

     JPanel topPanel = new JPanel(); 
     topPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); 

     bottomPanel = new JPanel(); 

     final JRadioButton threeSquareButton = new JRadioButton("3 X 3", false); 
     final JRadioButton fourSquareButton = new JRadioButton("4 X 4", false); 

     threeSquareButton.setBorder(lineBorder); 
     fourSquareButton.setBorder(lineBorder); 

     action = new ActionListener() 
     { 
      public void actionPerformed(ActionEvent ae) 
      { 
       if (ae.getSource() == threeSquareButton) 
       { 
        remove(bottomPanel); 
        bottomPanel = getCenterPanel(3); 
        add(bottomPanel, BorderLayout.CENTER); 
       } 
       else if (ae.getSource() == fourSquareButton) 
       { 
        remove(bottomPanel); 
        bottomPanel = getCenterPanel(4); 
        add(bottomPanel, BorderLayout.CENTER); 
       } 
       revalidate(); // If you are using JDK 1.7 + 
       // getContentPane().revalidate(); // if you using JDK 1.6 or lower 
       repaint(); 
      } 
     }; 

     threeSquareButton.addActionListener(action); 
     fourSquareButton.addActionListener(action); 

     ButtonGroup bg = new ButtonGroup(); 
     bg.add(threeSquareButton); 
     bg.add(fourSquareButton); 

     topPanel.add(threeSquareButton); 
     topPanel.add(fourSquareButton); 

     add(topPanel, BorderLayout.PAGE_START); 
     add(bottomPanel, BorderLayout.CENTER); 

     setSize(300, 300); 
     setVisible(true); 
    } 

    private JPanel getCenterPanel(int size) 
    { 
     JPanel bottomPanel = new JPanel(new GridLayout(size, size)); 

     for (int row = 0; row < size; row++) 
     { 
      for (int column = 0; column < size; column++) 
      { 
       JButton button = new JButton("Button " + row + " " + column); 
       button.setBorder(lineBorder); 
       button.setMargin(new Insets(2, 2, 2, 2)); 
       bottomPanel.add(button); 
      } 
     } 

     return bottomPanel; 
    } 

    public static void main(String... args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       new RadioSelection(); 
      } 
     }); 
    } 
} 

Вот результат этого:

3 X 3 MATRIX и 4 X 4 MATRIX

Добавлен этот новый код для ответа на новую вещь:

import java.awt.*; 
import java.awt.event.*; 

import java.util.Random; 

import javax.swing.*; 
import javax.swing.border.*; 

public class RadioSelection extends JFrame implements ActionListener 
{ 
    private ActionListener action; 
    private JButton[][] button; 

    private JPanel bottomPanel; 
    private LineBorder lineBorder; 

    private int randomRowLimit; 
    private int randomColumnLimit; 
    private Random random; 
    private int size; 

    public RadioSelection() 
    { 
     randomRowLimit = 0; 
     randomColumnLimit = 0; 
     random = new Random(); 
     size = 0; 

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setLocationByPlatform(true); 

     lineBorder = new LineBorder(Color.BLUE.darker()); 

     JPanel topPanel = new JPanel(); 
     topPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); 

     bottomPanel = new JPanel(); 

     final JRadioButton threeSquareButton = new JRadioButton("3 X 3", false); 
     final JRadioButton fourSquareButton = new JRadioButton("4 X 4", false); 
     final JRadioButton fiveSquareButton = new JRadioButton("5 X 5", false); 

     threeSquareButton.setBorder(lineBorder); 
     fourSquareButton.setBorder(lineBorder); 
     fiveSquareButton.setBorder(lineBorder); 

     action = new ActionListener() 
     { 
      public void actionPerformed(ActionEvent ae) 
      { 
       if (ae.getSource() == threeSquareButton) 
       { 
        remove(bottomPanel); 
        bottomPanel = getCenterPanel(3); 
        add(bottomPanel, BorderLayout.CENTER); 
       } 
       else if (ae.getSource() == fourSquareButton) 
       { 
        remove(bottomPanel); 
        bottomPanel = getCenterPanel(4); 
        add(bottomPanel, BorderLayout.CENTER); 
       } 
       else if (ae.getSource() == fiveSquareButton) 
       { 
        remove(bottomPanel); 
        bottomPanel = getCenterPanel(5); 
        add(bottomPanel, BorderLayout.CENTER); 
       } 
       revalidate(); // If you are using JDK 1.7 + 
       // getContentPane().revalidate(); // if you using JDK 1.6 or lower 
       repaint(); 
      } 
     }; 

     threeSquareButton.addActionListener(action); 
     fourSquareButton.addActionListener(action); 
     fiveSquareButton.addActionListener(action); 

     ButtonGroup bg = new ButtonGroup(); 
     bg.add(threeSquareButton); 
     bg.add(fourSquareButton); 
     bg.add(fiveSquareButton); 

     topPanel.add(threeSquareButton); 
     topPanel.add(fourSquareButton); 
     topPanel.add(fiveSquareButton); 

     add(topPanel, BorderLayout.PAGE_START); 
     add(bottomPanel, BorderLayout.CENTER); 

     setSize(300, 300); 
     //pack(); 
     setVisible(true); 
    } 

    private JPanel getCenterPanel(int size) 
    { 
     JPanel bottomPanel = new JPanel(new GridLayout(size, size)); 
     button = new JButton[size][size]; 
     this.size = size; 

     for (int row = 0; row < size; row++) 
     { 
      for (int column = 0; column < size; column++) 
      { 
       button[row][column] = new JButton(); 
       button[row][column].setBorder(lineBorder); 
       button[row][column].setMargin(new Insets(2, 2, 2, 2)); 
       button[row][column].addActionListener(this); 
       bottomPanel.add(button[row][column]); 
      } 
     } 

     randomRowLimit = random.nextInt(size); 
     randomColumnLimit = random.nextInt(size); 
     button[randomRowLimit][randomColumnLimit].setText("X"); 

     return bottomPanel; 
    } 

    public void actionPerformed(ActionEvent ae) 
    { 
     JButton button = (JButton) ae.getSource(); 

     if ((button.getText()).equals("X")) 
     { 
      randomRowLimit = random.nextInt(size); 
      randomColumnLimit = random.nextInt(size); 
      System.out.println("Row : " + randomRowLimit); 
      System.out.println("Column : " + randomColumnLimit); 
      button.setText(""); 
      this.button[randomRowLimit][randomColumnLimit].setText("X");    
     } 
     else 
     { 
      JOptionPane.showMessageDialog(this, "Please Click on X Mark to follow it.", "Small Game : ", JOptionPane.ERROR_MESSAGE); 
     } 
    } 

    public static void main(String... args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       new RadioSelection(); 
      } 
     }); 
    } 
} 
+0

удар только один upvote :-) +1 – mKorbel

+0

, спасибо вам за это.это тот, который мне действительно нужен. Как я могу поблагодарить вас за это. – shielomarie

+0

@shielomarie: Ваше приветствие и держите Smiling :-) –

2

Я не уверен, что понял вопрос или код, но я ожидал увидеть ActionListener на кнопку 3x3, что позволит создать массив JRadioButton экземпляров с помощью метода, который что-то вроде этого:

private JRadioButton [][] createRadioButtonArray(int squareSize) { 
    JRadioButton [][] arrayOfButtons = new JRadioButton[squareSize][squareSize]; 
    for (int i = 0; i < squareSize; ++i) { 
     for (int j = 0; j < squareSize; ++j) { 
      arrayOfButtons[i][j] = new JRadioButton("button" + i + "," + j,false); 
     } 
    } 
    return arrayOfButtons; 
} 
+0

Да, это то, что им нужно , спасибо за помощь. Извините, если вы не можете понять мой вопрос, я не очень хорошо по-английски. Хм, что это за квадрат? – shielomarie

+0

Вы имеете в виду "squareSize"? Это размер массива: 3 для вашего случая 3x3; 4 для вашего случая 4x4; и т. д. Я бы предпочел, чтобы вы приняли ответ на вашу благодарность. – duffymo

+0

Что такое импорт? Необходимость в этом приложении? Большое вам спасибо! – shielomarie

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