How can I make this program multi windowed? - java

I am learning Java and I though as good practice I could make a simple GUI program.
I'm hoping my program will be able to search read and write a text file.
I got all my components looking how I want them too.
I have 4 panels searchPanel, readPanel, writePanel, and the mainMenuPanel they are displayed on the mainframe JFrame.
Now what I want to do (this is where I could really use your guys' help) is how to make this program multi windowed?
i.e if I press the read button in the mainMenuPanel it will display the readPanel. and so on with the other buttons.
I hope my question makes senses and that you guys can help me.
This is my code:
package MyGUIStuff;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Scanner;
public class multiWinDemo {
public static void main (String args []) {
/* Search Panel Ingredients
* Label : File Name
* TextField : look for ...
* Button - Search
* Button - Back
* TextArea - Results found ...
*/
JLabel fileNameStorage1 = new JLabel ("File Name");
JTextField searchFor = new JTextField (20);
JButton searchBtnPanel = new JButton ("Search:");
JButton backButton1 = new JButton ("Back");
JTextArea searchedArea = new JTextArea ("Text Area Here!\nName : Misael\nIf this worked\nthen i should\nbe able to\nuse JScrollPane\ncorrectly", 5,20);
searchedArea.setEditable(false);
//searchedArea.setPreferredSize(new Dimension(100,100) );
JScrollPane searchedAreaScoller = new JScrollPane (searchedArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
/* Write Panel Ingredients
* Label : File Name
* TextField : write this text to file ...
* Button : Write
* Button : Back
*/
JLabel fileNameStorage2 = new JLabel ("File Name:");
JTextField writeThis = new JTextField (20);
JButton writeButton = new JButton ("Write");
JButton backButton2 = new JButton ("Back");
/* Read Panel Ingredients
* Label : File Name
* Button - Back
* TextArea - File That I Chose
*/
JLabel fileNameStorage3 = new JLabel ("File Name Here");
JButton backButton3 = new JButton ("Back");
JTextArea readTextArea = new JTextArea ("Text Area Here" ,5 , 20);
readTextArea.setEditable(false);
JScrollPane readScrollPane = new JScrollPane (readTextArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
/* Main Menu Panel Ingredients
* Label : "File Name"
* TextField : File Absolute Path
* Button - Browse
* Button - Search
* Button - Write
* Button - Read
* Button - Exit
*/
JLabel lbl1 = new JLabel ("File Name:");
JTextArea howTo = new JTextArea ("Search: Search a text file.\nWrite: Write to a text file.\nRead: Read a text file.", 3, 20);
howTo.setEditable(false);
JTextField filePath = new JTextField (20);
JButton browseBtn = new JButton ("Browse");
JButton searchBtn = new JButton ("Search");
JButton writeBtn = new JButton ("Write");
JButton readBtn = new JButton ("Read");
JButton exitBtn = new JButton ("Exit");
//Search Panel
JPanel searchPanel = new JPanel ();
//searchPanel.setLayout(new GridLayout (3,9,5,5) );
searchPanel.setVisible(false);
searchPanel.add(fileNameStorage1);
searchPanel.add(searchFor);
searchPanel.add(backButton1);
searchPanel.add(searchBtnPanel);
searchPanel.add(searchedAreaScoller);
//Write Panel
JPanel writePanel = new JPanel ();
//writePanel.setLayout(new GridLayout (3,9,5,5) );
writePanel.setVisible(false);
writePanel.add(fileNameStorage2);
writePanel.add(writeThis);
writePanel.add(backButton2);
writePanel.add(writeButton);
//Read Panel
JPanel readPanel = new JPanel ();
//readPanel.setLayout(new GridLayout (3,9,5,5) );
readPanel.setVisible(false);
readPanel.add(fileNameStorage3);
//readPanel.add(readTextArea);
readPanel.add(readScrollPane);
readPanel.add(backButton3);
//Main Menu Panel
JPanel blank1 = new JPanel ();
JPanel mainMenuPanel = new JPanel ();
mainMenuPanel.setVisible(true);
//mainMenuPanel.setLayout(new GridLayout (3,9,5,5) );
mainMenuPanel.add(lbl1);
mainMenuPanel.add(filePath);
mainMenuPanel.add(browseBtn);
mainMenuPanel.add(searchBtn);
mainMenuPanel.add(writeBtn);
mainMenuPanel.add(readBtn);
mainMenuPanel.add(howTo);
mainMenuPanel.add(exitBtn);
//Program Frame
JFrame mainFrame = new JFrame ("File Control");
mainFrame.setSize(300,235);
mainFrame.setLayout(new CardLayout() );
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.add(mainMenuPanel);
mainMenuPanel.add(searchPanel);
mainMenuPanel.add(writePanel);
mainMenuPanel.add(readPanel);
}
}
Note: what I've tried so far is: since all 4 panels are being displayed on the frame (frame has a card layout). what I did was try and add action listeners to the searchBtn and set the mainMenuPanel Visible false and searchPanel true, but nothing happened. How can I make it multi windowed?

You can add an ActionListener to the JButton and then an ActionPerformed that opens the other GUI window.
If you need documentation you can find it here --> event handler

From what I'm reading what you are trying to do is when you press a button you want another panel to start up. There are various ways to do this, in my experience you'd want to use an actionListener with your button. Here is some code that I have written based on a simple finance calculator that you can use as a reference. Notice it's using a Combobox and calling the method getselecteditems() to get each selection from a combo box on my main panel.
I then use the add() to add the panel and removeall() and remove() to remove it.
private class financeBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String selection = (String) financeBox.getSelectedItem();
if(selection.equals("Present value")){
//financeFinderPanel.removeAll();
presentValuePanel();
add(presentValuePanel, BorderLayout.NORTH);
financeFinderPanel.removeAll();
remove(financeFinderPanel);
pack();
}
else if(selection.equals("Simple interest")){
simpleInterestPanel();
add(simpleInterestPanel, BorderLayout.SOUTH);
financeFinderPanel.removeAll();
remove(financeFinderPanel);
pack();
}
else if(selection.equals("Doubling time")){
doublingTimePanel();
add(doublingTimePanel, BorderLayout.NORTH);
financeFinderPanel.removeAll();
remove(financeFinderPanel);
pack();
}
else if(selection.equals("Compound interest")){
compoundInterestPanel();
add(compoundInterestPanel, BorderLayout.EAST);
financeFinderPanel.removeAll();
remove(financeFinderPanel);
pack();
}
else if(selection.equals("Future value"))
{
futureValuePanel();
add(futureValuePanel, BorderLayout.WEST);
financeFinderPanel.removeAll();
remove(financeFinderPanel);
pack();
}
else if(selection.equals("Choose a formula")){
setSize(200, 125);
financeFinderPanel();
add(financeFinderPanel, BorderLayout.NORTH);
NONEMessage = new JLabel("PICK A SELECTION");
}
}
}
There are many other ways to do this, and this might not be the best way in your case. There is something called actionCommand and source which get the actually command that has been called, "you can use this with buttons."
like this...
if(actionCommand.equals("Calc Simple Interest")){
try{
double principal = Double.parseDouble(principalText.getText());
double yearlyRate = Double.parseDouble(yearlyRateText.getText());
double termYears = Double.parseDouble(termYearsText.getText());
double interestRate = financeFormula.simpleInterest(principal, yearlyRate, termYears);
//double interestRate = (principal * yearlyRate * termYears);
String msg = "Simple interest is: $" + dc.format(interestRate);
JOptionPane.showMessageDialog(null, msg);
simpleInterestPanel.removeAll();
remove(simpleInterestPanel);
financeFinderPanel();
add(financeFinderPanel, BorderLayout.NORTH);
pack();
}
In this example the name of the button I clicked is Calc Simple Interest.

Related

Buttons are doing actions assigned to other buttons via actionlistener

I just have a small problem with my code; I'm currently using a cardlayout wherein I currently have 3 buttons. 1(on the initial panel) adds JLabels to the initial panel,another(also on the initial panel) switches to the second panel which just contains the 3rd button that returns to the initial panel. My problem is that clicking the buttons for swapping between panels also triggers the first button which creates JLabels.
Here is part of my code:
actionListener al = new actionListener();
actionListener al2 = new actionListener();
actionListener al3 = new actionListener();
adddeck.addActionListener(al);//creates JLabels on panel1
addcardbutton.addActionListener(al2);//goes to panel2
goback.addActionListener(al3)//returns to panel1
Then the actionlistener part:
public class actionListener implements ActionListener{
public void actionPerformed(ActionEvent event) {
JButton src = (JButton) event.getSource();
if(event.getSource()==adddeck)
decklist.add(new Deck(newdeck.getText()));
//panel for label/buttons
JPanel deckpanel;
deckpanel= new JPanel();
deckpanel.setLayout(new GridLayout(1,2));
//label with new deck name
JLabel decklabel;
decklabel = new JLabel(newdeck.getText());
deckpanel.add(decklabel);
deckpanel.revalidate();
//label with # of cards
JLabel cardamt;
cardamt = new JLabel(i +"cards");
deckpanel.add(cardamt);
deckpanel.revalidate();
//add panel
initial.add(deckpanel);
initial.revalidate();
if(event.getSource()==addcardbutton)
cardLayout.show(contentPanel,"adding");
if(event.getSource()==goback)
cardLayout.show(contentPanel,"initial");
You have not used curly braces ({) for the if statements. When an if statement does not have curly braces, only the line just after if is included in the if block.
For example your code
if(event.getSource()==adddeck)
decklist.add(new Deck(newdeck.getText()));
//panel for label/buttons
JPanel deckpanel;
deckpanel= new JPanel();
deckpanel.setLayout(new GridLayout(1,2));
//label with new deck name
JLabel decklabel;
decklabel = new JLabel(newdeck.getText());
deckpanel.add(decklabel);
deckpanel.revalidate();
is equivalent to:
if(event.getSource()==adddeck) {
decklist.add(new Deck(newdeck.getText()));
}
//panel for label/buttons
JPanel deckpanel;
deckpanel= new JPanel();
deckpanel.setLayout(new GridLayout(1,2));
//label with new deck name
JLabel decklabel;
decklabel = new JLabel(newdeck.getText());
deckpanel.add(decklabel);
deckpanel.revalidate();
So, the code starts from line //panel for label/buttons is always executed regardless of the button you click.

Dynamically add JCombobox and JTextField

I want to add a JComboBox and a JTextField to a panel when there is an item selected in the combobox.
I have this code for the panel.
aantallenGebruikt.add(new JTextField("", 5));
onderdelenGebruikt.add(new JComboBox(onderdelenBox()));
onderdelenGebruikt.get(0).addActionListener(MyFrame.this);
panelAfronden = new JPanel();
panelAfronden.setLayout(new FlowLayout());
panelAfronden.add(new JLabel("Selecteer onderdeelNr en Vul gebruikte aantallen in"));
panelAfronden2 = new JPanel();
panelAfronden2.setLayout(new FlowLayout());
panelAfronden2.add(onderdelenGebruikt.get(0));
panelAfronden2.add(aantallenGebruikt.get(0));
JScrollPane sPane = new JScrollPane(panelAfronden2);
sPane.setPreferredSize(new Dimension(220, 230));
panelAfronden.add(sPane);
panelAfronden.add(new JLabel("Opmerkingen"));
opmerkingenAfronden = new JTextArea(5, 20);
panelAfronden.add(opmerkingenAfronden);
rondAf = new JButton("Rond Werkzaamheid Af");
rondAf.addActionListener(MyFrame.this);
panelAfronden.add(rondAf);
annuleer = new JButton("Annuleer");
annuleer.addActionListener(MyFrame.this);
panelAfronden.add(annuleer);
I have this in the ActionListener
if( eventSource == onderdelenGebruikt){
System.out.println("test");
}
I know how to add the combobox and textfield to the panel but At the moment it doesn't even print out the test to the console
Your Question:
I know how to add the combobox and textfield to the panel but At the moment it doesn't even print out the test to the console.
Answer:
Store the reference of JcomboBox some where and then check the source in ActionListener.
do in this way:
final JComboBox comboBox = new JComboBox(onderdelenBox());
onderdelenGebruikt.add(comboBox);
comboBox.addActionListener(MyFrame.this);
Your ActionListener will look like this.
if( eventSource == comboBox ){
System.out.println("test");
}

Can't update JPanel

I have a JTable which contains a list of item and a JPanel with some components. When I click to my button, I want all information of the selected item in the JTable will be loaded to the JPanel. At the first time, it work well but at the further times when I click to my button the Jpanel appears with empty component.
The code when clicking to my button:
jbtUpdateContract.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
Object contractID = getValueOfSelectedRow(contractTable, 0);
Contract contract = contractTransaction.getContractByID(Integer.parseInt(contractID.toString()));
//Create Jpanel to display information
jplUpdateContractForm.removeAll();
jplUpdateContractForm = createContractForm(contract);
jplUpdateContractForm.revalidate();
//Modify contract frame
jfrmUpdateContract.getContentPane().add(jplUpdateContractForm,
BorderLayout.CENTER);
jfrmUpdateContract.setSize(400, 300);
jfrmUpdateContract.setVisible(true);
jfrmUpdateContract.setResizable(false);
}
});
And my createContractForm function:
public static JPanel createContractForm(Contract contract)
{
JPanel jplContractForm = new JPanel(new SpringLayout());
JLabel jlblAppointmentDate = new JLabel("Appointment date:", JLabel.TRAILING);
jlblAppointmentDate.setName("jlblAppointmentDate");
jplContractForm.add(jlblAppointmentDate);
final JTextField jtxtAppointmentDate = new JTextField(15);
jtxtAppointmentDate.setName("jtxtAppointmentDate");
jtxtAppointmentDate.setText(contract.getAppointmentDate());
jtxtAppointmentDate.setEditable(false);
jtxtAppointmentDate.addMouseListener(appointmentDateMouseListener(jtxtAppointmentDate));
jlblAppointmentDate.setLabelFor(jtxtAppointmentDate);
jplContractForm.add(jtxtAppointmentDate);
jplContractForm.setOpaque(true);
//***Customer Cobobox
JLabel jlblCustomer= new JLabel("Customer:", JLabel.TRAILING);
jlblCustomer.setName("jlblCustomer");
jplContractForm.add(jlblCustomer);
final JComboBox jcbxCustomer = new JComboBox();
jcbxCustomer.setName("jcbxCustomer");
//Load customers from DB to combobox
Customer[] customers = customerTransaction.getAllCustomer();
for(int i = 0; i < customers.length; i++)
jcbxCustomer.addItem(customers[i]);
System.out.println("----------CUSTOMER----------" + getIndexOfCustomerComboBoxItem(jcbxCustomer, contract.getCustomerSeq()));
jcbxCustomer.setSelectedIndex(getIndexOfCustomerComboBoxItem(jcbxCustomer, contract.getCustomerSeq()));
jlblCustomer.setLabelFor(jcbxCustomer);
jplContractForm.add(jcbxCustomer);
jplContractForm.setOpaque(true);
}
Please help me to explaint why the JPanel is empty as I describes above.
Regards.
The frame is already visible, so I don't think any of these lines of code will help.
jfrmUpdateContract.setSize(400, 300);
jfrmUpdateContract.setVisible(true);
jfrmUpdateContract.setResizable(false);
The revalidate() does nothing because you haven't added the panel to the frame yet. Try the revalidate() AFTER the panel has been added to the frame.
jplUpdateContractForm = createContractForm(contract);
//jplUpdateContractForm.revalidate();
jfrmUpdateContract.getContentPane().add(jplUpdateContractForm, BorderLayout.CENTER);
jplUpdateContractForm.revalidate();
If you need more help then post a proper SSCCE.

How to display different JPanels in the same region of the panel with clicking a button

I want a different JPanel to be displayed when I press a button. The other two JPanels that are displayed in the panel are not to be moved. I've tried, but when pressing the button, nothing happens. When pressing the button even times, many textfields must be displayed, else a simple scrollpane. Here is the code:
final JPanel choseTypeOfAnswer = new JPanel();
choseTypeOfAnswer.add(radioBox);
radioBox.setToolTipText("Answer in form of radiobox");
radioBox.setIcon(GUI.createImageIcon("check.png"));
radioBox.setAlignmentX(Component.LEFT_ALIGNMENT);
radioBox.setPreferredSize(new Dimension(30, 20));
radioBox.setVisible(true);
radioBox.addActionListener(new ActionListener(){
private int clicked;
public void actionPerformed(ActionEvent e){
clicked++;
//reset contents of the image preview field
if((clicked % 2) == 0){
add(new JLabel("<html><b>Answer:</b>"));
JTextField textField = new JTextField(20);
JTextField textField1 = new JTextField(20);
JTextField textField2 = new JTextField(20);
JTextField textField3 = new JTextField(20);
choseTypeOfAnswer.add(textField);
choseTypeOfAnswer.add(textField1);
choseTypeOfAnswer.add(textField2);
choseTypeOfAnswer.add(textField3);
add(BorderLayout.NORTH,choseTypeOfAnswer);
}else{
add(new JLabel("<html><b>Answer:</b>"));
//now a scroll pane for the answer area
JScrollPane answerScroller = new JScrollPane(answerArea);
answerScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
answerScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
choseTypeOfAnswer.add(answerScroller);
//add(answerScroller);
add(choseTypeOfAnswer);
}
}
});//den emfanizei tpt me to patima tou koympiou
add(choseTypeOfAnswer);
//holds the bottom two components: "important" checkbox, "create card" button
JPanel bottomContainer = new JPanel();
//bottomContainer.setLayout(new BoxLayout(bottomContainer,BoxLayout.PAGE_AXIS));
//important.setAlignmentX(Component.CENTER_ALIGNMENT);
//bottomContainer.add(important);
createCard.setText("Finish and add card");
createCard.setIcon(GUI.createImageIcon("check.png"));
createCard.setAlignmentX(Component.CENTER_ALIGNMENT);
createCard.setAlignmentY(Component.BOTTOM_ALIGNMENT);
createCard.setPreferredSize(new Dimension(180, 45));
createCard.addActionListener(new cardListener());
bottomContainer.add(createCard);
//now add the bottom container
add(bottomContainer, BorderLayout.SOUTH);
Use Component#setVisible(...) making one panel visible, and hide the other.

Java - How to add new JLabel and JTextPane to JPanel when button is pressed

I have a JPanel to which when a button is pressed I want to add a new JLabel and JTextField too. However, I can't seem to get it working.
Is there an issue with my ActionListener, and if not, how could this be achieved?
JPanel south = new JPanel();
JButton add = new JButton("Add");
ActionListener addListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JLabel mL = new JLabel("MOD: ");
mR.add(mL);
JTextField mM = new JTextField(10);
mR.add(mM);
mR.repaint();
}
};
add.addActionListener(addListener);
south.add(add);
add(south, BorderLayout.NORTH);
The layout of the mR panel is a grid layout set to allow multiple rows and two columns.
Call mR.revalidate() before repaint();
See my answer on a previous SO question for some sample code which dynamically adds a component to a container

Categories