why JRadioButton is not selected even by using setSelected(true) - java

i only want one of the above button to be selected by default
but setSelected(true) is not working .
when i run the below program none of the JRadoiButton is selected
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioDemo implements ActionListener {
String buttonName;
JPanel radioPanel=new JPanel();
ButtonGroup group = new ButtonGroup();
Enumeration enl;
int result;
ActionEvent e;
JRadioButton birdButton[];
int i;
Vector<JComponent> list;
Vector<String> listName;
public RadioDemo(Vector<JComponent> list,Vector<String> listName,Enumeration en,Enumeration enl)
{
birdButton=new JRadioButton[list.size()];
this.enl=enl;
this.list=list;
this.listName=listName;
for(i=0;i<list.size()-1;i++)
{
buttonName=(String)enl.nextElement();
birdButton[i] = new JRadioButton(buttonName);
birdButton[i].setSelected(false);
birdButton[i].setActionCommand(buttonName);
group.add(birdButton[i]);
birdButton[i].addActionListener(this);
radioPanel.add(birdButton[i]);
}
buttonName=(String)enl.nextElement();
birdButton[i] = new JRadioButton(buttonName);
birdButton[i].setSelected(true);
birdButton[i].setActionCommand(buttonName);
group.add(birdButton[i]);
birdButton[i].addActionListener(this);
radioPanel.add(birdButton[i]);
radioPanel.setLayout(new BoxLayout(radioPanel,BoxLayout.Y_AXIS));
//birdButton.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
result = JOptionPane.showConfirmDialog(null, radioPanel,
"Please choose", JOptionPane.OK_CANCEL_OPTION);
show();
}
/** Listens to the radio buttons. */
public void actionPerformed(ActionEvent e)
{
this.e=e;
}
public void show()
{
if (result == JOptionPane.OK_OPTION)
{ i=0;
while(!birdButton[i].isSelected())
{
i++;
System.out.println(i);
}
//list.removeElementAt(i);
//listName.removeElementAt(i);
System.out.println(i);
System.out.println(e.getActionCommand());
}
}
i also try birdButton[0].setSelected(true);
out of loop

You haven't posted how you call your constructor, so maybe there is something there. I slightly modified your code, added a main method and it seems to work ok. Take a look at it:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class RadioDemo implements ActionListener {
String buttonName;
JPanel radioPanel = new JPanel();
ButtonGroup group = new ButtonGroup();
int result;
JRadioButton birdButton[];
Vector<String> listName;
private JRadioButton selectedButton;
public RadioDemo(Vector<String> listName) {
birdButton = new JRadioButton[listName.size()];
this.listName = listName;
int i = 0;
for (String buttonName : listName) {
birdButton[i] = new JRadioButton(buttonName);
if (i == 0) {
birdButton[i].setSelected(true);
selectedButton = birdButton[i];
}
birdButton[i].setActionCommand(buttonName);
group.add(birdButton[i]);
birdButton[i].addActionListener(this);
radioPanel.add(birdButton[i]);
i++;
}
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
// birdButton.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
result = JOptionPane.showConfirmDialog(null, radioPanel, "Please choose", JOptionPane.OK_CANCEL_OPTION);
show();
}
/** Listens to the radio buttons. */
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton rb = (JRadioButton) e.getSource();
System.err.println(rb.getText() + " is selected");
selectedButton = rb;
}
public void show() {
if (result == JOptionPane.OK_OPTION) {
System.err.println(selectedButton.getText() + " is selected and approved");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Vector<String> buttonNames = new Vector<String>();
buttonNames.add("Show");
buttonNames.add("Something");
buttonNames.add("Else");
buttonNames.add("Beep");
new RadioDemo(buttonNames);
}
});
}
}

Related

how can i capture data from one class and pass it around all classes

