Java GUI not showing anything - java

I am new to Java and I am creating a Gui. I don't have any error but when I ran the main nothing is shown.
I can not understand why. Can please someone help?
Here is my code of the GUI:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
public class DartsGUI implements ActionListener {
//Gui components
JFrame mainDartsFrame;
JPanel buttonsPanel,infoPanel;
JRadioButton viewTableAsc,viewTableDesc,editScores,viewDetails,searchById;
CardLayout cLayout;
JTextArea table1,table2;
JScrollPane scrollTable1,scrollTable2;
JLabel edit,details,search;
public void DartGUI() {
mainDartsFrame= new JFrame("Darts Competition");
mainDartsFrame.setSize(700, 500);
mainDartsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainDartsFrame.setLayout(new BorderLayout());
mainDartsFrame.setLocationRelativeTo(null);
createButtonsPanel();
createInfoPanel();
mainDartsFrame.setVisible(true);
}
private void createButtonsPanel() {
JPanel buttonsPanel = new JPanel( new GridLayout(5,1) );
viewTableAsc= new JRadioButton("Info Ascending Order");
viewTableAsc.addActionListener(this);
viewTableDesc= new JRadioButton("Info Descending Order");
viewTableDesc.addActionListener(this);
editScores= new JRadioButton("Edit Scores");
editScores.addActionListener(this);
viewDetails= new JRadioButton("View Details");
viewDetails.addActionListener(this);
searchById=new JRadioButton("Search Competitor");
searchById.addActionListener(this);
//Group radio buttons to ensure only one is chosen each time
ButtonGroup radioButtons = new ButtonGroup();
radioButtons.add(searchById);
radioButtons.add(viewTableAsc);
radioButtons.add(viewTableDesc);
radioButtons.add(editScores);
radioButtons.add(viewDetails);
//Push buttons into the buttons Panel
buttonsPanel.add(viewTableAsc);
buttonsPanel.add(viewTableDesc);
buttonsPanel.add(editScores);
buttonsPanel.add(viewDetails);
buttonsPanel.add(searchById);
mainDartsFrame.add(buttonsPanel,BorderLayout.WEST);
}
private void createInfoPanel() {
infoPanel = new JPanel();
cLayout = new CardLayout();
infoPanel.setLayout(cLayout);
table1 = new JTextArea(10,10);
table1.setEditable(false);
scrollTable1 = new JScrollPane(table1);
table2 = new JTextArea(10,10);
table2.setEditable(false);
scrollTable2 = new JScrollPane(table1);
edit = new JLabel("Edit Scores");
search= new JLabel("Search Id");
details=new JLabel("View Details");
infoPanel.add(scrollTable1, "viewTable1");
infoPanel.add(scrollTable2, "viewTable2");
infoPanel.add(edit, "edit");
infoPanel.add(search, "searchId");
infoPanel.add(details, "viewDetails");
mainDartsFrame.add(infoPanel,BorderLayout.CENTER);
}
public void actionPerformed (ActionEvent e) {
JRadioButton eventButton = (JRadioButton) e.getSource();
if(eventButton==viewTableAsc){
cLayout.show(infoPanel,"viewTable1");
}
else if(eventButton==viewTableDesc){
cLayout.show(infoPanel, "viewTable2");
}
else if(eventButton==editScores){
cLayout.show(infoPanel, "edit");
}
else if(eventButton==viewDetails){
cLayout.show(infoPanel, "viewDetails");
}
else{
cLayout.show(infoPanel, "searchId");
}
}
}
And the main class:
public class mainGui {
public static void main(String[] args) {
DartsGUI gui = new DartsGUI();
}
}

You need to call the DartGUI method:
public static void main(String[] args) {
DartsGUI gui = new DartsGUI();
gui.DartGUI();
}

