try and catch java with files in a GUI - java

private class PrintButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == radio){
try{
File file = new File("Birds.txt");
Scanner inputFile = new Scanner(file);
area.setText(inputFile.toString());
}
catch(Exception ex){
System.out.println("File not found!");
}
}
}
}
I need to display 2 different files. Each file has an associated radio button. The content of the files must display on the GUI interface once the button is clicked. I really need help with this one!
private JRadioButton radio; // first radio button
private JRadioButton radio2; // second radio button
private JRadioButton radio3; // third radio button
private JButton button; // button to gain access to whatever option was selected
private JPanel panel; // the panel
private JTextArea area;
private ButtonGroup buttonGroup;
public BirdTest2(){ // GUI constructor
super();
setSize(2000,950);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
buildPanel();
add(panel);
}
public void buildPanel(){ // building the panel for the GUI
panel = new JPanel();
radio = new JRadioButton("Display all birds!");
radio2 = new JRadioButton("Display foreign birds only!");
radio3 = new JRadioButton("Display non-foreign birds only!");
button = new JButton("Click me!");
button.addActionListener(new PrintButtonListener());
buttonGroup = new ButtonGroup();
buttonGroup.add(radio);
buttonGroup.add(radio2);
buttonGroup.add(radio3);
area = new JTextArea();
panel.add(radio);
panel.add(radio2);
panel.add(radio3);
panel.add(button);
panel.add(area);
}
Here is the code I have above the previous for my window, button, radio buttons. Help would be greatly appreciated! Please let me know if you need any additional info :)

The content of the files must display on the GUI interface once the button is clicked.
To read a File using Scanner, you have to explicitly iterate over all the lines of the file using the methods defined by the Scanner object you are using (the toString currently used in actionPerformed will only return a String representing the Scanner object, which isn't necessarily the contents of the File).
Scanner inputFile = new Scanner(file);
while ( inputFile.hasNextLine() ){
area.append(inputFile.nextLine());//append the line to the JTextArea
area.append("\n");//append any new lines as they are ommitted with Scanner.nextLine
}
You can check which JCheckBox is selected in the actionPerformed method to determine which File to open based upon which JCheckBox is selected.

Related

How to make JButton know on which panel it has been clicked on?

I'm trying to simulate a car renting system on a GUI.
Since I'm not very experienced with Swing components I decided to create a car list using GridBagLayout.
Each row has different panels each having different rental prices and car names.
CarList
The "Details" button is shared through all the panels in the list. I'm looking for a way in which "Details" gets the title and price text from the panel were it was pressed, then saves them inside variables.
so far whenever I press it, it only saves and sends the text from the last panel in the list even if I pressed the first button in the list.
CarDetails
This is the button's Event:
JButton btnNewButton = new JButton("details");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Car, price;
Car = Name.getText();
price = Price.getText();
Main.add(new CarD(Car,price), "2");
cl.show(Main, "2");
add.setVisible(false);
}
});
EDIT:
Following camickr's example, all that was left was to get the labels from the parent Panel using the location where they are placed within it.
JButton btnNewButton = new JButton("Details");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Car, price;
JButton button = (JButton)e.getSource();
JPanel panel = (JPanel)button.getParent();
JLabel N = (JLabel)panel.getComponentAt(202, 62);
JLabel P = (JLabel)panel.getComponentAt(202, 24);
Car = N.getText();
price = P.getText();
Main.add(new CarD(Car,price), "2");
cl.show(Main, "2");
add.setVisible(false);
}
});
In the ActionListener of your "Details" button you can get the button from the ActionEvent and the panel from the button:
JButton button = (JButton)e.getSource();
JPanel panel = (JPanel)button.getParent();
In ActionListener try this :
public void actionListener(ActionEvent evt)
{
if(evt.getSource()==b1) // b1 is button variable
{
//code
// this will run if you click on b1 button
}
if(evt.getSource()==b2) // b2 is another button variable
{
//code
// this will run if you click on b2 button
}
}