i have a multi class program, with each class having its own GUI, my task is to capture details from a class called dataInput and the data must be captured into variables of a class called studentRecords, i must capture about 10 records comprised of name, surname, student number and tests from 1-4, i have a class called RecordsMenu which have Buttons that call the different classes, for example, when i click dataInput button it calls the DataInput class, in the datainput class i must capture data into records class, then i must go back to recordsMenu screen, from there! when i click for example, the display Button , i must be able to see the data i captured, the problem i have is that, when ever i go back to the main screen , all the data i captured get lost and it print nulls when i test whether it captured or not, i will appreciate any kind of help, my code is below.this must be done with out using files, thank you
[here is the picture of the main screen of my application][1]
enter code here
[1]: https://i.stack.imgur.com/I6JyI.jpg
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.*;
public class InputDetails extends JPanel
{
JLabel title,name,surname,studentno,tests,t1,t2,t3,t4;
JTextField nametxf,surnametxf,studentnotxf,t1txf,t2txf,t3txf,t4txf;
JButton submit,home;
JPanel buttons, mainPanel, labels;
public InputDetails()
{
// title
title = new JLabel("Records Menu",SwingConstants.CENTER);
title.setForeground(Color.BLUE);
Font newLabelFont =new Font("Serif",Font.BOLD,70);
title.setFont(newLabelFont);
// buttons and actions
submit = new JButton("Submit");
submit.addActionListener(new Handler());
home = new JButton("Home");
home.addActionListener(new Handler());
//labels
name = new JLabel("Name");
surname = new JLabel("Surname");
studentno= new JLabel("Student Number");
tests = new JLabel("Tests");
// tests
t1 = new JLabel("Test 1");
t2 = new JLabel("Test 2");
t3 = new JLabel("Test 3");
t4 = new JLabel("Test 4");
//textfields
nametxf = new JTextField(10);
surnametxf = new JTextField(10);
studentnotxf = new JTextField(10);
t1txf= new JTextField(10);
t2txf= new JTextField(10);
t3txf= new JTextField(10);
t4txf= new JTextField(10);
buttons = new JPanel(new GridLayout(1,2,5,5));
buttons.add(submit);
buttons.add(home);
// fields
labels = new JPanel(new GridLayout(7,1,5,5));
labels.add(name);
labels.add(nametxf);
labels.add(surname);
labels.add(surnametxf);
labels.add(studentno);
labels.add(studentnotxf);
labels.add(t1);
labels.add(t1txf);
labels.add(t2);
labels.add(t2txf);
labels.add(t3);
labels.add(t3txf);
labels.add(t4);
labels.add(t4txf);
//
mainPanel = new JPanel(new BorderLayout(5,5));
mainPanel.add(title,BorderLayout.NORTH);
mainPanel.add(labels,BorderLayout.WEST);
mainPanel.add( buttons,BorderLayout.SOUTH);
add(mainPanel);
}
class Handler implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
if(click.getSource()==home)
{
// back to main view
mainPanel.setVisible(false);
add(new RecordsMenu());
}
else if(click.getSource()==submit)
{
String name,surname,studentno;
int test1,test2,test3,test4;
name = nametxf.getText();
surname = surnametxf.getText();
studentno=studentnotxf.getText();
test1 =Integer.parseInt(t1txf.getText());
test2 = Integer.parseInt(t2txf.getText());
test3 = Integer.parseInt(t3txf.getText());
test4 = Integer.parseInt(t4txf.getText());
StudentRecords records = new StudentRecords(name,surname,studentno,test1,test2,test3,test4);
}
}
}
}
import java.io.*;
import javax.swing.JOptionPane;
public class StudentRecords {
String name , Surname, studentno;
int test1,test2,test3,test4;
FileWriter records;
PrintWriter out;
public StudentRecords(String Name, String Surname,String StudentNo,int t1, int t2, int t3, int t4)
{
setName(Name);
setSurname(Surname);
setStudentno(StudentNo);
setTest1(t1);
setTest2(t2);
setTest3(t3);
setTest4(t4);
// saveRecords();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getStudentno() {
return studentno;
}
public void setStudentno(String studentno) {
this.studentno = studentno;
}
public int getTest1() {
return test1;
}
public void setTest1(int test1) {
this.test1 = test1;
}
public int getTest2() {
return test2;
}
public void setTest2(int test2) {
this.test2 = test2;
}
public int getTest3() {
return test3;
}
public void setTest3(int test3) {
this.test3 = test3;
}
public int getTest4() {
return test4;
}
public void setTest4(int test4) {
this.test4 = test4;
}
}
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.*;
public class ReadFile extends JPanel{
private JButton read,back;
private JTextArea desplay;
private JLabel title;
private JPanel mainpanel, buttons;
String record,student1,student2,student3,student4,student5,student6,student7,student8,student9,student10;
public ReadFile()
{
// title
title = new JLabel("Read File Contents",SwingConstants.CENTER);
Font newLabelFont =new Font("Serif",Font.BOLD,30);
title.setFont(newLabelFont);
// textarea
desplay = new JTextArea();
// buttons
read = new JButton("Open");
read.addActionListener(new Handler());
back = new JButton("back to main");
back.addActionListener(new Handler());
// panel
buttons = new JPanel(new GridLayout(1,2,5,5));
buttons.add(read);
buttons.add(back);
mainpanel = new JPanel(new BorderLayout(5,5));
mainpanel.add(title,BorderLayout.NORTH);
mainpanel.add(desplay,BorderLayout.CENTER);
mainpanel.add(buttons,BorderLayout.SOUTH);
add(mainpanel);
}
class Handler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent click) {
if(click.getSource()==read)
{
JFileChooser chooser = new JFileChooser();
Scanner input = null;
if(chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
try {
input = new Scanner(selectedFile);
while(input.hasNextLine())
{
record = input.nextLine();
desplay.append(record);
desplay.append("\n");
}
}catch(IOException fileerror) {
JOptionPane.showMessageDialog(null, "you have an error");
}
}
}
else if(click.getSource()==back)
{
mainpanel.setVisible(false);
add(new RecordsMenu());
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Search extends JPanel
{
DisplayDetails d = new DisplayDetails();
JLabel title,stdn;
JTextField studentno;
JPanel mainp,details,buttons;
JButton search,home;
Scanner input;
File records;
String key;
String line;
boolean wordfound = false;
public Search()
{
// title
title = new JLabel("Search a Student",SwingConstants.CENTER);
Font newLabelFont =new Font("Serif",Font.BOLD,30);
title.setFont(newLabelFont);
stdn = new JLabel("Student Number");
studentno = new JTextField(10);
//
search = new JButton("Search");
search.addActionListener(new Handler());
home = new JButton("Home");
mainp = new JPanel(new BorderLayout());
details = new JPanel(new GridLayout(1,2));
details.add(stdn);
details.add(studentno);
buttons = new JPanel(new GridLayout(1,2));
home.addActionListener(new Handler());
buttons.add(search);
buttons.add(home);
mainp.add(title,BorderLayout.NORTH);
mainp.add(details,BorderLayout.WEST);
mainp.add(buttons,BorderLayout.SOUTH);
add(mainp);
}
class Handler implements ActionListener
{
public void actionPerformed(ActionEvent button)
{
if(button.getSource()==search)
{
// define the key
key = studentno.getText();
if(key.matches("^2\\d{8}"))
{
File file =new File("StudentRecords.txt");
Scanner in;
try {
in = new Scanner(file);
while(in.hasNextLine())
{
line=in.nextLine();
if((line.contains(key))) {
wordfound=true;
break;
}
}
if((wordfound)) {
System.out.println(line);
mainp.setVisible(false);
add(d);
d.display.setText(line);
JOptionPane.showMessageDialog(null,"found");
}
else
{
JOptionPane.showMessageDialog(null,"not found");
}
in.close();
} catch(IOException e) {
}
}
else if(!(key.matches("^2\\d{8}")))
{
JOptionPane.showMessageDialog(null,"incorrect student number");
}
}
else if(button.getSource()==home)
{
mainp.setVisible(false);
add(new RecordsMenu());
}
}
}
// methods
public void RecordFOund()
{
}
public void notFound()
{
}
}
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame
{
public Frame()
{
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
add(new RecordsMenu());
// add(new Search());
setVisible(true);
}
}
try this
In the getter methods of the StudentRecords Class make them {return this.variable;}
as an example in the public int getTest1(){return this.test1;}

How to set a shortcut key for JRadioButton without modifiers

I'm working in a project where I need to add a key shortcut for each JRadioButton, while looking on another similar question and as I'm using some other custom Actions I decided to use the method setAction on each of my JRadioButtons, however it requires me to press ALT + 1 - ALT + 5 to "trigger" the actionPerformed method of my CustomAction class.
How can I modify this class in order to just press 1 - 5 and get the same behaviour?
This is the code I made that demonstrates this issue:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class RadioButtonSelectableByNumbers {
private JFrame frame;
private JRadioButton buttons[];
private ButtonGroup group;
public RadioButtonSelectableByNumbers() {
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RadioButtonSelectableByNumbers().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame("frame");
buttons = new JRadioButton[5];
group = new ButtonGroup();
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JRadioButton();
switch (i) {
case 0:
buttons[i].setAction(new CustomAction(String.valueOf(i + 1), KeyEvent.VK_1));
break;
case 1:
buttons[i].setAction(new CustomAction(String.valueOf(i + 1), KeyEvent.VK_2));
break;
case 2:
buttons[i].setAction(new CustomAction(String.valueOf(i + 1), KeyEvent.VK_3));
break;
case 3:
buttons[i].setAction(new CustomAction(String.valueOf(i + 1), KeyEvent.VK_4));
break;
default:
buttons[i].setAction(new CustomAction(String.valueOf(i + 1), KeyEvent.VK_5));
break;
}
group.add(buttons[i]);
frame.getContentPane().add(buttons[i]);
}
frame.pack();
frame.setVisible(true);
}
class CustomAction extends AbstractAction {
public CustomAction(String name, Integer mnemonic, Integer modifier) {
super(name);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(mnemonic, modifier));
}
public CustomAction(String name, Integer mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("radio clicked");
}
}
}
How do you tie any key to a component in Swing? Key Bindings: Key Bindings Tutorial.
Hang on while I look at your code...
For example
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class RadioButtonSelectableByNumbers {
private JFrame frame;
private JRadioButton buttons[];
private ButtonGroup group;
public RadioButtonSelectableByNumbers() {
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RadioButtonSelectableByNumbers().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame("frame");
frame.setDefaultCloseOperation(JFrame);
buttons = new JRadioButton[5];
group = new ButtonGroup();
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
for (int i = 0; i < buttons.length; i++) {
JRadioButton rbtn = createButton(i);
buttons[i] = rbtn;
frame.getContentPane().add(rbtn);
}
frame.pack();
frame.setVisible(true);
}
private JRadioButton createButton(int i) {
String name = String.valueOf(i + 1);
int stdMnemonic = KeyEvent.VK_1 + i; // for standard number keys
int numpadMnemonic = KeyEvent.VK_NUMPAD1 + i; // for numpad number keys
Action action = new CustomAction(name, stdMnemonic);
JRadioButton rBtn = new JRadioButton(action);
group.add(rBtn);
// bindings active if window is focused. Component doesn't have to be focused
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = rBtn.getInputMap(condition);
ActionMap actionMap = rBtn.getActionMap();
KeyStroke keyStroke = KeyStroke.getKeyStroke(stdMnemonic, 0);
KeyStroke keyStroke2 = KeyStroke.getKeyStroke(numpadMnemonic, 0);
inputMap.put(keyStroke, keyStroke.toString());
actionMap.put(keyStroke.toString(), action);
inputMap.put(keyStroke2, keyStroke2.toString());
actionMap.put(keyStroke2.toString(), action);
return rBtn;
}
class CustomAction extends AbstractAction {
public CustomAction(String name, Integer mnemonic, Integer modifier) {
super(name);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(mnemonic, modifier));
}
public CustomAction(String name, Integer mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("radio clicked: " + e.getActionCommand());
}
}
}
Another solution, that may be better, since usually JRadioButtons don't use ActionListeners, is to create an AbstractAction that simply clicks the button. In the example below, MyAction does this, as well as gives the active JRadioButton the focus:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class NumberActions extends JPanel {
private ButtonGroup buttonGroup = new ButtonGroup();
public NumberActions() {
ItemListener itemListener = new MyItemListener();
setLayout(new GridLayout(1, 0));
for (int i = 0; i < 10; i++) {
JRadioButton rBtn = createRadioBtn(i);
rBtn.addItemListener(itemListener);
buttonGroup.add(rBtn);
add(rBtn);
}
}
private JRadioButton createRadioBtn(int i) {
String text = String.valueOf(i);
JRadioButton rBtn = new JRadioButton(text);
rBtn.setActionCommand(text);
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = rBtn.getInputMap(condition);
ActionMap actionMap = rBtn.getActionMap();
Action action = new MyAction(rBtn);
bindAction(inputMap, actionMap, action, KeyEvent.VK_0 + i);
bindAction(inputMap, actionMap, action, KeyEvent.VK_NUMPAD0 + i);
return rBtn;
}
private void bindAction(InputMap inputMap, ActionMap actionMap, Action action, int mnemonic) {
KeyStroke keyStroke = KeyStroke.getKeyStroke(mnemonic, 0);
inputMap.put(keyStroke, keyStroke.toString());
actionMap.put(keyStroke.toString(), action);
}
private class MyItemListener implements ItemListener {
#Override
public void itemStateChanged(ItemEvent iEvt) {
if (iEvt.getStateChange() == ItemEvent.SELECTED) {
AbstractButton btn = (AbstractButton) iEvt.getSource();
System.out.println("Button: " + btn.getActionCommand());
}
}
}
private class MyAction extends AbstractAction {
private AbstractButton btn;
public MyAction(AbstractButton btn) {
this.btn = btn;
}
#Override
public void actionPerformed(ActionEvent e) {
btn.requestFocusInWindow();
btn.doClick();
}
}
private static void createAndShowGui() {
NumberActions mainPanel = new NumberActions();
JFrame frame = new JFrame("NumberActions");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
edit: code fixed

jbutton does not work

Hi I have the following code where I have a start and stop button . when start is pressed canvas starts painting but I cannot press stop button until the start operation is done . I need to stop and resume the paint on the button press . Once the start button is pressed the other buttons cannot be pressed till the canvas is painted.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.Timer;
public abstract class JUIApp extends JPanel implements ActionListener {
public static CACanvas cacanvas= null;
public ArrayList<int[]> genL;
public JFrame frame = null;
protected JPanel mainPanel = null;
private JButton btn0 = null;
private JButton btn1 = null;
private JButton btn2 = null;
#SuppressWarnings("rawtypes")
DefaultComboBoxModel rules = null;
#SuppressWarnings("rawtypes")
JComboBox rulesCombo =null;
JScrollPane ruleListScrollPane=null;
JLabel lable=null;
JTextField generation=null;
JLabel gLable=null;
public static String Rule;
public static String Generations;
public boolean isChanged =false;
public int gridCellSize=4;
private static final long serialVersionUID = 1L;
public int genCurrent=0;
public int posCurrent=0;
public int i;
public Color cellColor= null;
public Timer waitTimer;
public static boolean waitFlag;
public static boolean alert1Flag=false;
public boolean stopFlag=false;
public JLabel Alert1=new JLabel();
public int genCheck=0;
//private List<Point> fillCells;
public JUIApp() {
initGUI();
}
public void initGUI() {
//fillCells = new ArrayList<>(25);
frame = new JFrame();
frame.setTitle("Cellular Automata Demo");
frame.setSize(1050, 610);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(getMainPanel(),BorderLayout.NORTH);
frame.setVisible(true);
Toolkit.getDefaultToolkit().setDynamicLayout(false);
cacanvas=new CACanvas();
frame.add(cacanvas);
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public JPanel getMainPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout());
//cacanvas=new CACanvas();
btn0 = new JButton("Start");
btn0.addActionListener(this);
//waitTimer = new Timer(1000, this);
mainPanel.add(btn0);
JButton btn2 = new JButton("Stop");
btn2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent s)
{
stopFlag=true;
//cacanvas.repaint();
}
});
mainPanel.add(btn2);
btn1 = new JButton("Clear");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
CACanvas.clearFlag=true;
generation.setText("");
alert1Flag=true;
rulesCombo.setSelectedIndex(0);
Alert1.setText("Please enter the number of generations");
Alert1.setBounds(30, 20, 5, 5);
Alert1.setVisible(alert1Flag);
mainPanel.add(Alert1);
cacanvas.repaint();
frame.setSize(1060, 610);
}
});
mainPanel.add(btn1);
lable=new JLabel();
lable.setText("Select Rule :");
mainPanel.add(lable);
rules=new DefaultComboBoxModel();
for (int i=0;i<=100;i++)
{
String p=String.valueOf(i);
rules.addElement(p);
}
rules.addElement("250");
rules.addElement("254");
rulesCombo = new JComboBox(rules);
rulesCombo.setSelectedIndex(0);
ruleListScrollPane = new JScrollPane(rulesCombo);
mainPanel.add(ruleListScrollPane);
//mainPanel.revalidate();
gLable=new JLabel();
gLable.setText("Enter the number of Generations (Max 64)");
generation=new JTextField(2);
mainPanel.add(gLable);
mainPanel.add(generation);
// mainPanel.add(cacanvas);
return mainPanel;
}
public abstract void run();
#Override
public void actionPerformed(ActionEvent arg0) {
Alert1.setVisible(false);
waitFlag=false;
System.out.println("We received an ActionEvent " + arg0);
Generations=generation.getText();
System.out.println(Generations);
Rule = "";
if (rulesCombo.getSelectedIndex() != -1) {
Rule =
(String) rulesCombo.getItemAt
(rulesCombo.getSelectedIndex());
}
System.out.println(Rule);
int rule=Integer.parseInt(Rule);
Hashtable<String,Integer> rules= new Hashtable<String,Integer>();
CARule ruleClass=new CARule();
rules=ruleClass.setRule(rule);
CAGenetationSet sa =new CAGenetationSet(100, false,rules);
genL=new ArrayList<int[]>();
genL=sa.runSteps(Integer.parseInt(Generations));
System.out.println("calling pattern set");
for(int i=0;i<=genL.size()-1;i++)
{
System.out.println("Painting generation :"+i);
if(stopFlag==false)
{
cacanvas.repaint();
}
//genPaint();
//sleep();
int[] newCell=genL.get(i);
for(int r=0;r<newCell.length;r++)
{
if(newCell[r]==1)
{
System.out.println("Generaton is"+i+"CellLife is"+r);
cacanvas.fillCell(i,r);
}
}
}
/*cacanvas.patternSet(genL);
waitFlag=true;
System.out.println("run completed");
// cacanvas.clearFlag=true;
*/
}
public void genPaint()
{
cacanvas.repaint();
}
public void sleep()
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
JUIApp app = new JUIApp() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Run method");
}
};
}
}
Seems like you are using the current Thread on that task, you should create another Thread and add one listeners code to the new Thread.