You are using a method instead of constructor.
Here's how your code should be:
public class DartsGUI implements ActionListener {
//Gui components
JFrame mainDartsFrame;
JPanel buttonsPanel,infoPanel;
JRadioButton viewTableAsc,viewTableDesc,editScores,viewDetails,searchById;
CardLayout cLayout;
JTextArea table1,table2;
JScrollPane scrollTable1,scrollTable2;
JLabel edit,details,search;
public DartGUI(){
mainDartsFrame= new JFrame("Darts Competition");
mainDartsFrame.setSize(700, 500);
mainDartsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainDartsFrame.setLayout(new BorderLayout());
mainDartsFrame.setLocationRelativeTo(null);
createButtonsPanel();
createInfoPanel();
mainDartsFrame.setVisible(true);
}
private void createButtonsPanel(){
JPanel buttonsPanel = new JPanel( new GridLayout(5,1) );
viewTableAsc= new JRadioButton("Info Ascending Order");
viewTableAsc.addActionListener(this);
viewTableDesc= new JRadioButton("Info Descending Order");
viewTableDesc.addActionListener(this);
editScores= new JRadioButton("Edit Scores");
editScores.addActionListener(this);
viewDetails= new JRadioButton("View Details");
viewDetails.addActionListener(this);
searchById=new JRadioButton("Search Competitor");
searchById.addActionListener(this);
//Group radio buttons to ensure only one is chosen each time
ButtonGroup radioButtons = new ButtonGroup();
radioButtons.add(searchById);
radioButtons.add(viewTableAsc);
radioButtons.add(viewTableDesc);
radioButtons.add(editScores);
radioButtons.add(viewDetails);
//Push buttons into the buttons Panel
buttonsPanel.add(viewTableAsc);
buttonsPanel.add(viewTableDesc);
buttonsPanel.add(editScores);
buttonsPanel.add(viewDetails);
buttonsPanel.add(searchById);
mainDartsFrame.add(buttonsPanel,BorderLayout.WEST);
}
private void createInfoPanel(){
infoPanel = new JPanel();
cLayout = new CardLayout();
infoPanel.setLayout(cLayout);
table1 = new JTextArea(10,10);
table1.setEditable(false);
scrollTable1 = new JScrollPane(table1);
table2 = new JTextArea(10,10);
table2.setEditable(false);
scrollTable2 = new JScrollPane(table1);
edit = new JLabel("Edit Scores");
search= new JLabel("Search Id");
details=new JLabel("View Details");
infoPanel.add(scrollTable1, "viewTable1");
infoPanel.add(scrollTable2, "viewTable2");
infoPanel.add(edit, "edit");
infoPanel.add(search, "searchId");
infoPanel.add(details, "viewDetails");
mainDartsFrame.add(infoPanel,BorderLayout.CENTER);
}
public void actionPerformed (ActionEvent e){
JRadioButton eventButton = (JRadioButton) e.getSource();
if(eventButton==viewTableAsc){
cLayout.show(infoPanel,"viewTable1");
}
else if(eventButton==viewTableDesc){
cLayout.show(infoPanel, "viewTable2");
}
else if(eventButton==editScores){
cLayout.show(infoPanel, "edit");
}
else if(eventButton==viewDetails){
cLayout.show(infoPanel, "viewDetails");
}
else{
cLayout.show(infoPanel, "searchId");
}
}
}

Related

How can I transfer data between one jframe to another jframe?