How to refresh / reload / completely close and reopen jframe

I've read the similar questions regarding this problem, tried few methods but none is working.
I have 2 JFrame forms. I want to input information in the first form and submit it to the database. When I click a button, the second form will open and load the information
When I re-input new information in the first form and click the the button again, I want the second form to reload the new information inputted from the database.
This is my code so far.
time t = new time();
private void OrderButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(t.isVisible()){
t.dispose();
t.revalidate();
t.repaint();
t.setVisible(true);
t.setLocationRelativeTo(null);
}
else{
t.setVisible(true);
t.setLocationRelativeTo(null);
}
You don't need to play with JFrames for that. See below example :
JLabel toe = new JLabel("I'm primary text");
JFrame cow = new JFrame("Primary Window");
JPanel cowpanel = new JPanel();
cowpanel.add(toe);
cow.setContentPane(cowpanel);
cow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
cow.pack();
cow.setVisible(true);
JButton tow = new JButton("Change");
tow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
toe.setText("Hi!, I'm secondary text!");
}
});
JFrame dog = new JFrame("Secondary Window");
JPanel dogPanel = new JPanel();
dog.setContentPane(dogPanel);
dogPanel.add(tow);
dog.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
dog.pack();
dog.setVisible(true);
Clicking the 'Change' button from Frame 2 will change the JLabel's text in Frame 1.

ActionListener nested within an ActionListener? [duplicate]

