Dynamic generation of buttons in Java - java

I am trying to dynamically generate a form. Basically, I want to load a list of items for purchase, and generate a button for each. I can confirm that the buttons are being generated with the debugger, but they aren't being displayed. This is inside a subclass of JPanel:
private void generate() {
JButton b = new JButton("height test");
int btnHeight = b.getPreferredSize().height;
int pnlHeight = this.getPreferredSize().height;
int numButtons = pnlHeight / btnHeight;
setLayout(new GridLayout(numButtons, 1));
Iterator<Drink> it = DrinkMenu.iterator();
for (int i = 0; i <= numButtons; ++i) {
if (!it.hasNext()) {
break;
}
final Drink dr = it.next();
b = new DrinkButton(dr);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
order.addDrink(dr);
}});
add(b);
}
revalidate();
}
DrinkButton is a subclass of JButton. Any ideas?

example about validate() revalidate() plus repaint(), look like as required for correct output to the GUI, layed by some of LayourManagers
EDIT: as trashgod noticed, I added Schedule a job for the EDT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ValidateRevalidateRepaint {
private JPanel panel;
private GridBagConstraints gbc;
private boolean validate, revalidate, repaint;
public ValidateRevalidateRepaint() {
validate = revalidate = repaint = false;
panel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(0, 20, 0, 20);
panel.add(getFiller(), gbc);
JFrame f = new JFrame();
f.setJMenuBar(getMenuBar());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.getContentPane().add(getRadioPanel(), "East");
f.getContentPane().add(getCheckBoxPanel(), "South");
f.setSize(400, 200);
f.setLocation(200, 200);
f.setVisible(true);
}
private JMenuBar getMenuBar() {
JMenu menu = new JMenu("change");
ActionListener l = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
int n = Integer.parseInt(item.getActionCommand());
makeChange(n);
}
};
for (int j = 1; j < 5; j++) {
String s = String.valueOf(j) + " component";
if (j > 1) {
s += "s";
}
JMenuItem item = new JMenuItem(s);
item.setActionCommand(String.valueOf(j));
item.addActionListener(l);
menu.add(item);
}
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
private JPanel getRadioPanel() {
JPanel panel1 = new JPanel(new GridBagLayout());
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.insets = new Insets(2, 2, 2, 2);
gbc1.weighty = 1.0;
gbc1.gridwidth = GridBagConstraints.REMAINDER;
ButtonGroup group = new ButtonGroup();
ActionListener l = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton radio = (JRadioButton) e.getSource();
int n = Integer.parseInt(radio.getActionCommand());
makeChange(n);
}
};
for (int j = 0; j < 4; j++) {
String s = String.valueOf(j + 1);
JRadioButton radio = new JRadioButton(s);
radio.setActionCommand(s);
radio.addActionListener(l);
group.add(radio);
panel1.add(radio, gbc1);
}
return panel1;
}
private JPanel getCheckBoxPanel() {
final String[] operations = {"validate", "revalidate", "repaint"};
ActionListener l = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JCheckBox checkBox = (JCheckBox) e.getSource();
String ac = checkBox.getActionCommand();
boolean state = checkBox.isSelected();
if (ac.equals("validate")) {
validate = state;
}
if (ac.equals("revalidate")) {
revalidate = state;
}
if (ac.equals("repaint")) {
repaint = state;
}
}
};
JPanel panel2 = new JPanel();
for (int j = 0; j < operations.length; j++) {
JCheckBox check = new JCheckBox(operations[j]);
check.setActionCommand(operations[j]);
check.addActionListener(l);
panel2.add(check);
}
return panel2;
}
private void makeChange(int number) {
panel.removeAll();
for (int j = 0; j < number; j++) {
panel.add(getFiller(), gbc);
}
if (validate) {
panel.validate();
}
if (revalidate) {
panel.revalidate();
}
if (repaint) {
panel.repaint();
}
}
private JPanel getFiller() {
JPanel panel3 = new JPanel();
panel3.setBackground(Color.red);
panel3.setPreferredSize(new Dimension(40, 40));
return panel3;
}
public static void main(String[] args) {//added Schedule a job for the EDT
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ValidateRevalidateRepaint rVR = new ValidateRevalidateRepaint();
}
});
}
}

Works on my computer...
public class Panel extends JPanel {
public Panel() {
setLayout(new java.awt.GridLayout(4, 4));
for (int i = 0; i < 16; ++i) {
JButton b = new JButton(String.valueOf(i));
b.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
//...
}
});
add(b);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 300));
frame.add(new Panel());
frame.setVisible(true);
}
});
}
}
As far as I remember your version was working as well, although I had to remove your "drinking" code. Start from this example (it shows nice 4x4 grid of buttons) and determine what is wrong with your code.