I'm new to java and for some reason I don't know any other way to transfer the data from another frame after pressing submit. For example, it will show the output frame the label and textfield that the user wrote in the first frame like this "Name: "user's name". If you do know please post the code I should put, thank you!
package eventdriven;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventDriven extends JFrame {
JPanel items = new JPanel();
JLabel fName = new JLabel("First Name: ");
JLabel lName = new JLabel("Last Name: ");
JLabel mName = new JLabel("Middle Name: ");
JLabel mNum = new JLabel("Mobile Number: ");
JLabel eAdd = new JLabel("Email Address: ");
JTextField fname = new JTextField(15);
JTextField lname = new JTextField(15);
JTextField mname = new JTextField(15);
JTextField mnum = new JTextField(15);
JTextField eadd = new JTextField(15);
JButton submit = new JButton("Submit");
JButton clear = new JButton("Clear All");
JButton okay = new JButton("Okay");
JTextArea infos;
JFrame output;
public EventDriven()
{
this.setTitle("INPUT");
this.setResizable(false);
this.setSize(230, 300);
this.setLocation(300, 300);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(fName);
this.add(fname);
this.add(lName);
this.add(lname);
this.add(mName);
this.add(mname);
this.add(mNum);
this.add(mnum);
this.add(eAdd);
this.add(eadd);
submit.addActionListener(new btnSubmit());
this.add(submit);
clear.addActionListener(new btnClearAll());
this.add(clear);
okay.addActionListener(new btnOkay());
this.add(items);
this.setVisible(true);
}
class btnSubmit implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == submit)
{
submit.setEnabled(false);
output = new JFrame("OUTPUT");
output.show();
output.setSize(300,280);
output.setTitle("OUTPUT");
output.add(okay);
output.setLayout(new FlowLayout(FlowLayout.CENTER));
}
}
}
class btnClearAll implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == clear)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
class btnOkay implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == okay)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
public static void main(String[] args)
{
EventDriven window = new EventDriven();
}
}
It's not clear what problem you are having displaying a value from one field in another frame. But here's an example of doing that (with fields reduced to just one for demonstration):
public class EventDriven extends JFrame {
private final JTextField nameField = new JTextField(15);
private final JButton submit = new JButton("Submit");
private final JButton clear = new JButton("Clear All");
public EventDriven() {
setTitle("Input");
setLayout(new FlowLayout(FlowLayout.CENTER));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Name: "));
add(nameField);
submit.addActionListener(this::showOutput);
add(submit);
clear.addActionListener(this::clearInput);
add(clear);
pack();
}
private void showOutput(ActionEvent ev) {
submit.setEnabled(false);
JDialog output = new JDialog(EventDriven.this, "Output", true);
output.add(new Label("Name: " + nameField.getText()), BorderLayout.CENTER);
JButton okButton = new JButton("OK");
output.add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(bv -> output.setVisible(false));
output.pack();
output.setVisible(true);
}
private void clearInput(ActionEvent ev) {
nameField.setText(null);
submit.setEnabled(true);
}
public static void main(String[] args) {
EventDriven window = new EventDriven();
window.setVisible(true);
}
}
You will also see that I've simplified your action listeners to demonstrate an easier way to respond to user driven event.s

Button not displaying frame connected to it