This question already has answers here:
Detect enter press in JTextField
(10 answers)
Closed 7 years ago.
I have a program that has three functions; to read a file, write to a file and search for specific text within a file. I'm currently working on creating a GUI to use with it so that I will no-longer rely on the console. I've already created a fully functional "main window" and functional buttons with respect to the three aforementioned functions, as well as an exit button. Now I'm working on the GUI window for my Search function - the window is created as the response to the Search button being clicked. I have the window and components layed out the way I want but I'm having trouble setting up the action listener for when the user presses Enter after inputting the string they wish to search for. I've looked at a number of different sources including SOverflow, the javadoc and actionlistener tutorials; but I'm getting nowhere fast.
Here is the base code to draw the Search button in the main window and link to the Search GUI (I linked to this through main):
public class SimpleDBGUI{
static File targetFile; //Declare File var to be used in methods below for holding user's desired file
static JTextField sdbTarget;
static JTextField searchTerm;
public void mainWindow(){
//Create main window for Program
JFrame mainWindow = new JFrame("Simple Data Base"); //Init frame
mainWindow.setSize(500, 180); //Set frame size
mainWindow.setVisible(true); //Make frame visible
//Create panel for the main window of the GUI
JPanel simpleGUI = new JPanel( new GridBagLayout());
GridBagConstraints gbCons = new GridBagConstraints();
mainWindow.getContentPane().add(simpleGUI); //Adds JPanel container to the ContentPane of the JFrame
//Create button linking to the search function
JButton searchButton = new JButton("Search"); //Init button with text
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 1;
gbCons.gridy = 2;
gbCons.weightx = .1;
searchButton.setActionCommand("Search");
searchButton.addActionListener( new ButtonClickListener());
simpleGUI.add(searchButton, gbCons); //Adds the "Search" button to the JPanel
//Create TextField for user to input a desired file
sdbTarget = new JTextField();
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 0;
gbCons.gridy = 1;
gbCons.gridwidth = 3;
simpleGUI.add(sdbTarget, gbCons); //Adds TextField to GUI
}
public class ButtonClickListener implements ActionListener{ //Sets the EventListener for every function
public void actionPerformed(ActionEvent event){
targetFile = new File(sdbTarget.getText());
String function = event.getActionCommand(); //Reads the ActionCommand into a string for use in performing desired function
if( function.equals("Search")){ //Search Function, draws search window and components
JFrame searchWindow = new JFrame("SimpleDB Search"); //Draw window
searchWindow.setSize(500, 200);
searchWindow.setVisible(true);
JPanel searchGUI = new JPanel( new GridBagLayout()); //Create container and add to window
GridBagConstraints gb1Cons = new GridBagConstraints();
searchWindow.getContentPane().add(searchGUI);
JLabel searchPrompt = new JLabel("Please input the word/phrase you wish to find:"); //Prompt user to specify string to search for
gb1Cons.fill = GridBagConstraints.BOTH;
gb1Cons.gridy = 0;
gb1Cons.gridx = 0;
//gb1Cons.weighty = .1;
searchGUI.add(searchPrompt, gb1Cons); //Add prompt to container
JTextField searchTerm = new JTextField(); //Create JTextField for user input and add to container
gb1Cons.fill = GridBagConstraints.BOTH;
gb1Cons.gridy = 1;
gb1Cons.gridx = 0;
//gb1Cons.weighty = .1;
searchGUI.add(searchTerm, gb1Cons);
searchTerm.addActionListener(this); //Assign ActionListener to JTextField
JTextArea searchResult = new JTextArea(); //Create search output box and add to container
gb1Cons.fill = GridBagConstraints.BOTH;
gb1Cons.gridy = 2;
gb1Cons.gridx = 0;
//gb1Cons.weighty = .1;
searchGUI.add(searchResult, gb1Cons);
public void actionPerformed( ActionEvent event){ //Tried this as one event handler, supposed to execute the following upon the user pressing Enter, failed of course
boolean stringFound = false; //Set flag false
try{
Scanner searchFile = new Scanner(targetFile); //Read file to be searched into a scanner
String searchInput = searchTerm.getText(); //Read term to search for into a string
while( searchFile.hasNextLine()){ //Check that specified file has a next line and:
String searchLine = searchFile.nextLine(); //Read line into string
if( searchLine.contains(searchInput)){ //Check that Line contains searched term and:
stringFound = true; //If line contains term, set flag to true
searchResult.append("**" + searchLine + "**"); //Append line with term to output box
}
}searchFile.close(); //Close scanner
if(!stringFound){
searchResult.append("The term(s) you searched for does not exist in this file"); //Output if line does not contain term
}
}catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
You should try to re-structure your code some
I would not create the GUI within an actionPerformed, create it outside (or make a class for it extend JFrame), and in actionPerformed, just display it setVisible(true).
Even if this suggestion is not your problem, it would probably solve it.
Your current situation is:
Your are adding the actionListener to JTextField searchTerm, the actionListener that your are adding is actually the ButtonClickListener so you already have an actionPerformed method,hence same method!!!
So outcome is:
when you press enter in your searchTerm the ButtonClickListener.actionPerformed will be called and if you try to write "Search" in the textfield you will see something interesting!!
A short code for adding a new actionListener would be
searchTerm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//DO YOUR STUFF
}
});
Just paste this code in your constructor.
Hope it'll help. Remember your searchTerm should be of jtextfield as the code for jtextxarea is bit different.
searchTerm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionPerformed(e);
}
});

ActionListener on a JButton does not perform any action

