sieve using java - java

My friend has given me a practice problem regarding prime number. Numbers 1 to n needs to be displayed in a new window. I also can't figure out on how I can use the input I got from panel1 to panel2. I'm very new to GUI since I haven't gone there when I studied Java a few years back. Hope you can help!
I haven't done much with the GUI since I don't really know where to start, but I've watched youtube videos and have gone through many sites on how to start with a GUI. Here's what I have done:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sieve
{
private JPanel contentPane;
private MyPanel input;
private MyPanel2 sieve;
private void displayGUI()
{
JFrame frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
input = new MyPanel(contentPane);
sieve = new MyPanel2();
contentPane.add(input, "Input");
contentPane.add(sieve, "Sieve of Erasthoneses");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JTextField text;
private JLabel label1;
private JButton OK;
private JButton cancel;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
label1 = new JLabel ("Enter a number from 1 to n:");
text = new JTextField(1000);
OK = new JButton ("OK");
cancel = new JButton ("Cancel");
setPreferredSize (new Dimension (500, 250));
setLayout (null);
text.setBounds (145, 50, 60, 25);
OK.setBounds (450, 30, 150, 50);
cancel.setBounds (250, 30, 150, 50);
OK.setSize(315, 25);
OK.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add (text);
add (label1);
add (OK);
add (cancel);
}
}
class MyPanel2 extends JPanel {
private JFrame frame;
private JLabel label;
JLabel label1;
public MyPanel2()
{
frame = new JFrame("Sieve of Eratosthenes");
label = new JLabel("The Prime numbers from 2 to " + num + " are");
num1 = num;
boolean[] bool = new boolean[num1];
for (int i = 0; i < bool.length; i++)
{
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num1); i++)
{
if(bool[i] == true)
{
for(int j = (i*i); j < num1; j = j+i)
{
bool[j] = false;
}
}
}
for (int i = 2; i< bool.length; i++)
{
if(bool[i]==true)
{
label1 = new JLabel(" " + label[i]);
}
}
}
}
Thanks for your help!

Your code had many compilation errors.
Oracle has a helpful tutorial, Creating a GUI With JFC/Swing. Skip the Netbeans section. Review all the other sections.
I reworked your two JPanels. When creating a Swing application, you first create the GUI. After the GUI is created, you fill in the values to be displayed.
I created the following GUI. Here's the input JPanel.
Here's the Sieve JPanel.
I used Swing layout managers to create the two JPanels. Using null layouts and absolute positioning leads to many problems.
I created the sieve JPanel, then populated it with values. You can see how I did it in the source code.
Here's the complete runnable code. I made the classes inner classes.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Eratosthenes {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Eratosthenes().displayGUI();
}
});
}
private CardLayout cardLayout;
private JFrame frame;
private JPanel contentPane;
private InputPanel inputPanel;
private SievePanel sievePanel;
private void displayGUI() {
frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
cardLayout = new CardLayout();
contentPane.setLayout(cardLayout);
inputPanel = new InputPanel();
sievePanel = new SievePanel();
contentPane.add(inputPanel.getPanel(), "Input");
contentPane.add(sievePanel.getPanel(), "Sieve");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void cancelAction() {
frame.dispose();
System.exit(0);
}
public class InputPanel {
private JPanel panel;
private JTextField textField;
public InputPanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JPanel entryPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label = new JLabel("Enter a number from 1 to n:");
entryPanel.add(label);
textField = new JTextField(10);
entryPanel.add(textField);
panel.add(entryPanel, BorderLayout.BEFORE_FIRST_LINE);
JPanel buttonPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton okButton = new JButton("OK");
buttonPanel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int inputNumber = valueOf(textField.getText().trim());
if (inputNumber < 2) {
return;
}
sievePanel.updatePrimeLabel(inputNumber);
sievePanel.updatePrimeNumbers(inputNumber);
cardLayout.show(contentPane, "Sieve");
}
private int valueOf(String number) {
try {
return Integer.valueOf(number);
} catch (NumberFormatException e) {
return -1;
}
}
});
JButton cancelButton = new JButton("Cancel");
buttonPanel.add(cancelButton);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelAction();
}
});
okButton.setPreferredSize(cancelButton.getPreferredSize());
panel.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
return panel;
}
public JPanel getPanel() {
return panel;
}
}
public class SievePanel {
private JLabel primeLabel;
private JList<Integer> primeNumbersList;
private JPanel panel;
public SievePanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Font titlefont = panel.getFont().deriveFont(Font.BOLD, 24f);
JPanel textPanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Sieve of Eratosthenes");
titleLabel.setFont(titlefont);
titleLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(titleLabel, BorderLayout.BEFORE_FIRST_LINE);
primeLabel = new JLabel(" ");
primeLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(primeLabel, BorderLayout.AFTER_LAST_LINE);
panel.add(textPanel, BorderLayout.BEFORE_FIRST_LINE);
primeNumbersList = new JList<>();
JScrollPane scrollPane = new JScrollPane(primeNumbersList);
panel.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Return");
panel.add(button, BorderLayout.AFTER_LAST_LINE);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cardLayout.show(contentPane, "Input");
}
});
return panel;
}
public void updatePrimeLabel(int inputNumber) {
primeLabel.setText("The prime numbers from 2 to " +
inputNumber + " are:");
}
public void updatePrimeNumbers(int inputNumber) {
DefaultListModel<Integer> primeNumbers =
new DefaultListModel<>();
boolean[] bool = new boolean[inputNumber];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(inputNumber); i++) {
if (bool[i] == true) {
for (int j = (i * i); j < inputNumber; j = j + i) {
bool[j] = false;
}
}
}
for (int i = 2; i < bool.length; i++) {
if (bool[i] == true) {
primeNumbers.addElement(i);
}
}
primeNumbersList.setModel(primeNumbers);
}
public JPanel getPanel() {
return panel;
}
}
}