Swing,JTextAreas are blank

Class principal :
import javax.swing.*;
import java.util.Random;
public class Principal extends Guii {
public int combo;
public static Random bulion = new Random();
public static boolean sansa;
public static boolean input;
public int status;
//STATUS 0 = HEADS;
//STATUS 1 = TAILS;
public static void main(String[] args) {
Guii lee = new Guii();
Principal obiect = new Principal();
}
public int flip(){
boolean sansa2 ;
sansa2 = bulion.nextBoolean();
if(sansa2){
status = 0;
display.setText("Heads");
}
else{
status = 1;
display.setText("Tails");
}
return status;
}
public int returnStatus(){
return status;
}
}
Class Guii :
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import java.awt.Dimension;
public class Guii extends JFrame{
Principal obiect;
public JButton heads = new JButton("Heads");
public JButton tails = new JButton("Tails");
public JTextArea display = new JTextArea();
public JTextArea comboul = new JTextArea();
private JPanel panel;
public int predictie;
public Guii(){
super("Heads or Tails");
setContentPane(panel);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);}
public void dacaHeads(){
if(heads.getModel().isPressed()) predictie = 0;
}
public void dacaTails(){
if(tails.getModel().isPressed()) predictie = 1;
heads.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e){
dacaHeads();
obiect.flip();
if(predictie == obiect.returnStatus() ){
String s = comboul.getText();
int combo = Integer.valueOf(s);
s = Integer.toString(++combo);
comboul.setText("asdsaad");}
else{
String z = "0";
comboul.setText("asdasda");
}
}
});
tails.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e){
dacaTails();
obiect.flip();
if(predictie == obiect.returnStatus() ){
String s = comboul.getText();
int combo = Integer.valueOf(s);
s = Integer.toString(++combo);
comboul.setText(s);}
else{
String z = "0";
comboul.setText(z);
}
}
});}
The problem is that the window opens, i see everything but nothing happens when i press the buttons.
I used gui designer from intellij idea.
Thank you.
//Sorry for the second question.Deleted it.
I don't know if it is a mistake of writing your code but your function dacaTails(), which add the listener to the button, seems to be never called. You should put the addActionListener's functions in the constructor method, I think.