I have a slight issue with my Actionlistener, when i click button nothing happens ?? I do not see where the problem is, so another pair of eyes could help me out :)
public class GameOptions extends JPanel implements ActionListener{
public GameOptions(){
System.out.println("GameOptions Class test blabla");
easyButton().addActionListener(this);
mediumButton().addActionListener(this);
hardButton().addActionListener(this);
JPanel center = new JPanel(new GridLayout(4,1,10,10));
center.add(new JLabel("Chose Difficulty Level"));
center.add(easyButton());
center.add(mediumButton());
center.add(hardButton());
this.add(center, BorderLayout.CENTER);
this.setPreferredSize(this.getPreferredSize());
this.setFocusable(true);
this.requestFocusInWindow();
}
private JButton easyButton(){
JButton levelEasy = new JButton("Easy");
return levelEasy;
}
private JButton mediumButton(){
JButton levelMedium = new JButton("Medium");
return levelMedium;
}
private JButton hardButton(){
JButton levelHard = new JButton("Hard");
return levelHard;
}
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if(src == easyButton()){
System.out.println("Easy");
}
else if(src == mediumButton()){
System.out.println("Medium");
}
else if(src == hardButton()){
System.out.println("Hard");
}
else{
}
}
}
Your xxxButton() methods create new JButtons each time, and so you add the ActionListener to a newly created JButton and then discard the button, and then add a completely different JButton, one without the ActionListener to the GUI.
Suggestion: create your JButtons, set a variable to them, add your ActionListener, and add the same button to the GUI.
So instead of this:
easyButton().addActionListener(this); // creates one JButton
center.add(easyButton()); // creates a completey different JButton
do this:
JButton easyButton = easyButton();
easyButton.addActionListener(this);
center.add(easyButton);
Note, if this were my code, I'm not sure that I'd use JButtons at all. Instead perhaps I'd use either JRadioButtons or a JComboBox.
You're creating each JButton with a function. And later you try to add it like center.add(easyButton()); but the one you added a ActionListener isn't the same button as this one. You're creating each one with new, so the reference isn't the same.
You should do it like this:
JButton buttonEasy = easyButton();
buttonEasy.addActionListener(this);
center.add(buttonEasy);

Actionlistener java

For my class I need to use my ActionListener. I am having trouble adding my ActionListener to my buttons. I have to use the word "this" like this.buttons to add my ActionListener but Im having trouble doing that. I will get to my actionPerformed method later but my main problem is my ActionListener.
public class TextButtonsHW extends JFrame implements ActionListener {
private JButton[] buttons; //Do not change
private JTextArea textArea; //Do not change
//Assign values for these constants in the constructor
private final int ENTER; //Index of Enter button in buttons
private final int SPACE; //Index of Space button in buttons
private final int CLEAR; //Index of Clear button in buttons
/**
* Set up this frame and its contents.
* #param title Title to appear in JFrame title bar
*/
public TextButtonsHW(String title) {
super(title); //call parent JFrame constructor to set the title
buttons = new JButton[] { new JButton("A"), new JButton("B"), new JButton("C"),
new JButton("1"), new JButton("2"), new JButton("3"),
new JButton("X"), new JButton("Y"), new JButton("Z"),
new JButton("Enter"), new JButton("Space"), new JButton("Clear")};
ENTER = buttons.length-3;
SPACE = buttons.length-2;
CLEAR = buttons.length-1;
textArea = new JTextArea(15, 5);
textArea.setEditable(false);
this.buttons[0].addActionListener(I dont know what to put right here);
//TODO: instantiate all JButtons, add them to the buttons array,
// and register "this" as the ActionListener for each button.
//DONE
//TODO: assign values to ENTER, SPACE, and CLEAR constants to
// indicate the indexes of those buttons in the buttons array
//DONE
//TODO: create the JTextArea textArea
//TODO: set its "editable" property to false
//DONE
//Create a TextButtonsHWPanel to display the buttons and textArea
TextButtonsHWPanel mainPanel = new TextButtonsHWPanel(buttons, textArea);
this.getContentPane().add(mainPanel);
this.pack();
}
public void actionPerformed(ActionEvent e) {
//TODO: update the text of textArea according to which
// button generated the ActionEvent.
}
public static void main(String[] args) {
final TextButtonsHW f = new TextButtonsHW("Text Buttons");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null); //centers frame on screen
f.setVisible(true);
}
}
buttons[0].addActionListener(this);
Since you have 12 buttons you could also go for a for-loop to add ActionListener to all your buttons i.e.
for(int i=0; i<12; i++)
{
buttons[i].addActionListener(this);
}
Instead of a long code i.e.
buttons[0].addActionListener(this);
buttons[1].addActionListener(this);
........................
Though buttons[0].addActionListener(this); will work well, From design perspective I will suggest to have separate class (may be inner class) which implements ActionListner and pass its object reference to the method.
the whole point of Object Oriented programming is to delegate different responsibilities to different Objects(classes), so code becomes more maintainable and reusable.

Categories