Related

Adding an image to a frame by button press

I am trying to implement an image appearing when a button is pressed. For this purpose I thought I could just copy the concept of button 4 (which works) and exchange the System.exit(0) with code to add an image, but while I've been able to use that code elsewhere successfully, here it does not seem to work.
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JSpinner;
import java.awt.Color;
import java.util.ArrayList;
public class Mainframe {
private JFrame frmOceanlife;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Mainframe window = new Mainframe();
window.frmOceanlife.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Mainframe() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setBounds(100, 100, 750, 600);
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.getContentPane().setLayout(null);
JButton btnNewButton_4 = new JButton("Quit");
btnNewButton_4.setBounds(640, 6, 81, 29);
frmOceanlife.getContentPane().add(btnNewButton_4);
btnNewButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JButton btnNewButton_5 = new JButton("Einfügen");
btnNewButton_5.setBounds(410, 34, 103, 29);
frmOceanlife.getContentPane().add(btnNewButton_5);
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
// label.setBounds(25,25,50,50);
frmOceanlife.getContentPane().add(label);
}
});
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
panel.add(piclabel);
frmOceanlife.getContentPane().add(panel);
JLabel lblNewLabel_2 = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
lblNewLabel_2.setBounds(6, 539, 334, 16);
frmOceanlife.getContentPane().add(lblNewLabel_2);
}
}
The problem is that you are creating a new JLabel and trying to add it to the frame, once the button is pressed. Instead, you should just change the Icon of the label that is already added to the frame (i.e., piclabel), using piclabel.setIcon(icon);. So, you should declare picLabel at the start of your code, so that it can be accessible in the actionPerformed method of your button.
public class Mainframe {
private JFrame frmOceanlife;
JLabel piclabel;
...
Then, instantiate the label in the initialize() method as below:
...
panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
...
Finally, your actionPerformed method for btnNewButton_5 (please consider using descriptive names instead) should look like this:
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
piclabel.setIcon(icon);
}
});
Update
If, however, what you want is to add a new JLabel each time, and not change the icon of the existing one, you could use Box object with BoxLayout added to a ScrollPane. Then add the ScrollPane to your JFrame. Working example is shown below, based on the code you provided (again, please consider using descriptive names and removing unecessary code):
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.*;
public class Mainframe {
private JFrame frmOceanlife;
Box box;
JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Mainframe mf = new Mainframe();
mf.initialize();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JButton insertBtn = new JButton("Einfügen");
insertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
box.add(Box.createRigidArea(new Dimension(0, 5)));// creates space between the JLabels
box.add(label);
frmOceanlife.repaint();
frmOceanlife.revalidate();
Rectangle bounds = label.getBounds();
scrollPane.getViewport().scrollRectToVisible(bounds);// scroll to the new image
}
});
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
box = new Box(BoxLayout.Y_AXIS);
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
box.add(piclabel);
scrollPane = new JScrollPane(box);
Dimension dim = new Dimension(box.getComponent(0).getPreferredSize());
scrollPane.getViewport().setPreferredSize(dim);
scrollPane.getVerticalScrollBar().setUnitIncrement(dim.height);
scrollPane.getViewport().setBackground(Color.WHITE);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(insertBtn);
controlPanel.add(quitBtn);
JLabel titleLbl = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!", SwingConstants.CENTER);
frmOceanlife = new JFrame();
frmOceanlife.getContentPane().add(titleLbl, BorderLayout.NORTH);
frmOceanlife.getContentPane().add(scrollPane, BorderLayout.CENTER);
frmOceanlife.getContentPane().add(controlPanel, BorderLayout.SOUTH);
frmOceanlife.setTitle("OceanLife");
frmOceanlife.pack();
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLocationRelativeTo(null);
frmOceanlife.setVisible(true);
}
}
Here is a sample application demonstrating the use of CardLayout. Note that I used [Eclipse] WindowBuilder. All the below code was generated by WindowBuilder apart from the ActionListener implementations. Also note that the ActionListener implementation for quitButton uses a lambda expression while the insertButton implementation uses a method reference.
More notes after the code.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class MainFram {
private JFrame frame;
private JPanel cardsPanel;
private JPanel firstPanel;
private JLabel firstLabel;
private JPanel secondPanel;
private JLabel secondLabel;
private JPanel buttonsPanel;
private JButton insertButton;
private JButton quitButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFram window = new MainFram();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainFram() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(getCardsPanel(), BorderLayout.CENTER);
frame.getContentPane().add(getButtonsPanel(), BorderLayout.SOUTH);
}
private JPanel getCardsPanel() {
if (cardsPanel == null) {
cardsPanel = new JPanel();
cardsPanel.setLayout(new CardLayout(0, 0));
cardsPanel.add(getFirstPanel(), "first");
cardsPanel.add(getSecondPanel(), "second");
}
return cardsPanel;
}
private JPanel getFirstPanel() {
if (firstPanel == null) {
firstPanel = new JPanel();
firstPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
firstPanel.add(getFirstLabel());
}
return firstPanel;
}
private JLabel getFirstLabel() {
if (firstLabel == null) {
firstLabel = new JLabel("");
firstLabel.setIcon(new ImageIcon(getClass().getResource("underwater-600x450.png")));
}
return firstLabel;
}
private JPanel getSecondPanel() {
if (secondPanel == null) {
secondPanel = new JPanel();
secondPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
secondPanel.add(getLabel_1());
}
return secondPanel;
}
private JLabel getLabel_1() {
if (secondLabel == null) {
secondLabel = new JLabel("");
secondLabel.setIcon(new ImageIcon(getClass().getResource("Stone.png")));
}
return secondLabel;
}
private JPanel getButtonsPanel() {
if (buttonsPanel == null) {
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
buttonsPanel.add(getInsertButton());
buttonsPanel.add(getQuitButton());
}
return buttonsPanel;
}
private JButton getInsertButton() {
if (insertButton == null) {
insertButton = new JButton("Einfügen");
insertButton.addActionListener(this::insertAction);
}
return insertButton;
}
private JButton getQuitButton() {
if (quitButton == null) {
quitButton = new JButton("Quit");
quitButton.addActionListener(e -> System.exit(0));
}
return quitButton;
}
private void insertAction(ActionEvent event) {
CardLayout cardLayout = (CardLayout) cardsPanel.getLayout();
cardLayout.next(cardsPanel);
}
}
The above code requires that the image files, i.e. underwater-600x450.png and Stone.png, be located in the same directory as file MainFram.class. Refer to How to Use Icons.
When you click on the insertButton, the panel containing the underwater-600x450.png image is hidden and the panel containing the Stone.png image is displayed. Clicking the insertButton a second time will hide Stone.png and display underwater-600x450.png. In other words, clicking the insertButton toggles the images.
The first thing to do is using layout managers instead of setting bounds manually:
import java.awt.*;
import javax.swing.*;
public class Mainframe {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
new Mainframe();
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* Create the application.
*/
public Mainframe() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
//frmOceanlife.setBounds(100, 100, 750, 600);
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frmOceanlife.getContentPane().setLayout(null);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton btnNewButton_4 = new JButton("Quit");
btnNewButton_4.addActionListener(e -> System.exit(0));
//btnNewButton_4.setBounds(640, 6, 81, 29);
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(btnNewButton_4);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
frmOceanlife.getContentPane().add(stonesPanel);
JButton btnNewButton_5 = new JButton("Insert");
//btnNewButton_5.setBounds(410, 34, 103, 29);
btnNewButton_5.addActionListener(e -> {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
//label.setBounds(25,25,50,50);
stonesPanel.add(label);
frmOceanlife.revalidate();
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(btnNewButton_5);
frmOceanlife.getContentPane().add(insertPanel);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
//panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
panel.setPreferredSize(new Dimension(700,550));
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
panel.add(piclabel);
frmOceanlife.getContentPane().add(panel);
JLabel lblNewLabel_2 = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
//lblNewLabel_2.setBounds(6, 539, 334, 16);
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(lblNewLabel_2);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
}
Next, let's introduce better names and use publicly available images to make the code more readable and more of an mre:
import java.awt.*;
import java.net.*;
import javax.swing.*;
public class Mainframe {
private static final String STONE = "https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/32x32/Circle_Red.png",
OCEAN ="https://media-gadventures.global.ssl.fastly.net/media-server/dynamic/blogs/posts/robin-wu/2014/12/PB110075.jpg";
public Mainframe() {
initialize();
}
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(e -> System.exit(0));
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(quitBtn);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
frmOceanlife.getContentPane().add(stonesPanel);
JButton insertBtn = new JButton("Insert");
insertBtn.addActionListener(e -> {
try {
ImageIcon icon = new ImageIcon(new URL(STONE));
JLabel stoneLbl = new JLabel(icon);
stonesPanel.add(stoneLbl);
frmOceanlife.revalidate();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(insertBtn);
frmOceanlife.getContentPane().add(insertPanel);
JPanel oceanPanel = new JPanel();
oceanPanel.setBackground(Color.WHITE);
oceanPanel.setLayout(new FlowLayout());
oceanPanel.setPreferredSize(new Dimension(700,550));
try {
JLabel oceanLbl = new JLabel(new ImageIcon(new URL(OCEAN)));
oceanPanel.add(oceanLbl);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
frmOceanlife.getContentPane().add(oceanPanel);
JLabel infoLabel = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(infoLabel);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
public static void main(String[] args) {
//no change in main
}
}
And add some final touchups :
public class Mainframe {
private static final String STONE = "https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/32x32/Circle_Red.png",
OCEAN ="https://media-gadventures.global.ssl.fastly.net/media-server/dynamic/blogs/posts/robin-wu/2014/12/PB110075.jpg";
private ImageIcon oceanIcon;
public Mainframe() {
initialize();
}
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(e -> System.exit(0));
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(quitBtn);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
JLabel stoneLbl = new JLabel();
stonesPanel.add(stoneLbl);
frmOceanlife.getContentPane().add(stonesPanel);
JButton insertBtn = new JButton("Insert");
insertBtn.addActionListener(e -> {
try {
ImageIcon icon = new ImageIcon(new URL(STONE));
stoneLbl.setIcon(icon);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(insertBtn);
frmOceanlife.getContentPane().add(insertPanel);
try {
oceanIcon = new ImageIcon(new URL(OCEAN));
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
JLabel oceanLbl = new JLabel();
oceanLbl.setIcon(oceanIcon);
JPanel oceanPanel = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(oceanIcon.getIconWidth()+100, oceanIcon.getIconHeight());
};
};
oceanPanel.add(oceanLbl);
oceanPanel.setBackground(Color.WHITE);
oceanPanel.setLayout(new GridBagLayout()); //center image in panel
frmOceanlife.getContentPane().add(oceanPanel);
JLabel infoLabel = new JLabel("Welcome to Oceanlife - Your Ocean size is "+oceanIcon+oceanIcon.getIconWidth()+
"x"+oceanIcon.getIconHeight()+"!");
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(infoLabel);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
public static void main(String[] args) {
//no change in main
}
}

How to make a new JButton instance in a existing button group everytime a Jbutton is pressed(clicked)

This may come off as an odd question, but I would like to make a program that makes a new Jbutton instance in an existing group every time a button(called new) is pressed. It will be added under the previously added button, all buttons must be part of a group(so when one button is pressed it will deselect previously selected button if the button in the group is pressed) and should be able to make an infinite number of buttons given n number of clicks. Here is what I have so far, but honestly I don't even know how to approach this one.
public static void makebuttonpane() {
buttonpane.setLayout(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
//d.anchor = GridBagConstraints.CENTER;
}
public static void addbutton(JButton button) {
System.out.println("button made");
buttonpane.removeAll();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
d.gridx=0;
System.out.println(ButtonMaker.getNumb());
d.gridy= ButtonMaker.getNumb();
buttonpane.add(button,d);
frame.setVisible(true);
buttonpane.validate();
}
public static void makebuttonpane() {
buttonpane.setLayout(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
//d.anchor = GridBagConstraints.CENTER;
}
public static void addbutton(JButton button) {
System.out.println("button made");
buttonpane.removeAll();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
d.gridx=0;
System.out.println(ButtonMaker.getNumb());
d.gridy= ButtonMaker.getNumb();
buttonpane.add(button,d);
frame.setVisible(true);
buttonpane.validate();
}
class ButtonMaker implements ActionListener{
public static int i=1;
public void actionPerformed(ActionEvent e) {
//System.out.println("I hear you");
//System.out.println(i);
JButton button = new JButton("Button "+i);
MultiListener.addbutton(button);
i++;
}
public static int getNumb() {
return i;
}
}
It adds the first button instance but pressing 'New' only changes that first created button instead of making a new one underneath
I created a GUI that adds a JButton when you click on the "Add Button" button.
Feel free to modify this any way you want.
Mainly, I separated the construction of the JFrame, the construction of the JPanel, and the action listener. Focusing on one part at a time, I was able to code and test this GUI quickly.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class JButtonCreator implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JButtonCreator());
}
private static int buttonCount = 0;
private JButtonPanel buttonPanel;
#Override
public void run() {
JFrame frame = new JFrame("JButton Creator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JButtonPanel();
JScrollPane scrollPane = new JScrollPane(
buttonPanel.getPanel());
frame.add(scrollPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class JButtonPanel {
private ButtonGroup buttonGroup;
private JPanel buttonPanel;
private JPanel panel;
public JButtonPanel() {
createPartControl();
}
private void createPartControl() {
panel = new JPanel();
panel.setPreferredSize(new Dimension(640, 480));
panel.setLayout(new BorderLayout());
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 5));
buttonGroup = new ButtonGroup();
panel.add(buttonPanel, BorderLayout.CENTER);
JButton newButton = new JButton("Add Button");
newButton.addActionListener(new ButtonListener(this));
panel.add(newButton, BorderLayout.AFTER_LAST_LINE);
}
public void addJButton() {
String text = "Button " + ++buttonCount;
JButton button = new JButton(text);
buttonPanel.add(button);
buttonGroup.add(button);
}
public JPanel getPanel() {
return panel;
}
}
public class ButtonListener implements ActionListener {
private JButtonPanel buttonPanel;
public ButtonListener(JButtonPanel buttonPanel) {
this.buttonPanel = buttonPanel;
}
#Override
public void actionPerformed(ActionEvent event) {
buttonPanel.addJButton();
buttonPanel.getPanel().revalidate();;
}
}
}

displaying selected jcheckbox in a jlabel

i have 10 jcheckbox and only 5 should be selected. i already did all the coding for this one, but i don't know how to display the selected 5 into a jlabel. i tried doing it by this code:
JCheckBox check;
JPanel panel=new JPanel();
for(int i=0; i<10; i++){
check=new JCheckBox();
check.addActionListener(listener);
check.setName("Select"+i);
panel.add(check);
}
this is the listener
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
name=check.getName();
}
};
and this is the panel where it should be displayed into jlabel
panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel(name);
panel2.add(txtVote);
}
but using this code, it doesn't display anything on the jlabel. if i change the listener into this:
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
txtVote.setText(check.getName());
}
};
it will only display into the last label. other jlabels would be blank. please help thank you so much
EDIT
here is the code that is runnable
public class JCheckBoxtoLabel{
JCheckBox check;
String name;
JLabel txtVote;
public JCheckBoxtoLabel() {
JFrame frame = new JFrame();
JPanel panel = createPanel();
JPanel panel2 = panel2();
frame.setLayout(new GridLayout(1,2));
frame.add(panel); frame.add(panel2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel() {
JPanel panel=new JPanel(new GridLayout(10,1));
for(int i=0; i<10; i++){
check=new JCheckBox();
check.addActionListener(listener);
check.setName("Select"+i);
panel.add(check);
}
return panel;
}
private JPanel panel2(){
JPanel panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel();
txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
panel2.add(txtVote);
}
return panel2;
}
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
txtVote.setText(check.getName());
}
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JCheckBoxtoLabel();
}
});
}
}
Consider changing what you're doing and displaying the text in a JList and not in JLabels. This can help you consolidate your information. You can also give your JCheckBoxes or JRadioButtons and ItemListener that only allows 5 of the buttons to be selected at a time -- unselecting the oldest one currently selected. For instance:
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class FiveNames extends JPanel {
private static final String[] ALL_NAMES = {"Bob", "Bill", "Frank", "Helen",
"Erica", "Mickey", "Donald", "Hillary", "Michael", "Peter", "Roger"};
private static final int ALLOWED_SELECTIONS_COUNT = 5;
private DefaultListModel<String> displayListModel = new DefaultListModel<>();
private JList<String> list = new JList<>(displayListModel);
public FiveNames() {
JPanel namePanel = new JPanel(new GridLayout(0, 1, 0, 5));
RButtonItemListener rButtonListener = new RButtonItemListener();
for (String name : ALL_NAMES) {
JRadioButton rButton = new JRadioButton(name);
rButton.setActionCommand(name);
rButton.addItemListener(rButtonListener);
namePanel.add(rButton);
}
list.setVisibleRowCount(ALLOWED_SELECTIONS_COUNT);
list.setPrototypeCellValue(" ");
list.setBackground(null);
setLayout(new GridLayout(1, 0));
add(namePanel);
add(list);
}
// listener to only allow the last 5 radiobuttons to be selected
private class RButtonItemListener implements ItemListener {
private List<ButtonModel> buttonModelList = new ArrayList<>();
#Override
public void itemStateChanged(ItemEvent e) {
JRadioButton rBtn = (JRadioButton) e.getSource();
ButtonModel model = rBtn.getModel();
if (e.getStateChange() == ItemEvent.SELECTED) {
buttonModelList.add(model);
if (buttonModelList.size() > ALLOWED_SELECTIONS_COUNT) {
for (int i = 0; i < buttonModelList.size() - ALLOWED_SELECTIONS_COUNT; i++) {
ButtonModel removedModel = buttonModelList.remove(0);
removedModel.setSelected(false);
}
}
} else {
buttonModelList.remove(model);
}
displayListModel.clear();
for (ButtonModel buttonModel : buttonModelList) {
displayListModel.addElement(buttonModel.getActionCommand());
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("FiveNames");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FiveNames());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
The problem is that txtVote is only a single Jlabel and you are trying to use it for all 5. Since the fifth jlabel was the last to be created it is the one being used. My suggestion is that you create an arraylist field and inside panel12 add each label to the arraylist. Then inside the listener it would iterate through each jlabel in the arraylist check if has text set to it, if so check the next one until it finds one with no text, then sets the text to that. The problem with this at the moment is that in your code you are never defining what happens when they uncheck the box.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JCheckBoxtoLabel{
JCheckBox check;
String name;
JLabel txtVote;
ArrayList<JLabel> boxLabels;
public JCheckBoxtoLabel() {
boxLabels = new ArrayList<JLabel>();
JFrame frame = new JFrame();
JPanel panel = createPanel();
JPanel panel2 = panel2();
frame.setLayout(new GridLayout(1,2));
frame.add(panel); frame.add(panel2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createPanel() {
JPanel panel=new JPanel(new GridLayout(10,1));
for(int i=0; i<10; i++){
check=new JCheckBox();
check.addActionListener(listener);
check.setName("Select"+i);
panel.add(check);
}
return panel;
}
private JPanel panel2(){
JPanel panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel();
txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
panel2.add(txtVote);
boxLabels.add(txtVote);
}
return panel2;
}
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
if(!check.isSelected()){
for(JLabel label: boxLabels){
if(label.getText().equals(check.getName())) label.setText("");
}
}else{
for(JLabel label: boxLabels){
if(label.getText().isEmpty()){
label.setText(check.getName());
return;
}
}
}
}
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JCheckBoxtoLabel();
}
});
}
}
Your variable JLabel txtVote is a single JLabel object, not an array.
In your panel2() function you assign 5 new JLabels to txtVote. Since you assign 5 in a row, it gets overriden each time so it only ever contains the final JLabel.
private JPanel panel2(){
JPanel panel2=new JPanel(new GridLayout(5,1));
for(int i=0; i<5; i++){
txtVote=new JLabel();
txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
panel2.add(txtVote);
}
return panel2;
}
So when you call getText on voteTxt in the action listener, you are only getting the last labels text.
To fix this, you need to make txtVote an array of JLabels, and in your action listener iterate a second time through your JLabels and call get text on each in turn.
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
check = (JCheckBox) e.getSource();
for (int i = 0; i < txtVotes.length; i++) {
txtVotes[i].getText(check.getName());
}
}
};
I don't know if you realise or want to, but each label is being set to the same value, if you don't want this you will need to store an array of check names somewhere and iterate through these as well.