Populating a JList from a JButton ActionListener

Running into a lot of problems trying to populate a JList after a button press. The code below utilizes a technique that I have employed successfully before, but I have been unable to get this working. The goal is to run a test after pressing a button and display the urls that passed and the urls that failed in separate JLists.
The Action Listener:
//Start button--starts tests when pressed.
JButton start = new JButton("Start");
start.setPreferredSize(new Dimension(400, 40));
start.setAlignmentX(Component.CENTER_ALIGNMENT);
start.addActionListener(new Web(urlA, codeA, cb, passJ, failJ));
panel2.add(start);
The Action Listener Method:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JList;
public class Web implements ActionListener {
private ArrayList<String> urls;
private ArrayList<Integer> statusCodes;
private JComboBox cb;
private JList passJ = new JList();
private JList failJ = new JList();
//constructor--allows other values to be used
public Web(ArrayList<String> urls, ArrayList<Integer> statusCodes, JComboBox cb, JList passList, JList failList ){
this.urls = urls;
this.statusCodes = statusCodes;
this.cb = cb;
this.passJ = passJ;
this.failJ = failJ;
}
#Override
public void actionPerformed(ActionEvent event){
ArrayList<String> resultsP = new ArrayList<String>();
ArrayList<String> resultsF = new ArrayList<String>();
//get source
JButton start = (JButton) event.getSource();
//get value from combobox
String selected = cb.getSelectedItem().toString();
if(selected.equals("ALL")){
}
if(selected.equals("STATUS CODE")){
for(int i = 0; i < urls.size(); i++){
try {
URL u = new URL(urls.get(i));
HttpURLConnection connection = (HttpURLConnection)u.openConnection(); //open connection and cast to HttpURLConnection
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if (code == statusCodes.get(i)){
System.out.println(i + "."+ urls.get(i)+" \t\t\t PASS");
resultsP.add(urls.get(i));
}
else{
System.out.println(i + "." +urls.get(i)+ "\t\t\t FAIL");
resultsF.add(urls.get(i));
}
} catch (MalformedURLException | ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (String str: resultsP){
System.out.println(str);
}
System.out.println("/////////////////////////////////////////////////////////////////////////////////");
for (String str: resultsF){
System.out.println(str);
}
passJ.removeAll();
failJ.removeAll();
passJ.setListData(resultsP.toArray());
failJ.setListData(resultsF.toArray()) ;
passJ.repaint();
failJ.repaint();
}//StatusCodeTest
}
}
How the lists are added to the GUI:
JList passJ = new JList(urlA.toArray());
JScrollPane scroll1 = new JScrollPane(passJ);
scroll1.setPreferredSize(new Dimension (700, 150));
scroll1.setMaximumSize( scroll1.getPreferredSize() );
scroll1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel2.add(scroll1);
panel2.add(Box.createRigidArea(new Dimension(0,50)));
JList failJ = new JList(urlA.toArray());
JScrollPane scroll2 = new JScrollPane(failJ);
scroll2.setPreferredSize(new Dimension(700, 150));
scroll2.setMaximumSize(scroll1.getPreferredSize());
scroll2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel2.add(scroll2);
//spacer
panel2.add(Box.createRigidArea(new Dimension(0,25)));
Any GUIdance would be greatly appreciated.
Seems you have different instances of passJ/failJ in your Web class and GUI class.
passJ.removeAll(); failJ.removeAll(); doesn't clear items of JList, that method from Container.
Here is simple example of adding/clearing items to JList:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestFrame extends JFrame {
private JList<Integer> normal;
private JList<Integer> fail;
private Integer[] vals;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
normal = new JList<Integer>(new DefaultListModel<Integer>());
fail = new JList<Integer>(new DefaultListModel<Integer>());
vals = new Integer[]{1,2,3,4,5,6,7,8,9,33};
JButton add = new JButton("collect data");
add.addActionListener(getCollectListener());
JButton clear = new JButton("clear data");
clear.addActionListener(getClearListener());
JPanel p = new JPanel();
p.add(new JScrollPane(normal));
p.add(new JScrollPane(fail));
JPanel btnPanel = new JPanel();
btnPanel.add(add);
btnPanel.add(clear);
add(p);
add(btnPanel,BorderLayout.SOUTH);
}
private ActionListener getClearListener() {
return new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((DefaultListModel<Integer>)normal.getModel()).removeAllElements();
((DefaultListModel<Integer>)fail.getModel()).removeAllElements();
}
};
}
private ActionListener getCollectListener() {
return new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(Integer i : vals){
if(i%3==0){
((DefaultListModel<Integer>)normal.getModel()).addElement(i);
} else {
((DefaultListModel<Integer>)fail.getModel()).addElement(i);
}
}
}
};
}
public static void main(String args[]) {
new TestFrame();
}
}

Categories