I am trying to write code for an application I'm making, I have my main frame with 6 buttons on them. When I push one of my buttons, it is meant to bring up a frame that has a tabbed layout set up.
I have the tabbed frame coded correctly and when I set each frame as visible they will appear to screen but they don't appear when the button is pushed.
I have action listeners connected to the buttons and the frames I want to connect with them as well as constructors but for some reason I can't get my code to work correctly.
I have added my driver and my first two forms I'm trying to connect to each other.
public class SimpsonsDriver {
//#param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame simpsonFrame = new JFrame("The Simpson");
JFrame homerFrame = new JFrame ("Homer Simpson");
JFrame margeFrame = new JFrame ("Marge Simpson");
JFrame bartFrame = new JFrame ("Bart Simpson");
JFrame lisaFrame = new JFrame("Lisa Simpson");
JFrame maggieFrame = new JFrame("Maggie Simpson");
SimpsonForm simpsonForm = new SimpsonForm(simpsonFrame, homerFrame, margeFrame, bartFrame,
lisaFrame, maggieFrame);
HomerForm homerForm = new HomerForm(homerFrame, simpsonFrame);
MargeForm margeForm = new MargeForm(margeFrame, simpsonFrame);
BartForm bartForm = new BartForm(bartFrame, simpsonFrame);
LisaForm lisaForm = new LisaForm(lisaFrame, simpsonFrame);
MaggieForm maggieForm = new MaggieForm(maggieFrame, simpsonFrame);
}
}
public class SimpsonForm implements ActionListener{
JFrame simpsonFrame, homerFrame, margeFrame, bartFrame, lisaFrame, maggieFrame;//instance variables
JButton homerBtn, margeBtn, bartBtn, lisaBtn, maggieBtn, closeBtn; //instance variables
public SimpsonForm(JFrame simpsonFrame, JFrame homerFrame, JFrame margeFrame, JFrame bartFrame, JFrame lisaFrame, JFrame maggieFrame) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
this.margeFrame = margeFrame;
this.bartFrame = bartFrame;
this.lisaFrame = lisaFrame;
this.maggieFrame = maggieFrame;
simpsonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createPanel();
}//end constructor method SimpsonForm
private void createPanel(){
homerBtn = new JButton ("Homer");
margeBtn = new JButton ("Marge");
bartBtn = new JButton ("Bart");
lisaBtn = new JButton ("Lisa");
maggieBtn = new JButton ("Maggie");
closeBtn = new JButton ("Close");
FlowLayout flow = new FlowLayout();
JPanel p1 = new JPanel();
p1.setLayout(flow);
JPanel p2 = new JPanel();
p2.setLayout(flow);
ImageIcon img = new ImageIcon(this.getClass().getResource("simpsons.png"));
JLabel imgLabel = new JLabel();
imgLabel.setIcon(img);
imgLabel.setBounds(10, 10, img.getIconWidth(), img.getIconHeight());
p1.add(imgLabel);
p2.add(homerBtn);
homerBtn.addActionListener(this);
p2.add(margeBtn);
margeBtn.addActionListener(this);
p2.add(bartBtn);
bartBtn.addActionListener(this);
p2.add(lisaBtn);
lisaBtn.addActionListener(this);
p2.add(maggieBtn);
maggieBtn.addActionListener(this);
p2.add(closeBtn);
closeBtn.addActionListener(this);
simpsonFrame.setLayout(new BorderLayout());
simpsonFrame.setResizable(false);
simpsonFrame.add(p1, BorderLayout.BEFORE_FIRST_LINE);
simpsonFrame.add(p2, BorderLayout.CENTER);
simpsonFrame.setSize(425, 425);
simpsonFrame.setLocationRelativeTo(null);
simpsonFrame.setVisible(true);
}//end method createPanel
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == homerBtn) {
homerFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == margeBtn) {
margeFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == bartBtn) {
bartFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == lisaBtn) {
lisaFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == maggieBtn) {
maggieFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == closeBtn) {
System.exit(0);
}//end if
}//end event handler
}
public class HomerForm implements ActionListener{
JFrame simpsonFrame, homerFrame;
JButton closeBtn;
public HomerForm(JFrame simpsonFrame, JFrame homerFrame ) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
createPanel();
}
private void createPanel() {
homerFrame = new JFrame("Homer Simpson");
closeBtn = new JButton("Close");
closeBtn.setSize(200, 50);
ImageIcon ogImage = new ImageIcon(this.getClass().getResource("/homer1.png"));
JLabel ogLabel = new JLabel();
ogLabel.setIcon(ogImage);
JPanel p1 = new JPanel();
p1.add(ogLabel);
ImageIcon hwImage = new ImageIcon(this.getClass().getResource("/homer2.png"));
JLabel hwLabel = new JLabel();
hwLabel.setIcon(hwImage);
JPanel p2 = new JPanel();
p2.add(hwLabel);
ImageIcon cImage = new ImageIcon(this.getClass().getResource("/homer3.png"));
JLabel cLabel = new JLabel();
cLabel.setIcon(cImage);
JPanel p3 = new JPanel();
p3.add(cLabel);
JPanel p4 = new JPanel();
JTabbedPane tab = new JTabbedPane();
tab.setBounds(100, 100, 300, 300);
tab.add("Original", p1);
tab.add("HalfWay", p2);
tab.add("Current", p3);
tab.add("Close", p4);
p4.add(closeBtn);
closeBtn.setLayout(new BorderLayout());
closeBtn.addActionListener(this);
homerFrame.add(tab);
homerFrame.setResizable(false);
homerFrame.setSize(500, 500);
homerFrame.setLocationRelativeTo(null);
homerFrame.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == closeBtn) {
homerFrame.setVisible(false);
simpsonFrame.setVisible(true);
}//end if
else
{
System.exit(0);
}
}
}
When i run it, i get this image. simpsonsFrame
this is what happens when i click the homer button i then have to max it to see a blank screen.homerFrame.
when i set the homerFrame to visible, it displays what i what to appear if the button was pushed.it shows homerFrame then it shows the simpsonFrame.homersetVisible true

Gui not loading because the program is stuck in an infinite loop [duplicate]