You can use revalidate(), as shown in this example.
Addendum: Here's my variation on #mKorbel's interesting answer that shows a similar result for GridLayout. It looks like repaint() may be necessary after revalidate().
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/** #see https://stackoverflow.com/questions/6395105 */
public class ValidateRevalidateRepaint {
private JPanel center;
private boolean validate = false;
private boolean revalidate = true;
private boolean repaint = true;
public ValidateRevalidateRepaint() {
center = new JPanel(new GridLayout(1, 0, 10, 10));
JFrame f = new JFrame();
f.setTitle("VRR");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(center, BorderLayout.CENTER);
f.add(getRadioPanel(), BorderLayout.EAST);
f.add(getCheckBoxPanel(), BorderLayout.SOUTH);
makeChange(4);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JPanel getRadioPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1));
ButtonGroup group = new ButtonGroup();
ActionListener l = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton radio = (JRadioButton) e.getSource();
int n = Integer.parseInt(radio.getActionCommand());
makeChange(n);
}
};
for (int j = 0; j < 4; j++) {
String s = String.valueOf(j + 1);
JRadioButton radio = new JRadioButton(s);
radio.setActionCommand(s);
radio.addActionListener(l);
group.add(radio);
panel.add(radio);
if (j == 3) {
group.setSelected(radio.getModel(), true);
}
}
return panel;
}
private JPanel getCheckBoxPanel() {
final String[] operations = {"validate", "revalidate", "repaint"};
ActionListener l = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JCheckBox checkBox = (JCheckBox) e.getSource();
String ac = checkBox.getActionCommand();
boolean state = checkBox.isSelected();
if (ac.equals("validate")) {
validate = state;
}
if (ac.equals("revalidate")) {
revalidate = state;
}
if (ac.equals("repaint")) {
repaint = state;
}
}
};
JPanel panel = new JPanel();
for (int j = 0; j < operations.length; j++) {
JCheckBox check = new JCheckBox(operations[j]);
if (j == 0) {
check.setSelected(false);
} else {
check.setSelected(true);
}
check.setActionCommand(operations[j]);
check.addActionListener(l);
panel.add(check);
}
return panel;
}
private void makeChange(int number) {
center.removeAll();
for (int j = 0; j < number; j++) {
center.add(getFiller());
}
if (validate) {
center.validate();
}
if (revalidate) {
center.revalidate();
}
if (repaint) {
center.repaint();
}
}
private JPanel getFiller() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.blue, 5));
panel.setBackground(Color.red);
panel.setPreferredSize(new Dimension(50, 50));
return panel;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ValidateRevalidateRepaint();
}
});
}
}

Related

sieve using 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;
}
}
}

How to make this text area show which toggle buttons are selected?