Need help debugging, code compiles but won't run

Hey I could use help debugging this program. The code is not mine, it is from an answer to a question and I wanted to try it but I get a NullPointerException and can't figure out where the problem is. I think the problem may be image paths but I am not sure so I could use help.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class CircleImages {
private int score = 0;
private JTextField scoreField = new JTextField(10);
public CircleImages() {
scoreField.setEditable(false);
final ImageIcon[] icons = createImageIcons();
final JPanel iconPanel = createPanel(icons, 8);
JPanel bottomLeftPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomLeftPanel.add(new JLabel("Score: "));
bottomLeftPanel.add(scoreField);
JPanel bottomRightPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JButton newGame = new JButton("New Game");
bottomRightPanel.add(newGame);
JButton quit = new JButton("Quit");
bottomRightPanel.add(quit);
JPanel bottomPanel = new JPanel(new GridLayout(1, 2));
bottomPanel.add(bottomLeftPanel);
bottomPanel.add(bottomRightPanel);
newGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
reset(iconPanel, icons);
score = 0;
scoreField.setText(String.valueOf(score));
}
});
JFrame frame = new JFrame();
frame.add(iconPanel);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void reset(JPanel panel, ImageIcon[] icons) {
Component[] comps = panel.getComponents();
Random random = new Random();
for(Component c : comps) {
if (c instanceof JLabel) {
JLabel button = (JLabel)c;
int index = random.nextInt(icons.length);
button.setIcon(icons[index]);
}
}
}
private JPanel createPanel(ImageIcon[] icons, int gridSize) {
Random random = new Random();
JPanel panel = new JPanel(new GridLayout(gridSize, gridSize));
for (int i = 0; i < gridSize * gridSize; i++) {
int index = random.nextInt(icons.length);
JLabel label = new JLabel(icons[index]);
label.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
score += 1;
scoreField.setText(String.valueOf(score));
}
});
label.setBorder(new LineBorder(Color.GRAY, 2));
panel.add(label);
}
return panel;
}
private ImageIcon[] createImageIcons() {
String[] files = {"DarkGrayButton.png",
"BlueButton.png",
"GreenButton.png",
"LightGrayButton.png",
"OrangeButton.png",
"RedButton.png",
"YellowButton.png"
};
ImageIcon[] icons = new ImageIcon[files.length];
for (int i = 0; i < files.length; i++) {
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
}
return icons;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleImages();
}
});
}
}
Your problem is here:
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
You don't have the required images in your project, so getClass().getResource() will return null and you will have a NullPointerException in the constructor of ImageIcon.
What you have to do is put the following files in your project:
/circleimages/DarkGrayButton.png
/circleimages/BlueButton.png
/circleimages/GreenButton.png
/circleimages/LightGrayButton.png
/circleimages/OrangeButton.png
/circleimages/RedButton.png
/circleimages/YellowButton.png

Radio button issue

So for this class in java, here is my code
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();
}
});
}
}
This one is working but if you notice, I used invalidate(); here. If it is revalidate();, it will not run. However, my concern here is when a radio-button is clicked (e.g 3x3), the button will not show automatically. The frame should be adjusted first before the gird buttons appear. How can I work with this one?
Try your hands on this code :
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();
}
});
}
}
Here is the output of this :
and
Added this new code to answer a new thing :
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();
}
});
}
}
I'm not sure I understand the question or the code, but I'd expect to see an ActionListener on the 3x3 button that would create an array of JRadioButton instances using a method that's something like this:
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;
}

Categories