First, I would like to say I have searched these forums, as well as others for an answer to my question. I am very new to Java, and programing in general. After working on this for several hours, I would like to ask for some help.
I am trying to open up a window (that will have some graphics later), that has a menu bar. The options are 3 drop down menus that perform a task when selected. The file menu lets me save, load, and exit the program. For now the rest just print to the screen to let me know that much is working. Right now, I want to set it up so when I click the "Create Seller" option, it will open up a new dialog box with 3 fields. I would like to enter a string in one, and two doubles in the other two. I will then store those as variables and send them to another function. I have been stuck on this part for way too long. Keep in mind that, while this has probably been answered before, I think I am just not competent enough with Java yet to understand the answer. Try to dumb it down for me if that is not too much to ask. THANKS!
here is the class I am working on. Feel free to ask for less or more if you need.
package seller;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFileChooser;
import javax.swing.JTextField;
import datastore.Meteorite;
import datastore.continents;
import datastore.customers;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class BaseFrame extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JFileChooser myChooser = new JFileChooser(".");
JMenuItem menuItemSave;
JMenuItem menuItemLoad;
JMenuItem menuItemExit;
JMenuItem menuItemCreateSeller;
JMenuItem menuItemUpdateSeller;
JMenuItem menuItemRemoveSeller;
JMenuItem menuItemCreateMeteorite;
JMenuItem menuItemUpdateMeteorite;
JMenuItem menuItemRemoveMeteorite;
JMenuItem menuItemCreateOneLine;
continents worldMap = new continents();
boolean[][] mapArray = null;
int selection = 1;
String shopName = null;
Map myMap= new Map();
Scanner myScanner = new Scanner(System.in);
Menu myMenu = new Menu();
seller seller= new seller();
Meteorites myMeteorite = new Meteorites();
customers sellers= new customers(0,0,"test");
customers buyers= new customers(0, 0, "test");
ArrayList <Meteorite> myMeteorites = new ArrayList<Meteorite>();
ArrayList <customers> mySellers= new ArrayList<customers>();
ArrayList <customers> myBuyers= new ArrayList<customers>();
customers people= new customers(0,0,"test");
public void makeGui()
{
this.setTitle("Phase 3");
JMenuBar mb = new JMenuBar();
this.setJMenuBar(mb);
//Load and Save used from class example
JMenu fileMenu = new JMenu("File");
mb.add(fileMenu);
menuItemSave = new JMenuItem("Save");
menuItemSave.addActionListener(this);
menuItemLoad = new JMenuItem("Load");
menuItemLoad.addActionListener(this);
menuItemExit = new JMenuItem("Exit");
menuItemExit.addActionListener(this);
fileMenu.add(menuItemSave);
fileMenu.add(menuItemLoad);
fileMenu.add(menuItemExit);
//seller menu
JMenu sellerMenu = new JMenu("Seller");
mb.add(sellerMenu);
menuItemCreateSeller = new JMenuItem("Create Seller");
menuItemCreateSeller.addActionListener(this);
menuItemUpdateSeller = new JMenuItem("Update Seller");
menuItemUpdateSeller.addActionListener(this);
menuItemRemoveSeller = new JMenuItem("Remove Seller");
menuItemRemoveSeller.addActionListener(this);
sellerMenu.add(menuItemCreateSeller);
sellerMenu.add(menuItemUpdateSeller);
sellerMenu.add(menuItemRemoveSeller);
//handle meteorite menu
JMenu handleMeteoriteMenu = new JMenu("Handle Meteorite");
mb.add(handleMeteoriteMenu);
menuItemCreateMeteorite = new JMenuItem("Create Meteorite");
menuItemCreateMeteorite.addActionListener(this);
menuItemUpdateMeteorite = new JMenuItem("Update Meteorite");
menuItemUpdateMeteorite.addActionListener(this);
menuItemRemoveMeteorite = new JMenuItem("Remove Meteorite");
menuItemRemoveMeteorite.addActionListener(this);
menuItemCreateOneLine = new JMenuItem("Create Meteorite(1 line)");
menuItemCreateOneLine.addActionListener(this);
handleMeteoriteMenu.add(menuItemCreateMeteorite);
handleMeteoriteMenu.add(menuItemUpdateMeteorite);
handleMeteoriteMenu.add(menuItemRemoveMeteorite);
handleMeteoriteMenu.add(menuItemCreateOneLine);
JPanel tPanel = new JPanel();
this.add(tPanel);
this.pack();
this.setSize(new Dimension(640,480));
this.setVisible(true);
}
String myName;
double myLong;
double myLat;
#Override
public void actionPerformed(ActionEvent e)
{
Object source=null;
source=e.getSource();
if (source == menuItemLoad)
{
mapArray = worldMap.createMap();
myChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = myChooser.showOpenDialog(this);
//if user clicked Cancel button, return
if (result == JFileChooser.CANCEL_OPTION)
System.exit(1);
File myFile = myChooser.getSelectedFile(); //get file
//display error if invalid
if ( ( myFile == null) || (myFile.getName().equals("")))
{
JOptionPane.showMessageDialog(this, "Invalid Name", "Invalid Name", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
myMeteorites= myMeteorite.loadMeteorite(myMeteorites, myFile);
sellers.loadSeller(mySellers);
buyers.loadBuyer(myBuyers);
}
if (source == menuItemSave)
{
mapArray = worldMap.createMap();
myChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = myChooser.showOpenDialog(this);
//if user clicked Cancel button, return
if (result == JFileChooser.CANCEL_OPTION)
System.exit(1);
File myFile = myChooser.getSelectedFile(); //get file
//display error if invalid
if ( ( myFile == null) || (myFile.getName().equals("")))
{
JOptionPane.showMessageDialog(this, "Invalid Name", "Invalid Name", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
myMeteorites= myMeteorite.saveMeteorite(myMeteorites, myFile);
sellers.saveSeller(mySellers);
buyers.saveBuyer(myBuyers);
}
if (source == menuItemExit)
{
System.exit(1); //exit system
}
if (source == menuItemCreateSeller)
{
JFrame myFrame = new JFrame("Create a Seller");
JPanel myPanel = new JPanel();
JLabel myLabel1 = new JLabel();
JLabel myLabel2 = new JLabel();
JLabel myLabel3 = new JLabel();
final JTextField myText1 = new JTextField(30);
final JTextField myText2 = new JTextField(30);
final JTextField myText3 = new JTextField(30);
setDefaultCloseOperation(EXIT_ON_CLOSE);
myLabel1.setText("Enter Name");
myLabel2.setText("Enter Longitude");
myLabel3.setText("Enter Latitude");
myPanel.add(myLabel1);
myPanel.add(myText1);
myPanel.add(myLabel2);
myPanel.add(myText2);
myPanel.add(myLabel3);
myPanel.add(myText3);
myFrame.add(myPanel);
myFrame.setSize(350,200);
myFrame.setVisible(true);
myText1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
myName = myText1.getText();
}
});
myName = myText1.getText();
//myLong = Double.parseDouble(myText2.getText());
//myLat = Double.parseDouble(myText3.getText());
System.out.println(myName);
//mySellers=people.createCust(mySellers, myLong, myLat, myName);
//mySellers=people.saveSeller(mySellers);
}
if (source == menuItemRemoveSeller)
{
System.out.println("remove seller");
}
if (source == menuItemUpdateSeller)
{
System.out.println("update seller");
}
if (source == menuItemCreateMeteorite)
{
System.out.println("create meteorite");
}
if (source == menuItemUpdateMeteorite)
{
System.out.println("updateMeteorite");
}
if (source == menuItemRemoveMeteorite)
{
System.out.println("remove meteorite");
}
if (source == menuItemCreateOneLine)
{
System.out.println("create one line");
}
}
}
See this example for what I am talking about. Though I'd advise against using multiple frames, this will work for what yo are trying to do. As #MadProgrammer suggested, look into creating JDialogs
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BaseFrame extends JFrame {
private String name;
private double value1;
private double value2;
private final JMenuBar jMenuBar = new JMenuBar();
private final JMenu jmOpen = new JMenu("Open");
JMenuItem menuItemCreateSeller = new JMenuItem("Create Seller");
InnerFrame innerFrame = new InnerFrame();
public BaseFrame() {
innerFrame.setResizable(false);
jmOpen.add(menuItemCreateSeller);
jMenuBar.add(jmOpen);
setJMenuBar(jMenuBar);
menuItemCreateSeller.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
innerFrame.setVisible(true);
}
});
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
Frame frame = new BaseFrame();
}
});
}
private class InnerFrame extends JFrame {
JPanel myPanel = new JPanel();
JLabel myLabel1 = new JLabel("Enter Name");
JLabel myLabel2 = new JLabel("Enter Longitude");
JLabel myLabel3 = new JLabel("Enter Latitude");
JLabel jlblStatus = new JLabel(" ");
JTextField myText1 = new JTextField(10);
JTextField myText2 = new JTextField(10);
JTextField myText3 = new JTextField(10);
JButton jbtPrint = new JButton("Print");
public InnerFrame() {
myPanel.add(myLabel1);
myPanel.add(myText1);
myPanel.add(myLabel2);
myPanel.add(myText2);
myPanel.add(myLabel3);
myPanel.add(myText3);
JPanel p1 = new JPanel(new GridLayout(1,2));
p1.add(jlblStatus);
p1.add(jbtPrint);
jlblStatus.setHorizontalAlignment(SwingConstants.LEFT);
jlblStatus.setForeground(Color.RED);
jbtPrint.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
name = myText1.getText();
value1 = Double.parseDouble(myText2.getText());
value2 = Double.parseDouble(myText3.getText());
System.out.println(name);
double total = value1 + value2;
System.out.println(total);
setVisible(false);
} catch (NumberFormatException ex) {
jlblStatus.setText("Invalid Input");
}
}
});
add(myPanel, BorderLayout.CENTER);
add(p1, BorderLayout.SOUTH);
setSize(180, 220);
setLocationRelativeTo(null);
setVisible(false);
}
}
}
You've gotten good advice in comments, and the other answer that has been posted looks reasonable at a glance. I'm going to throw in an explanation that you may or may not need; if you do need it, it would be the sort of thing it would be hard to explain that you need, because it is a concept that you may not have assimilated yet.
UI programming is "event-driven"; that means that, instead of having control in your code as you do for a non-interactive program, the control is passed to another system or part of the system, and when certain events happen, that other part calls your code. The 'other part' in this case is the Swing runtime. So your code is all about setting up the frames, panels, layouts, text fields, drop-downs, etc., AND setting listeners to those things that might cause events, and waiting for events to happen.
If your confusion is rooted in a lack of understanding of this, then the answer to your question might be that the listener for the button on the dialog is going to read the values from the drop-downs and/or text fields -- presumably the user has chosen and/or entered values as he/she was supposed to and then clicked the button. So the action routine that fires when the button (or the enter key) is clicked (pressed) goes and gets those values as they are at that time and puts them into variables (or writes them to a database or instantiates another object with them or whatever it is supposed to do.
This routine also might do validation -- if, for instance, one of the text fields holds a value that is required and the user didn't fill it out, then this listener routine could detect that and, instead of allowing the program to continue, could popup a message dialog for the user telling him/her what is wrong.
Again, I don't know that this is any part of your problem, but I thought it might be. It is a concept that inexperienced UI programmers sometimes have trouble with, and it is so basic to UI programming that a lot of the tutorials just assume you already know it.
Related
I am trying to create and Editable JComboBox to allow the user to type the name of the song to purchase. However when I set tunes.setEditable(true); I get an error... any help will be appreciated!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes2 extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes = new JComboBox();
// set as editable
tunes.setEditable(true);
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes2()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes frame = new JTunes();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
Thank you!
Actually, Java requires that you setup JComponents in the constructor. In order for your code to work, you need to call on setEditable(true) in the constructor, which means that you just need to move tunes.setEditable(true); to the constructor.
Tip: always allocate memory for JComponents in the constructor (you want to draw the components as soon as you create the Jframe). You can have a reference to the JComboBox at the class level.
Here is another version of your code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes2 extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes;
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes2()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
tunes = new JComboBox();
// set as editable
tunes.setEditable(true);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes2 frame = new JTunes2();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
You added the tunes.setEditable(true) at the class level, instead of at the method level. No statements allowed at the class level!
Here's a fixed version: I renamed JTunes2 to JTunes to fix the compilation errors, and moved the setEditable to the constructor. Also I fixed the indentation - this makes it harder to make this mistake:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes = new JComboBox();
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
tunes.setEditable(true);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes frame = new JTunes();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
my current program takes in text from some JTextFields and adds it to a file to keep track of medications. What i want to do, is add another button to the bottom of the program that will open a second jframe to display the medications that are already documented, but all attempts have been brutally unsuccessful. Below is the code that i am currently working with.
Much Thanks.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
#SuppressWarnings({ "serial" })
public class MedGUITest extends JFrame {
private JLabel medName;
private JLabel medTime;
private JLabel medDose;
private JLabel finished;
private JTextField textFieldMed;
private JTextField textFieldTime;
private JTextField textFieldDose;
private JButton submitButton;
private JButton meds;
public MedGUITest(){
setLayout(new FlowLayout());
medName = new JLabel("Type Medication Here:");
add(medName);
textFieldMed = new JTextField("",15);
add(textFieldMed);
medDose = new JLabel("Type Medication Dose:");
add(medDose);
textFieldDose = new JTextField("",15);
add(textFieldDose);
medTime = new JLabel("Type Medication Time:");
add(medTime);
textFieldTime = new JTextField("",15);
add(textFieldTime);
submitButton = new JButton("Click Here to Add");
event e = new event();
submitButton.addActionListener(e);
add(submitButton);
meds = new JButton("Click Here to see meds");
event2 r = new event2();
meds.addActionListener(r);
add(meds);
finished = new JLabel("");
add(finished);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e){
String medName = textFieldMed.getText();
String medDose = textFieldDose.getText();
String medTime = textFieldTime.getText();
File med = new File("med.txt");
try(PrintWriter out= new PrintWriter(new FileWriter(med,true))) {
out.println("Medication: " + medName + " " +"Dosage: "+ medDose + " Mg"+ " " +"Time of day: "+ medTime);
finished.setText("Your Med has been added");
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public class event2 implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
public static void main(String args[]) throws IOException{
int winWidth = 300;
int winLength = 300;
MedGUITest gui = new MedGUITest();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(winWidth, winLength);
gui.setVisible(true);
gui.setTitle("Standard GUI");
}
}
You would probably want to use a JDialog instead of another JFrame. You just set it up the same way you set up any other JFrame or JDialog. You create the frame/dialog, add components and then call pack() then setvisible(true). You just want to make sure that you don't set JFrame.setDefaultCloseOperation() to close when the close your second JFrame.
I find it easier to set up my classes to sub-class JPanel instead of JFrame so then it is easier to reuse it in other places.
After a lot of googling i still haven't found what im looking for, mostly because i don't know what i'm looking for.
Basically i want the lock in button to be disabled until one of the radio buttons is selected, and i only want one of the radio buttons to be selected at a a time.
I haven't done any formatting yet so its still ugly.
My JFrame
My Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
public class Game extends JFrame
{
JLabel lblQuestion;
JRadioButton btA;
JRadioButton btB;
JRadioButton btC;
JRadioButton btD;
JButton btLock;
JTextField txtQuestion;
int question = 0;
public Game()
{
getContentPane().setLayout(null);
setupGUI();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void setupGUI()
{
txtQuestion = new JTextField();
txtQuestion.setLocation(10,10);
txtQuestion.setSize(100,25);
txtQuestion.setText(Integer.toString(question));
getContentPane().add(txtQuestion);
lblQuestion = new JLabel();
lblQuestion.setLocation(50,82);
lblQuestion.setSize(300,50);
lblQuestion.setText("No_Label");
getContentPane().add(lblQuestion);
btA = new JRadioButton();
btA.setLocation(50,160);
btA.setSize(100,50);
btA.setText("No_Label");
btA.setSelected(false);
getContentPane().add(btA);
btB = new JRadioButton();
btB.setLocation(250,160);
btB.setSize(100,50);
btB.setText("No_Label");
btB.setSelected(false);
getContentPane().add(btB);
btC = new JRadioButton();
btC.setLocation(50,240);
btC.setSize(100,50);
btC.setText("No_Label");
btC.setSelected(false);
getContentPane().add(btC);
btD = new JRadioButton();
btD.setLocation(250,240);
btD.setSize(100,50);
btD.setText("No_Label");
btD.setSelected(false);
getContentPane().add(btD);
btLock = new JButton();
btLock.setLocation(150,303);
btLock.setSize(100,50);
btLock.setText("Lock in");
getContentPane().add(btLock);
btLock.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
question = question + 1;
txtQuestion.setText(Integer.toString(question));
try{
ArrayList<String> list = questions(question);
}catch(Exception ex){}
}
});
setTitle("Who wants to be a millionare");
setSize(570,400);
setVisible(true);
setResizable(true);
setLocationRelativeTo(null);
}
public ArrayList<String> questions(int quesion) throws IOException{
File file = new File("questions.txt");
if (!file.exists()){
throw new FileNotFoundException("Could not find \"users\" file");
}
FileReader fr = new FileReader(file.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
ArrayList<String> list = new ArrayList<String>();
String s;
for(int i = 0; i*4 <= quesion; i++){
br.readLine();
}
while((s=br.readLine()) !=null){
list.add(s);
}
br.close();
return list;
}
public static void main( String args[] )
{
new Game();
}
}
First you need to add an action listener to whichever RadioButton needs to be pressed before the button is active.
Like this:
someRadioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
someButton.enabled(true);
}
});
And secondly for the only one RadioButton used at a time you need a ButtonGroup such as:
ButtonGroup myButtonGroup = new ButtonGroup();
myButtonGroup.add(someRadioButton);
Add all the RadioButtons you want into a group.
Hope this helps :)
Start by taking a look at How to Use Buttons, Check Boxes, and Radio Buttons.
You can use a ButtonGroup to ensure that only one button within the group is selected
You can use an ActionListener to detect changes to the JRadioButton state
I'm creating an encryption method that takes input from a JTextArea, and I'm getting an error saying:
'Illegal modifier for parameter input; only final is permitted'
I have gone through many documentation websites and other articles, and I have found nothing. Here is my near-complete code:
Package lake. RAMBIT7;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import net.miginfocom.swing.MigLayout;
public class RAMBIT7 implements ActionListener {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RAMBIT7 window = new RAMBIT7();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public RAMBIT7() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setSize(800, 600); //1024x768, 800x600
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("RAMBIT7 Encryption Software 1.0.0");
frame.setResizable(false);
/**
* 'Encrypt' and 'Decrypt' buttons
*/
JButton encrypt = new JButton("Encrypt");
encrypt.addActionListener(this);
JButton decrypt = new JButton("Decrypt");
decrypt.addActionListener(this);
/**
* JMenuBar
*/
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu help = new JMenu("Help");
JMenuItem about = new JMenuItem("About");
JMenuItem license = new JMenuItem("License");
JMenuItem close = new JMenuItem("Exit");
file.add(close);
help.add(about);
help.add(license);
bar.add(file);
bar.add(help);
about.addActionListener(this);
license.addActionListener(this);
close.addActionListener(this);
frame.setJMenuBar(bar);
/**
* Text and input related stuff
*/
frame.getContentPane().setLayout(new MigLayout("", "[69px][71px,grow][]", "[23px][35.00][200px][][grow][]"));
frame.getContentPane().add(encrypt, "cell 0 0,alignx left,aligny top");
frame.getContentPane().add(decrypt, "cell 2 0,alignx right,aligny top");
JLabel lblCopyTextIn = new JLabel("Copy Text in here.");//JLabel
frame.getContentPane().add(lblCopyTextIn, "cell 1 1");
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, "cell 0 2 3 1,grow");
JTextArea textArea = new JTextArea();//JTextArea
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
JLabel lblOutputTextIn = new JLabel("Output text in RAMBIT7 encryption");//JLabel
frame.getContentPane().add(lblOutputTextIn, "cell 1 3");
JScrollPane scrollPane_1 = new JScrollPane();
frame.getContentPane().add(scrollPane_1, "cell 0 4 3 1,grow");
JTextArea textArea_1 = new JTextArea();//JTextArea_1
scrollPane_1.setViewportView(textArea_1);
textArea_1.setEditable(false);
textArea_1.setLineWrap(true);
JLabel lblRambitEncryptionMethod = new JLabel("RAMBIT7 Encryption Method"); //JLabel
frame.getContentPane().add(lblRambitEncryptionMethod, "cell 1 5");
public String input_0 = textArea.getText();//Error here
}
#Override
public void actionPerformed(ActionEvent e) {
String a = e.getActionCommand();
if(a.equalsIgnoreCase("encrypt")) {
System.out.println("Begin RAMBIT7 encryption.");
encryptRAMBIT7(input);
} else if(a.equalsIgnoreCase("decrypt")) {
System.out.println("Begin RAMBIT7 decryption.");
decryptRAMBIT7(input);
} else if(a.equalsIgnoreCase("about")) {
System.out.println("Opening Program Specs...");
JOptionPane.showMessageDialog(frame, "RAMBIT7 v1.0.0");
System.out.println("Program Specs Closed.");
} else if(a.equalsIgnoreCase("license")) {
System.out.println("Opening License...");
JOptionPane.showMessageDialog(frame, "You may not sell this program or say that any part of the code is yours.");
System.out.println("License closed.");
} else if(a.equalsIgnoreCase("exit")) {
System.out.println("Why, oh WHY CRUEL WORLD does that person have to close me?! I'm\na living thing too! Or maybe I'm an emotionless pig! NOOOOOOOO!");
System.exit(3);
}
}
}
You need to re-think your structure a bit:
Even if you could get the String out of the JTextArea on creation time, it would not help you one bit. When the JTextArea changes its display text, that String will not change since Strings are invariants.
Likewise a String field would not help, not unless it was dynamically bound to the JTextArea via a DocumentListener or something similar.
Instead make the JTextArea a private field and extract its String when needed.
If other classes need the text, then create a public method public String getTextAreaText() and return the text held by the JTextArea in that method.
public class RAMBIT7 implements ActionListener {
private JFrame frame;
private JTextArea textarea = new JTextArea();
// ....
private void initialize() {
// .....
// JTextArea textArea = new JTextArea();//JTextArea
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
and elsewhere:
if(a.equalsIgnoreCase("encrypt")) {
System.out.println("Begin RAMBIT7 encryption.");
encryptRAMBIT7(textarea.getText());
You just can't use the public keyword inside a method. Visibility modifiers are used to determine what members of each object can be accessed from outside, by other objects or classes. Things you declare inside of a method are not members of a class, but rather things that only exist in that method, so visibility modifiers make no sense there.
public String input_0 = textArea.getText();
Any variable declared inside a function is local to that function. Outside world don't know about that variable but the function itself. hence, access modifier public, private or protected are not applicable to local instance variable, such as input_0 here which is local to initialize(). Again, this code, is inside initialize() function, which is responsible for initializing your GUI component, creating them and adding them to the container, user input is yet to happen, so reading the text content of textArea is meaning less.
I want to change the image a JLabel is viewing during runtime, but I keep getting NullPointerExceptions or nothing happens when I press the magic button that's supposed to do things. Is it even possible in Java?
Here is my code in its entirety:
import java.text.*;
import javax.swing.text.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Shell implements ActionListener, MenuKeyListener
{
JFrame frame;
JWindow window;
JButton PSubmit;
JPanel pane1, pane2;
JRadioButton R1, R2, R3;
ButtonGroup PGroup;
JTabbedPane layout;
String result;
String border = "Border.png";
String DF = "Frame.png";
String list [];
Driver driver;
public Shell()
{
driver = new Driver();
list = new String [6];
}
public void setFrame()
{
frame = new JFrame("Pokemon Program 3 by Systems Ready");
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().setLayout(new BorderLayout());
}
public void frameLayout()
{
layout = new JTabbedPane();
JPanel pane1 = new JPanel();
JPanel pane2 = new JPanel();
JLabel label = new JLabel("Please choose the restrictions:");
JLabel imgLabel1 = new JLabel(new ImageIcon(border));
JLabel notiLabel1 = new JLabel("The Pokemon chosen with these restrictions are: ");
JLabel notiLabel2 = new JLabel("'No Restrictions': No restrictions for the kind of Pokemon chosen based on species or items.");
JLabel notiLabel3 = new JLabel("'Battle Revolution': All Pokemon must have unique items.");
JLabel notiLabel4 = new JLabel("'Battle Tower': All Pokemon must have unique items, Uber and Event Legendaries banned.");
JLabel label2 = new JLabel("Please choose possible Pokemon:");
pane1.add(label);
pearlButtons();
pane1.add(R1);
pane1.add(R2);
pane1.add(R3);
pane1.add(PSubmit);
pane1.add(notiLabel2);
pane1.add(notiLabel3);
pane1.add(notiLabel4);
pane1.add(imgLabel1);
pane1.add(notiLabel1);
JLabel pokeLabel1 = new JLabel(new ImageIcon(DF));
JLabel pokeLabel2 = new JLabel(new ImageIcon(DF));
JLabel pokeLabel3 = new JLabel(new ImageIcon(DF));
JLabel pokeLabel4 = new JLabel(new ImageIcon(DF));
JLabel pokeLabel5 = new JLabel(new ImageIcon(DF));
JLabel pokeLabel6 = new JLabel(new ImageIcon(DF));
pane1.add(pokeLabel1);
pane1.add(pokeLabel2);
pane1.add(pokeLabel3);
pane1.add(pokeLabel4);
pane1.add(pokeLabel5);
pane1.add(pokeLabel6);
pane2.add(label2);
layout.add("Pearl Version", pane1);
layout.add("SoulSilver Version", pane2);
frame.add(layout);
}
public void pearlButtons()
{
PGroup = new ButtonGroup();
R1 = new JRadioButton("No Restrictions", true);
R1.setActionCommand("N");
R1.setVisible(true);
R2 = new JRadioButton("Battle Revolution");
R2.setActionCommand("BR");
R2.setVisible(true);
R3 = new JRadioButton("Battle Tower");
R3.setActionCommand("B");
R3.setVisible(true);
PGroup.add(R1);
PGroup.add(R2);
PGroup.add(R3);
PSubmit = new JButton("Submit");
PSubmit.setActionCommand("pstart");
PSubmit.setVisible(true);
PSubmit.addActionListener(this);
}
public void pearlProcessing()
{
//The "list" array has a bunch of string names that get .png affixed to them (and I named the image files as such when I name them)
String file1 = list[0] + ".png";
String file2 = list[1] + ".png";
String file3 = list[2] + ".png";
String file4 = list[3] + ".png";
String file5 = list[4] + ".png";
String file6 = list[5] + ".png";
/*-------------------------------------------------------------------------------//
This is where the method's supposed to go to change the image...
I've tried pokeLabel = new JLabel(new ImageIcon(file1));, but that yields a NullPointerException.
//-----------------------------------------------------------------------------------*/
}
public static void main(String[] args)
{
Shell test = new Shell();
test.setFrame();
test.frameLayout();
test.frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if ("pstart".equals(e.getActionCommand()))
{
result = PGroup.getSelection().getActionCommand();
if (result.equals("N"))
{
list = driver.Prandom();
pearlProcessing();
}
else
System.out.println("Not done yet! ;)");
}
}
public void menuKeyPressed(MenuKeyEvent e)
{
System.out.println("pressed");
}
public void menuKeyReleased(MenuKeyEvent e)
{
System.out.println("menuKeyReleased");
}
public void menuKeyTyped(MenuKeyEvent e)
{
System.out.println("menuKeyTyped");
}
}
Without knowing if this is the cause, I would change
result = PGroup.getSelection().getActionCommand();
if (result.equals("N")) {
to
ButtonModel selection = PGroup.getSelection();
result = (selection==null ? null : selection.getActionCommand());
if ("N".equals(result)) {
// etc...
This guards against likely null pointers.
I highly suggest whenever you get any exception to always look at the stack trace and see where the actual line the exception occurred at was.
But if I were to speculate, you call PGroup.getSelection() in your actionPerformed method. This method may return null if there is no button selected in your radio button group. I also noticed that you do not set an initially selected radio button (call setSelected(true) on the radio button). Thus, if the selected radio button is null calling getActionCommand will result in a NullPointerException.