Please can someone help me, I'm trying to make a seat reservation part for my cinema ticket system assignment ... so the problem is i want the text of the button to show in the text area when selected and not show only the specific text when deselected .. but when i deselect a button the whole text area is cleared.
For e.g. when I select C1, C2, C3 - it shows in the text area correctly, but if I want to deselect C3, the text area must now show only C1 & C2. Instead, it clears the whole text area!
Can anyone spot the problem in the logic?
import java.awt.*;
import static java.awt.Color.blue;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.Border;
public class Cw_Test2 extends JFrame {
JButton btn_payment,btn_reset;
JButton buttons;
JTextField t1,t2;
public static void main(String[] args) {
// TODO code application logic here
new Cw_Test2();
}
public Cw_Test2()
{
Frame();
}
public void Frame()
{
this.setSize(1200,700); //width, height
this.setTitle("Seat Booking");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 6);
Font newFont = myFont.deriveFont(20F);
t1=new JTextField();
t1.setBounds(15, 240, 240,30);
JPanel thePanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
thePanel.setLayout(null);
JPanel ourPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border ourBorder = BorderFactory.createLineBorder(blue , 2);
ourPanel.setBorder(ourBorder);
ourPanel.setLayout(null);
ourPanel.setBounds(50,90, 1100,420);
JPanel newPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border newBorder = BorderFactory.createLineBorder(blue , 1);
newPanel.setBorder(newBorder);
newPanel.setLayout(null);
newPanel.setBounds(790,50, 270,340);
JLabel label1 = new JLabel( new ColorIcon(Color.GRAY, 400, 100) );
label1.setText( "SCREEN" );
label1.setHorizontalTextPosition(JLabel.CENTER);
label1.setVerticalTextPosition(JLabel.CENTER);
label1.setBounds(130,50, 400,30);
JLabel label2 = new JLabel(" CINEMA TICKET MACHINE ");
label2.setBounds(250,50,400,30);
label2.setFont(newFont);
JLabel label3 = new JLabel("Please Select Your Seat");
label3.setBounds(270,10,500,30);
label3.setFont(newFont);
JLabel label4 = new JLabel("Selected Seats:");
label4.setBounds(20,10,200,30);
label4.setFont(newFont);
btn_payment=new JButton("PROCEED TO PAY");
btn_payment.setBounds(35,290,200,30);
JLabel label6 = new JLabel("Center Stall");
label6.setBounds(285,172,200,30);
JPanel seatPane, seatPane1, seatPane2, seatPane3, seatPane4, seatPane5;
JToggleButton[] seat2 = new JToggleButton[8];
JTextArea chosen = new JTextArea();
chosen.setEditable(false);
chosen.setLineWrap(true);
chosen.setBounds(20, 60, 200, 100);
// Center Seats
seatPane1 = new JPanel();
seatPane1.setBounds(200,200,250,65);
seatPane1.setLayout(new FlowLayout());
for(int x=0; x<8; x++){
seat2[x] = new JToggleButton("C"+(x+1));
seatPane1.add(seat2[x]);
seat2[x].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
AbstractButton abstractButton = (AbstractButton) ev.getSource();
boolean selected = abstractButton.getModel().isSelected();
for(int x=0; x<8; x++){
if(seat2[x]==ev.getSource()){
if(selected){
chosen.append(seat2[x].getText()+",");
}else{
chosen.setText(seat2[x].getText().replace(seat2[x].getText(),""));
}
}
}
}
});
}
newPanel.add(chosen);
ourPanel.add(seatPane1);
ourPanel.add(label6);
thePanel.add(label2);
ourPanel.add(label3);
ourPanel.add(label1);
newPanel.add(btn_payment);
newPanel.add(label4);
ourPanel.add(newPanel);
thePanel.add(ourPanel);
add(thePanel);
setResizable(false);
this.setVisible(true);
}
public static class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
When any seat is selected or deselected, this code iterates an array of seats (in the method showSelectedSeats()) and updates the text area to show the seats that are selected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CinemaTicketMachine {
private JComponent ui = null;
private JToggleButton[] seats = new JToggleButton[80];
private JTextArea selectedSeats = new JTextArea(3, 40);
CinemaTicketMachine() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
selectedSeats.setLineWrap(true);
selectedSeats.setWrapStyleWord(true);
selectedSeats.setEditable(false);
ui.add(new JScrollPane(selectedSeats), BorderLayout.PAGE_END);
JPanel cinemaFloor = new JPanel(new BorderLayout(40, 0));
cinemaFloor.setBorder(new TitledBorder("Available Seats"));
ui.add(cinemaFloor, BorderLayout.CENTER);
JPanel leftStall = new JPanel(new GridLayout(0, 2, 2, 2));
JPanel centerStall = new JPanel(new GridLayout(0, 4, 2, 2));
JPanel rightStall = new JPanel(new GridLayout(0, 2, 2, 2));
cinemaFloor.add(leftStall, BorderLayout.WEST);
cinemaFloor.add(centerStall, BorderLayout.CENTER);
cinemaFloor.add(rightStall, BorderLayout.EAST);
ActionListener seatSelectionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showSelectedSeats();
}
};
for (int ii=0; ii <seats.length; ii++) {
JToggleButton tb = new JToggleButton("S-" + (ii+1));
tb.addActionListener(seatSelectionListener);
seats[ii] = tb;
int colIndex = ii%8;
if (colIndex<2) {
leftStall.add(tb);
} else if (colIndex<6) {
centerStall.add(tb);
} else {
rightStall.add(tb);
}
}
}
private void showSelectedSeats() {
StringBuilder sb = new StringBuilder();
for (int ii=0; ii<seats.length; ii++) {
JToggleButton tb = seats[ii];
if (tb.isSelected()) {
sb.append(tb.getText());
sb.append(", ");
}
}
String s = sb.toString();
if (s.length()>0) {
s = s.substring(0, s.length()-2);
}
selectedSeats.setText(s);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
CinemaTicketMachine o = new CinemaTicketMachine();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

How to add a method to a JPanel?

I working on this assignment and I have a problem where I need to add this matrix to a JPanel. I made the matrix in another method because I thought it would be easier but can't find a solution. I also used this layout by following a tutorial on Oracles website if it look familiar.
The text also needs to be editable which is why I have buttons. I don't have there functions here either.
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
JPanel array;
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
c.fill = GridBagConstraints.HORIZONTAL;
}
button = new JButton("Reset to 0");
pane.add(button, c);
// WHERE IT NEEDS TO BE ADDED***********************
array = new JPanel();
pane.add(array, c);
}
private static void createAndShowGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public int[][] getRandomMatrix() {
int[][] randomMatrix = new int[10][10];
for (int r = 0; r < randomMatrix.length; r++) {
for (int c = 0; c < randomMatrix[r].length; c++) {
randomMatrix[r][c] = (int)(Math.random() * 2);
}
}
return randomMatrix;
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
From the question you outline, it looks like you want to add an additional method to JPanel.
Ok, that would require you to create a custom instance of a JPanel like this:
public class MyPanel extends JPanel {
public MyPanel() {
super();
}
public int[][] getRandomMatrix() {
int[][] randomMatrix = new int[10][10];
for (int r = 0; r < randomMatrix.length; r++) {
for (int c = 0; c < randomMatrix[r].length; c++) {
randomMatrix[r][c] = (int)(Math.random() * 2);
}
}
return randomMatrix;
}
}
And instead of adding a pre-rolled JPanel to the frame, you would add an instance of 'MyPanel' to the frame instead.
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
MyPanel array;
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
c.fill = GridBagConstraints.HORIZONTAL;
}
button = new JButton("Reset to 0");
pane.add(button, c);
array = new MyPanel();
pane.add(myPanel, c);
}
private static void createAndShowGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

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