Im fairly new to Java and im just looking for a little help Im trying to create a program which allows the user to enter as a gui the name and> >location of a department store. It allows this but the program does not wait for the >details to be entered it just initializes the Gui class and simply continues on with the >processing Which is to add the details entered into the Gui into an array list. But the >details have not yet been entered yet so it is creating a null value because it has jumped >ahead.
So how can I make it stop and wait till the values have been entered and then submitted?
Here is the Gui component of the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class guiDepartment extends JFrame
{
private String depName;
private String depLocation;
private static Department newDepartment;
private JTextField departmentDetails1;
private JTextField departmentDetails2;
private JTextField departmentDetails3;
private Employee worksInInTheDepartment;
public guiDepartment()
{
System.out.println("bob the builder ");
JButton submit;
JButton b1;
JFrame frame = new JFrame();
departmentDetails1 = new JTextField(10);
departmentDetails2 = new JTextField(10);
departmentDetails3 = new JTextField(10);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(320, 75));
frame.setTitle("Department Details");
frame.setLayout(new FlowLayout());
frame.add(new JLabel("Please enter department Name: "));
frame.add(departmentDetails1);
ButtonListenerDepName dListener = new ButtonListenerDepName();
System.out.println(depName);
frame.add(new JLabel("Please enter department location: "));
frame.add(departmentDetails2);
ButtonListenerDepName1 dListener1 = new ButtonListenerDepName1();
b1 = new JButton ("Submit");
ButtonListener listener = new ButtonListener();
b1.addActionListener(listener);
b1.addActionListener(dListener);
b1.addActionListener(dListener1);
frame.add(b1);
frame.pack();
frame.setSize(300,300);
frame.setVisible(true);
}
public class ButtonListenerDepName implements ActionListener
{
public void actionPerformed (ActionEvent e )
{
depName = departmentDetails1.getText();
System.out.println("and This is the departments name :"+ depName);
}
}
public class ButtonListenerDepName1 implements ActionListener
{
public void actionPerformed (ActionEvent e )
{
depLocation = departmentDetails2.getText();
System.out.println("and This is the departments location :"+ depLocation);
}
}
public class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e )
{
//create a new department and then adds it to thee system
newDepartment = new Department(depName, depLocation);
}
}
public static Department getDepartment()
{
return newDepartment;
}
}
>>and this is the Main class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class MainWelcomeGui1
{
JFrame frame = new JFrame();
JButton b1 ;
JButton b2 ;
JButton b3 ;
JButton b4 ;
JButton b5 ;
JButton b6 ;
JButton b7 ;
JButton b8 ;
JButton b9 ;
JButton b10 ;
JButton b11 ;
JButton b12 ;
private String fName;
private String sName;
private String gender;
private String pLevel;
private String empIDnumber;
private int dPayLevel;
private static ArrayList<Employee> allEmployees = new ArrayList<Employee>();
private static ArrayList<Department> allDepartments = new ArrayList<Department>();
public MainWelcomeGui1()
{
frame.setTitle("Human Resources allocation screen");
JLabel hdr = new JLabel ("Welcome to the Human Resources employee control system");
b1 = new JButton ("Add a new department");
ButtonListener listener = new ButtonListener();
b1.addActionListener(listener);
// addDepartmentToSystem();
b2 = new JButton ("Add a new employee to the system");
ButtonListener listener1 = new ButtonListener();
b2.addActionListener(listener1);
b3 = new JButton ("Alter a employees details");
ButtonListener listener2 = new ButtonListener();
b3.addActionListener(listener2);
b4 = new JButton ("Add a employee to a department of my choice");
ButtonListener listener3 = new ButtonListener();
b4.addActionListener(listener3);
b5 = new JButton ("Assign a employee to a department");
b6 = new JButton ("Designate a employee as department head");
b7 = new JButton ("Delete a department");
b8 = new JButton ("To delete an employee from the system");
b9 = new JButton ("To see a list of all employees assigned to a particular department");
b10 = new JButton ("To see the amounts needed to be paid fortnightly");
b11 = new JButton ("To chane an employees pay level");
b12 = new JButton ("To change an employees name");
frame.setLayout (new GridLayout (6, 6));
frame.setBackground (Color.green);
frame.add(hdr,BorderLayout.NORTH);
frame.add (b1);
frame.add (b2);
frame.add (b3);
frame.add (b4);
frame.add (b5);
frame.add (b6);
frame.add (b7);
frame.add (b8);
frame.add (b9);
frame.add (b10);
frame.add (b11);
frame.add (b12);
frame.setSize(400, 100);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
new MainWelcomeGui1();
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e )
{
if (e.getSource() == b1)
{
guiDepartment guiDepartment = new guiDepartment();
System.out.println("i should really come after bob the builder");
addDepartmentToSystem();
}
else if (e.getSource() == b2)
{
guiEmployee1 theGuiEmployee = new guiEmployee1();
}
else if (e.getSource() == b3)
{
System.out.println("hello1 button 2");
}
else if (e.getSource() == b4)
{
System.out.println("hello button 3");
}
else if (e.getSource() == b5)
{
guiEmployee1 theGuiEmployee = new guiEmployee1();
}
else if (e.getSource() == b6)
{
System.out.println("hello1 button 2");
}
else if (e.getSource() == b7)
{
System.out.println("hello button 3");
}
}
}
public void addDepartmentToSystem()
{
Department departmentToAdd = new Department("berel","sam") ;
System.out.println("to two");
System.out.println(departmentToAdd);
departmentToAdd = guiDepartment.getDepartment();
System.out.println("got to three");
allDepartments.add(departmentToAdd);
System.out.println("to four+");
System.out.println(allDepartments);
}
}
You shouldn't have a JFrame launching other JFrames, especially if you want the child windows to behave as a modal dialogs -- a dialog that halts the code in the launching window until it has been fully dealt with. When this is the case, make the dialog windows dialogs by using modal JDialogs in place of JFrames for the dialog windows.
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainWelcomeGui2 {
public static void main(String[] args) {
final JFrame frame = new JFrame("Main GUI");
JButton addDeptButtonLaunchJFrame = new JButton(
"Add a New Department, Launch JFrame");
JButton addDeptButtonLaunchJDialog = new JButton(
"Add a New Department, Launch JDialog");
addDeptButtonLaunchJDialog.addActionListener(new LaunchJDialogListener(
frame));
addDeptButtonLaunchJFrame.addActionListener(new LaunchJFrameListener());
JPanel panel = new JPanel();
panel.add(addDeptButtonLaunchJDialog);
panel.add(addDeptButtonLaunchJFrame);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class LaunchJDialogListener implements ActionListener {
JDialog dialog;
public LaunchJDialogListener(JFrame parentFrame) {
JButton doneButton = new JButton(new AbstractAction("Done") {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.add(doneButton);
dialog = new JDialog(parentFrame, "Dialog", true);
dialog.add(panel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("called before setting dialog visible");
dialog.setVisible(true);
System.out
.println("called after setting dialog visible. Note that this line doesn't show until the dialog disappears");
}
}
class LaunchJFrameListener implements ActionListener {
JFrame frame;
public LaunchJFrameListener() {
JButton doneButton = new JButton(new AbstractAction("Done") {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.add(doneButton);
frame = new JFrame("JFrame");
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("called before setting frame visible");
frame.setVisible(true);
System.out
.println("called after setting frame visible. Note that this line shows up immediately.");
}
}

JPanel on CardLayout Swing Java

I am new to Java and I am making a navigation through CardLayout in Swing. Basically I have two buttons on a JFrame and when I click on one button it should go to card 1 where I have kept two buttons on JPanel, card1 and when I click on another button it should go to card 2 where I have kept a JTextField on panel card2. But it is not happening.
Can anyone fix it?
My code is as below.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CardLayoutTest extends JFrame implements ActionListener {
JFrame f;
JButton b;
JButton c;
JPanel panel;
JPanel cards;
JPanel card1;
JPanel card2;
CardLayout card;
Container pane;
final String card1Text = "One";
final String card2Text = "Two";
CardLayoutTest() {
}
public void passBtn() {
f=new JFrame("Card Layout Test");
card1 = new JPanel();
card1.add(new JButton("Button 1 - Card 1"));
card1.add(new JButton("Button 2 - Card 1"));
card1.setBackground(new Color(255,0,0));
card2 = new JPanel();
card2.add(new JTextField("TextField on Card 2", 20));
card2.setBackground(new Color(0,255,0));
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, card1Text);
cards.add(card2, card2Text);
b = new JButton("Page 1");
b.setBounds(50,50,70,30);
b.setBackground(Color.red);
c = new JButton("Page 2");
c.setBounds(50,80,70,30);
c.setBackground(Color.blue);
pane = f.getContentPane();
pane.add(cards, BorderLayout.CENTER);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
card.show(card1, card1Text);
}
});
c.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
card.show(card2, card2Text);
}
});
f.add(b); f.add(c); f.add(panel); f.add(cards);
}
public static void main(String[] args) {
new CardLayoutTest();
}
}
Try:
card = new CardLayout();
cards = new JPanel(card);
instead of cards = new JPanel(new CardLayout());
UPDATE
public class CardLayoutTest extends JFrame {
JButton b;
JButton c;
JPanel cards;
JPanel card1;
JPanel card2;
CardLayout card;
final String card1Text = "One";
final String card2Text = "Two";
CardLayoutTest() {
super();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
passBtn();
}
public void passBtn() {
card1 = new JPanel();
card1.setBackground(new Color(255,0,0));
card2 = new JPanel();
card2.add(new JTextField("TextField on Card 2", 20));
card2.setBackground(new Color(0, 255, 0));
//Create the panel that contains the "cards".
card = new CardLayout();
cards = new JPanel(card);
cards.add(card1, card1Text);
cards.add(card2, card2Text);
b = new JButton("Page 1");
b.setBounds(50, 50, 70, 30);
b.setBackground(Color.red);
card1.add(b);
c = new JButton("Page 2");
c.setBounds(50, 80, 70, 30);
c.setBackground(Color.blue);
card1.add(c);
add(cards);
card.show(cards, card1Text);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
card.show(cards, card1Text);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
card.show(cards, card2Text);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
public static void main(String[] args) {
CardLayoutTest cardLayoutTest = new CardLayoutTest();
cardLayoutTest.setVisible(true);
}
}

Eventhandling and how to use itemListener for multiple items

So I have 2 questions, the following classes regarding the questions I will ask are supplemented below:
1) If I have multiple JCheckBoxes, how can I use an itemListener to know when a specific JCheckBox is selected.
(In the example below, I have 3 JCheckBoxes named petrol, Electric & diesel, if petrol is chosen how can I be aware of this, I want to do something like, if petrol is selected then remove some items from the JComboBox)
2) How can I make the progress bar increase or decrease when a JButton is clicked. In the code below I have a JProgressBar, when the user clicks drive I want the JProgressBar to decrease and when they select refuel I want the JProgressBar to increase. I sort of want the JProgressBar to represent the fuel Level of the car. How would I go about doing this?
Class 1
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class CarViewer extends JFrame{
//row1
JPanel row1 = new JPanel();
JButton drv = new JButton("Drive");
JButton park = new JButton("Park");
JButton refuel = new JButton("Refuel");
//row2
JPanel row2 = new JPanel();
JLabel carTypeTag = new JLabel("Car Model:", JLabel.RIGHT);
JComboBox<String> options = new JComboBox<String>();
JCheckBox petrol = new JCheckBox("Petrol");
JCheckBox Electric = new JCheckBox("Electric");
JCheckBox diesel = new JCheckBox("Diesel");
JLabel fuelTypeTag = new JLabel("Fuel Type: ", JLabel.RIGHT);
ButtonGroup groupFuelType = new ButtonGroup();
//row3
JPanel row3 = new JPanel();
JLabel costTag = new JLabel("Cost:", JLabel.RIGHT);
JTextField costField = new JTextField(10);
JLabel engTag = new JLabel("Engine Size: ", JLabel.RIGHT);
JTextField engField = new JTextField(5);
JLabel mileageTag = new JLabel("Mileage: ", JLabel.RIGHT);
JTextField mField = new JTextField(10);
JLabel tankSizeTag = new JLabel("Tank size: ", JLabel.RIGHT);
JTextField tSField = new JTextField(5);
//row4
JPanel row4 = new JPanel();
JProgressBar petTank = new JProgressBar();
//row5
JPanel row5 = new JPanel();
JButton reset = new JButton("Reset");
public CarViewer(){
super("Analyse A Car - AAC");
setSize(400,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layoutMaster = new GridLayout(6, 1, 10, 20);
setLayout(layoutMaster);
////Initial Errands
groupFuelType.add(petrol);
groupFuelType.add(diesel);
groupFuelType.add(Electric);
Dimension buttonDimension = new Dimension(80,30);
Dimension resetButtonX = new Dimension(150,100);
drv.setPreferredSize(buttonDimension);
park.setPreferredSize(buttonDimension);
refuel.setPreferredSize(buttonDimension);
petTank.setMinimum(0);
petTank.setMaximum(100);
///Adding Car Models to Dropdown (JComboBox)
options.addItem("Mercedes C63 AMG");
options.addItem("BMW i7");
options.addItem("Jaguar XFR");
options.addItem("Nissan Skyline R35 GTR 4");
EmptyBorder empty0 = new EmptyBorder(60, 0, 440, 0); //empty Border;
EmptyBorder empty2 = new EmptyBorder(50,40,0,120); //empty Border row 3;
EmptyBorder empty4 = new EmptyBorder(80,0,0,0);
//Errands Complete
CarEvent handler = new CarEvent();
//Adding Listeners
drv.addActionListener(handler);
park.addActionListener(handler);
refuel.addActionListener(handler);
reset.addActionListener(handler);
options.addItemListener(handler);
petrol.addItemListener(handler);
Electric.addItemListener(handler);
diesel.addItemListener(handler);
//Listeners Added.
FlowLayout layout0 = new FlowLayout();
row1.setLayout(layout0);
row1.add(drv);
row1.add(park);
row1.add(refuel);
row1.setBorder(empty0);
add(row1);
GridLayout layout1 = new GridLayout(1, 3, 40, 50);
row2.setLayout(layout1);
row2.add(carTypeTag);
row2.add(options);
row2.add(fuelTypeTag);
row2.add(petrol);
row2.add(diesel);
row2.add(Electric);
add(row2);
GridLayout layout2 = new GridLayout(1, 4, 20, 0);
row3.setLayout(layout2);
costField.setEditable(false);
engField.setEditable(false);
tSField.setEditable(false);
mField.setEditable(false);
row3.add(costTag);
row3.add(costField);
row3.add(engTag);
row3.add(engField);
row3.add(tankSizeTag);
row3.add(tSField);
row3.add(mileageTag);
row3.add(mField);
row3.setBorder(empty2);
add(row3);
FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER);
row4.setLayout(layout3);
row4.setBorder(empty4);
row4.add(petTank);
add(row4);
FlowLayout layout4 = new FlowLayout(FlowLayout.CENTER);
row5.setLayout(layout4);
reset.setPreferredSize(resetButtonX);
row5.add(reset);
add(row5);
setVisible(true);
}
public static void main(String[] args){
CarViewer gui = new CarViewer();
}
}
Event handling class (2):
import java.awt.event.*;
public class CarEvent implements ActionListener, ItemListener {
public void actionPerformed(ActionEvent event){
String cmd = event.getActionCommand();
if(cmd.equals("Drive"));{
}
else if(cmd.equals("Park")){
}
else if(cmd.equals("Refuel")){
}
else if(cmd.equals("Reset")){
}
}
public void itemStateChanged(ItemEvent event){
Object identifier = event.getItem();
String item = identifier.toString();
if())
}
}
For the check box question the below code may help you.
Use the CarEvent class as a inner class to CarViewer.
In the CarViewer add the event to each control
public class CarViewer extends JFrame {
petrol.addItemListener (new CarEvent());
Electric.addItemListener (new CarEvent());
diesel.addItemListener (new CarEvent());
class CarEvent implements ActionListener, ItemListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.toString());
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getItem().equals(petrol)) {
System.out.println("Petrol");
}
else if (e.getItem().equals(Electric)) {
System.out.println("Electric");
}
else if (e.getItem().equals(diesel)) {
System.out.println("Diesel");
}
}
} //CarEvent class
} //CarViewer class
If you want to use the CarEvent as a separate class then you need to pass the CarViewer class instance to this CarEvent class and access the check boxes (when the check boxes as public)
public class CarViewer extends JFrame {
petrol.addItemListener (new CarEvent(this));
//and so on ,,,,
}//CarViewer class
class CarEvent implements ActionListener, ItemListener {
CarViewer cv:
public CarEvent(CarViewer _object){
cv=_object;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.toString());
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getItem().equals(cv.petrol)) {
System.out.println("Petrol");
}
else if (e.getItem().equals(cv.Electric)) {
System.out.println("Electric");
}
else if (e.getItem().equals(cv.diesel)) {
System.out.println("Diesel");
}
}
}//CarEvent class

Categories

Resources