More than 1 object in a single JFrame - java

I'm hoping someone can push me in the right direction with this. I have 3 separate classes, Calculator, Calculator2, and a Calculator3. In principal they are all the same, except for a few changes to some of the buttons, so I'll just paste the code for Calculator. I was wondering how can I get them so all appear in a single JFrame next to each other in a main? I attached my most recent attempt of the main as well.
Here is Calculator:
public class Calculator implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JButton subtractButton;
private JButton divideButton;
private JButton addButton;
private JButton timesButton;
private JPanel xpanel;
public Calculator() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("Result:"));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
/***********************************************************************
***********************************************************************
**********************************************************************/
JPanel southPanel = new JPanel(); //New panel for the artimatic buttons
southPanel.setBorder(BorderFactory.createEtchedBorder());
timesButton = new JButton("Multiplication");
southPanel.add(timesButton);
timesButton.addActionListener(this);
subtractButton = new JButton("Subtract");
southPanel.add(subtractButton);
subtractButton.addActionListener(this);
divideButton = new JButton("Division");
southPanel.add(divideButton);
divideButton.addActionListener(this);
addButton = new JButton("Addition");
southPanel.add(addButton);
addButton.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Font thisFont = result.getFont(); //Get current font
result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD)); //Make the result bold
result.setForeground(Color.red); //Male the result answer red in color
result.setBackground(Color.yellow); //Make result background yellow
result.setOpaque(true);
frame.pack();
frame.setVisible(true);
}
/**
* clear()
* Resets the x and y field to 0 after invalid integers were input
*/
public void clear() {
xfield.setText("0");
yfield.setText("0");
}
#Override
public void actionPerformed(ActionEvent event) {
String xText = xfield.getText(); //Get the JLabel fiels and set them to strings
String yText = yfield.getText();
int xVal;
int yVal;
try {
xVal = Integer.parseInt(xText); //Set global var xVal to incoming string
yVal = Integer.parseInt(yText); //Set global var yVal to incoming string
}
catch (NumberFormatException e) { //xVal or yVal werent valid integers, print message and don't continue
result.setText("ERROR");
clear();
return ;
}
if(event.getSource().equals(timesButton)) { //Button pressed was multiply
result.setText(Integer.toString(xVal*yVal));
}
else if(event.getSource().equals(divideButton)) { //Button pressed was division
if(yVal == 0) { //Is the yVal (bottom number) 0?
result.setForeground(Color.red); //Yes it is, print message
result.setText("CAN'T DIVIDE BY ZERO!");
clear();
}
else
result.setText(Integer.toString(xVal/yVal)); //No it's not, do the math
}
else if(event.getSource().equals(subtractButton)) { //Button pressed was subtraction
result.setText(Integer.toString(xVal-yVal));
}
else if(event.getSource().equals(addButton)) { //Button pressed was addition
result.setText(Integer.toString(xVal+yVal));
}
}
}
And here is my current main:
public class DemoCalculator {
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Calculators");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Calculator calc = new Calculator();
Calculator2 calc2 = new Calculator2();
JPanel calcPanel = new JPanel(new BorderLayout());
JPanel calcPanel2 = new JPanel(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//calcPanel.add(calc, BorderLayout.CENTER);
//calcPanel2.add(calc2, BorderLayout.CENTER);
mainPanel.add(calcPanel);
mainPanel.add(calcPanel2);
calcPanel.add(mainPanel);
mainFrame.getContentPane().add(calcPanel);
mainFrame.getContentPane().add(calcPanel2);
mainFrame.pack();
mainFrame.setVisible(true);
}
}

You should just create a single JFrame and put your Calculator classes each into a single JPanel.Don't create a new JFrame for each class.
public class Calculator{
JPanel panel;
public Calculator(){
panel = new JPanel();
/*
* Add labels and buttons etc.
*/
panel.add(buttons);
panel.add(labels);
}
//Method to return the JPanel
public JPanel getPanel(){
return panel;
}
}
Then add the panels to your JFrame in your testers class using whatever layout best suits your needs.
public class DemoCalculator {
public static void main(String[] args) {
JPanel cal1,cal2;
JFrame frame = new JFrame("Calculators");
frame.add(cal1 = new Calculator().getPanel(),new BorderLayout().EAST);
frame.add(cal2 = new Calculator2().getPanel(),new BorderLayout().WEST);
frame.setSize(1000,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
}

Related

Using JComobBox, find results of 2 numbers and output to the results (Java)

I am to make a simple calculator but I am having issues with this:
When the button is pressed it should do the following:
Get the text from the two JTextFields and convert them to Doubles. Use Double.parseDouble(String input) to turn a String into a Double. (Not sure where to put this?)
Get the text from the JComboBox. Use the getSelectedItem() method to get the currently selected string. (Not sure if I did this correctly)
Calculate the result based on the string from the JComboBox
This determines if you will use the + operator, - operator, * operator or / operator. (do not know how to do this)
Set the result to the JLabel
Use the .setText() method to construct a String
These are my 4 problems.
class MyFrame extends JFrame {
public JTextField firstNumber;
public JTextField secondNumber;
public JButton calc;
public JLabel result;
public JComboBox combo;
public MyFrame() {
super();
init();
}
private void init() {
JButton calc = new JButton("Calculate");
calc.addActionListener(new MyButtonListener(this));
firstNumber = new JTextField();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(calc);
this.add(firstNumber);
this.add(secondNumber);
this.pack();
this.setVisible(true);
}
}
class MyButtonListener implements ActionListener {
MyFrame fr;
public MyButtonListener(MyFrame frame)
{
fr = frame;
fr.firstNumber.getText();
fr.secondNumber.getText();
fr.combo.getSelectedItem();
}
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton) e.getSource();
}
}
private static void constructGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JTextField firstNumber = new JTextField();
JTextField secondNumber = new JTextField();
JButton calc = new JButton("Calculate");
JLabel result = new JLabel();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Simple Calculator");
String[] arth = { "Add", "Subtract", "Multiple",
"Divide" };
JComboBox combo = new JComboBox(arth);
combo.setSelectedIndex(0);
frame.setLayout(new GridLayout(5, 2));
frame.add(new JLabel("First Number:"));
frame.add(firstNumber);
frame.add(new JLabel("Second Number:"));
frame.add(secondNumber);
frame.add(combo);
frame.add(calc);
frame.add(new JLabel("Result:"));
frame.pack();
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
constructGUI();
}
});
}
}
Your MyFrame is not connected with the rest of the code invoked in main.
Added listener to your result field (also included in JFrame because it was not used) - code from lambda can be extracted for better visibility
Added only "ADD" rest will be similar
private static void constructGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JTextField firstNumber = new JTextField();
JTextField secondNumber = new JTextField();
JButton calc = new JButton("Calculate");
JLabel result = new JLabel("Result:");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Simple Calculator");
String[] arth = {"Add", "Subtract", "Multiple", "Divide"};
JComboBox combo = new JComboBox(arth);
combo.setSelectedIndex(0);
frame.setLayout(new GridLayout(5, 2));
frame.add(new JLabel("First Number:"));
frame.add(firstNumber);
frame.add(new JLabel("Second Number:"));
frame.add(secondNumber);
frame.add(combo);
frame.add(calc);
frame.add(result);
frame.pack();
frame.setSize(200, 200);
frame.setVisible(true);
calc.addActionListener(
e -> {
var first = Double.parseDouble(firstNumber.getText());
var secound = Double.parseDouble(secondNumber.getText());
double res = 0;
switch (Objects.requireNonNull(combo.getSelectedItem()).toString()) {
case "Add":
res = first + secound;
break;
}
result.setText(String.valueOf(res));
});
}
Simplified main:
public static void main(String[] args) {
SwingUtilities.invokeLater(Main2::constructGUI);
}

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

Java Swing: Can't show several instances of my JPanel

I'm making a GUI and having trouble with a JPanel.
First of all here is my JPanel:
public class ExperimentPanel extends JPanel{
private static File file1,file2=null;
private static DefaultListModel model = new DefaultListModel();
private static JList list = new JList(model);
private static JPanel mainpanel = new JPanel();
private static JPanel leftpanel = new JPanel();
private static JPanel rightpanel = new JPanel();
private static JPanel twoFiles = new SelectTwoFiles();
private static JPanel folderOrFile = new SelectFolderOrFile();
private static JPanel foldersOrFiles = new SelectTwoFoldersOrFiles();
public ExperimentPanel(int selectID){
this.setBorder(new EmptyBorder(10, 10, 10, 10));
if(selectID==Constants.SelectTwoFiles){
this.add(twoFiles, BorderLayout.NORTH);
}
else if(selectID==Constants.SelectFolderOrFile){
this.add(folderOrFile, BorderLayout.NORTH);
}
else if(selectID==Constants.SelectTwoFoldersOrFiles){
this.add(foldersOrFiles,BorderLayout.NORTH);
}
JButton remove =new JButton("Remove Method");
JButton add = new JButton("Add Method");
JButton save = new JButton("Save list");
JButton load = new JButton("Load list");
leftpanel.add(new JScrollPane(list));
Box listOptions = Box.createVerticalBox();
listOptions.add(add);
listOptions.add(remove);
listOptions.add(save);
listOptions.add(load);
rightpanel.add(listOptions);
Box mainBox = Box.createHorizontalBox();
mainBox.add(leftpanel);
mainBox.add(rightpanel);
//mainBox.add(leftleft);
this.add(mainBox, BorderLayout.CENTER);
//start jobs
JButton start = new JButton("Launch experiment");
this.add(start,BorderLayout.PAGE_END);
start.addActionListener(launch);
add.addActionListener(adding);
remove.addActionListener(delete);
}
public static ActionListener launch = new ActionListener(){
public void actionPerformed(ActionEvent event){
//check the files
if((file1==null)||(file2==null)){
JOptionPane.showMessageDialog(null,
"A graph file is missing",
"Wrong files",
JOptionPane.ERROR_MESSAGE);
}
//checks the list
}
};
public static ActionListener delete = new ActionListener() {
public void actionPerformed(ActionEvent event) {
ListSelectionModel selmodel = list.getSelectionModel();
int index = selmodel.getMinSelectionIndex();
if (index >= 0)
model.remove(index);
}
};
public static ActionListener adding = new ActionListener(){
public void actionPerformed(ActionEvent event){
JComboBox combo = new JComboBox();
final JPanel cards = new JPanel(new CardLayout());
JPanel form = new JPanel();
JPanel methode1 = new JPanel();
methode1.add(new JLabel("meth1"));
methode1.setBackground(Color.BLUE);
methode1.setName("meth1");
JPanel methode2 = new JPanel();
methode2.add(new JLabel("meth2"));
methode2.setBackground(Color.GREEN);
methode1.setName("meth2");
combo.addItem("meth1");
combo.addItem("meth2");
cards.add(methode1,"meth1");
cards.add(methode2,"meth2");
JPanel control = new JPanel();
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox jcb = (JComboBox) e.getSource();
CardLayout cl = (CardLayout) cards.getLayout();
cl.show(cards, jcb.getSelectedItem().toString());
}
});
control.add(combo);
form.add(cards, BorderLayout.CENTER);
form.add(control, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null,form,"Select a method",JOptionPane.PLAIN_MESSAGE);
}
};
}
The problem is that if i create several instances of that panel they won't show like intended.
I tried creating 2 simple JFrames in my main with a new ExperimentPanel for each so the problem is not from the caller.
It works well with one JFrame calling one experiementPanel.
here is the display for one and 2 calls:
http://imgur.com/a/4DHJn
And how i call them:
JFrame test = new JFrame();
test.add(new ExperimentPanel(3));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
test.setLocation(dim.width/3 - test.getWidth()/3, dim.height/3 - test.getHeight()/3);
test.setSize(550,300);
test.setVisible(true);
JFrame test2 = new JFrame();
test2.add(new ExperimentPanel(3));
test2.setLocation(dim.width/3 - test.getWidth()/3, dim.height/3 - test.getHeight()/3);
test2.setSize(550,300);
test2.setVisible(true);
You create a Panel class ExperimentPanel which itself consists of several components which are stored in class fields of ExperimentPanel.
Since you declare these class fields as static there is only one instance of them. When you instantiate several ExperimentPanel objects they all want to share these fields, which leads to the effects you have seen.
Therefore remove the static modifier from these fields:
public class ExperimentPanel extends JPanel{
private File file1,file2=null;
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
private JPanel mainpanel = new JPanel();
private JPanel leftpanel = new JPanel();
...

Java grid layout GUI - how to enter new pane on event?

How can I set a button to link to a completely different grid pane? If I click the JButton "More options" for example, I want it to link me to a new page with more JButton options. Right now, everything is static.
The program right now just calculates the area of a rectangle given an length and width when you press "Calculate." The grid layout is 4 x 2, denoted by JLabel, JTextField, and JButton listed below.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel lengthL, widthL, areaL;
private JTextField lengthTF, widthTF, areaTF;
private JButton calculateB, exitB;
//Button handlers:
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public RectangleProgram()
{
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
//SPecify handlers for each button and add (register) ActionListeners to each button.
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
setTitle("Sample Title: Area of a Rectangle");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
//Add things to the pane in the order you want them to appear (left to right, top to bottom)
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area;
length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields.
width = Double.parseDouble(widthTF.getText());
area = length * width;
areaTF.setText("" + area);
}
}
public class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
RectangleProgram rectObj = new RectangleProgram();
}
}
You can use CardLayout. It allows the two or more components share the same display space.
Here is a simple example
public class RectangleProgram {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Area of a Rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField lengthField = new JTextField(10);
JTextField widthField = new JTextField(10);
JTextField areaField = new JTextField(10);
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
final JPanel content = new JPanel(new CardLayout());
JButton optionsButton = new JButton("More Options");
optionsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) content.getLayout();
cardLayout.next(content);
}
});
JPanel panel = new JPanel(new GridLayout(0, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
};
panel.add(new JLabel("Enter the length: ", JLabel.RIGHT));
panel.add(lengthField);
panel.add(new JLabel("Enter the width: ", JLabel.RIGHT));
panel.add(widthField);
panel.add(new JLabel("Area: ", JLabel.RIGHT));
panel.add(areaField);
panel.add(calculateButton);
panel.add(exitButton);
JPanel optionsPanel = new JPanel();
optionsPanel.add(new JLabel("Options", JLabel.CENTER));
content.add(panel, "Card1");
content.add(optionsPanel, "Card2");
frame.add(content);
frame.add(optionsButton, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
});
}
}
Read How to Use CardLayout

Can't seem to get .remove to work

So for a class that I am currently taking I need to create an ATM System. So, I decided to have 2 panels. A main panel, where all of the processes take place, and an options panel, where the options are listed for the user. The problem, as mentioned above, is that I can't seem to get the main panel to be removed so I can actually replace it with the panel for, say the create account screen. In fact, all that happens is that the terminal window shows. Completely blank. As far as I have checked, the buttons event is firing and it even gets past the remove function.
In any event, I can't seem to figure out what the problem is, perhaps it is because the button being pressed is also being removed with the panel. Here's the related code.
public class AccountSystem extends JFrame implements ActionListener
{
public static Account currentuser = new Account(); //This is so that the methods know which account is currently logged in so they can perform operations on it.
public static int count=0;
public static Account acc[] = new Account[1000];
public static String parts[] = new String[3];
private JButton login, logout, createacc, deposit1, deposit2, withdraw1, withdraw2, transfer1, transfer2, nevermind;
private JPanel options, mainarea, titlecard;
private JTextField username, password, transfer, depositarea, withdrawarea, retypearea;
private JLabel userprompt, depositprompt, withdrawpromt, balancedisp, passwordprompt, mainmessage, title;
private String newuser, newpass, newpassconfirm;
BorderLayout borderlayout;
GridLayout gridlayout;
public AccountSystem()
{
borderlayout = new BorderLayout();
borderlayout.setHgap(5);
borderlayout.setVgap(5);
//Establishing our buttons here.
JButton login = new JButton("Login");
login.addActionListener(this);
JButton createacc = new JButton("New Account");
createacc.addActionListener(this);
//Establishing our panels here.
JPanel options = new JPanel();
JPanel mainarea = new JPanel();
JPanel titlecard = new JPanel();
//Establishing our JLabel here.
JLabel userprompt = new JLabel("Username: ");
JLabel passwordprompt = new JLabel("Password: ");
JLabel title = new JLabel(" LOGIN ");
//Establishing our textfields here.
JTextField username = new JTextField(20);
JTextField password = new JTextField(20);
JTextField transfer = new JTextField(20);
JTextField withdrawarea = new JTextField(20);
//Building the GUI here.
titlecard.setSize(500,50);
titlecard.setLocation (0,0);
mainarea.setSize(300,450);
mainarea.setLocation(0,50);
options.setSize(150,450);
options.setLocation(300,50);
titlecard.add(title);
mainarea.add(userprompt);
mainarea.add(username);
mainarea.add(passwordprompt);
mainarea.add(password);
mainarea.add(login);
mainarea.add(createacc);
getContentPane().setLayout(null);
getContentPane().add(titlecard);
getContentPane().add(mainarea);
getContentPane().add(options);
}
}
public void actionPerformed (ActionEvent e)
{
if ((e.getActionCommand()).equals("Login"))
{
login();
}
else if ((e.getActionCommand()).equals("New Account"))
{
accountmaker();
}
else if ((e.getActionCommand()).equals("Deposit Funds"))
{
deposit();
}
else if ((e.getActionCommand()).equals("Withdraw Funds"))
{
withdraw();
}
else if ((e.getActionCommand()).equals("Withdraw"))
{
withdrawprocedure();
}
else if ((e.getActionCommand()).equals("Create Account"))
{
accountprocedure();
}
}
public void accountmaker() //This is the screen where the user creates the account they want to. Of course, something needed to be done to differentiate this screen and the login screen.
{
currentuser = null; //This is so that the program doesn't get somehow confused when dealing with multiple uses of the program.
getContentPane().remove(mainarea);
title.setText("Create New Account");
mainarea = new JPanel();
JLabel userprompt = new JLabel ("Username: ");
JLabel passwordprompt = new JLabel("Password: ");
JLabel retype = new JLabel ("Retype: "); //This is what makes it different from the login screen
createacc = new JButton ("Create Account");
createacc.addActionListener(this);
JButton nevermind = new JButton("Cancel");
nevermind.addActionListener(this);
JTextField username = new JTextField(20);
JTextField password = new JTextField(20);
retypearea = new JTextField(20);
mainarea.setSize(300,500);
mainarea.setLocation(0,0);
mainarea.add(userprompt);
mainarea.add(username);
mainarea.add(passwordprompt);
mainarea.add(password);
mainarea.add(retype);
mainarea.add(retypearea);
getContentPane().add(mainarea);
getContentPane().invalidate();
getContentPane().validate();
getContentPane().repaint();
}
And this is the Account class that the program uses.
public class Account
{
private String username;
private String password;
private double balance=0;
public void deposit (double deposit)
{
balance += deposit;
}
public void withdraw (double withdraw)
{
balance -= withdraw;
}
public void setBalance (double newbalance)
{
balance = newbalance;
}
public void setUsername (String newusername)
{
username = newusername;
}
public void setPassword (String newpassword)
{
password = newpassword;
}
public String getUsername ()
{
return username;
}
public double getbalance ()
{
return balance;
}
public String getpassword()
{
return password;
}
}
If I understand correctly.. you basically need to replace the main panel with account panel on certain event!
I have written example code (please modify it according to your project)
In this code.. I have created 4 panels namely
Component Panel: To hold all components
Main Panel: contains the label with text "Main Panel" and its border is painted RED
Account Panel: contains the label with text "Account Panel" and its border is painted GREEN
Option Panel: empty panel with its border is painted BLUE
Two buttons:
Account Button: Which should replace Main Panel with Account Panel
Main Button: Which should replace Account Panel with Main Panel
Using GridBagLayout, all you need to do is to place Main Panel and Account Panel at the same location i.e. gridx = 0 and gridy = 0 for both. At first Main Panel shall be displayed. On event "Account Button" set Main Panel's visibility false and Account Panels' true. For event "Main Button" do the vica versa. GridBagLayout is fantastic dynamic layout which manages the empty spacing by itslef without any distortion.
public class SwingSolution extends JFrame implements ActionListener
{
private JPanel componentPanel = null;
private JPanel mainPanel = null;
private JLabel mainLabel = null;
private JPanel optionPanel = null;
private JPanel accountPanel = null;
private JLabel accountLabel = null;
private JButton replaceToAccountPanel = null;
private JButton replaceToMainPanel = null;
private final static String MAIN_TO_ACCOUNT = "MainToAccount";
private final static String ACCOUNT_TO_MAIN = "AccountToMain";
public JPanel getComponentPanel()
{
if(null == componentPanel)
{
componentPanel = new JPanel();
GridBagLayout gridBagLayout = new GridBagLayout();
componentPanel.setLayout(gridBagLayout);
GridBagConstraints constraint = new GridBagConstraints();
constraint.insets = new Insets(10, 10, 10, 10);
mainPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 0;
mainPanel.setMinimumSize(new Dimension(100, 50));
mainPanel.setPreferredSize(new Dimension(100, 50));
mainPanel.setMaximumSize(new Dimension(100, 50));
mainPanel.setBorder(
BorderFactory.createLineBorder(Color.RED));
mainLabel = new JLabel("Main Panel");
mainPanel.add(mainLabel);
componentPanel.add(mainPanel, constraint);
accountPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 0;
accountPanel.setMinimumSize(new Dimension(100, 50));
accountPanel.setPreferredSize(new Dimension(100, 50));
accountPanel.setMaximumSize(new Dimension(100, 50));
accountPanel.setBorder(
BorderFactory.createLineBorder(Color.GREEN));
accountLabel = new JLabel("Account Panel");
accountPanel.add(accountLabel);
componentPanel.add(accountPanel, constraint);
optionPanel = new JPanel();
constraint.gridx = 0;
constraint.gridy = 1;
optionPanel.setMinimumSize(new Dimension(100, 50));
optionPanel.setPreferredSize(new Dimension(100, 50));
optionPanel.setMaximumSize(new Dimension(100, 50));
optionPanel.setBorder(
BorderFactory.createLineBorder(Color.BLUE));
componentPanel.add(optionPanel, constraint);
replaceToAccountPanel = new JButton("Account Button");
replaceToAccountPanel.setName(MAIN_TO_ACCOUNT);
constraint.gridx = 0;
constraint.gridy = 2;
replaceToAccountPanel.setSize(new Dimension(800, 30));
replaceToAccountPanel.addActionListener(this);
componentPanel.add(replaceToAccountPanel, constraint);
replaceToMainPanel = new JButton("Main Button");
replaceToMainPanel.setName(ACCOUNT_TO_MAIN);
constraint.gridx = 1;
constraint.gridy = 2;
replaceToMainPanel.setMinimumSize(new Dimension(800, 30));
replaceToMainPanel.addActionListener(this);
componentPanel.add(replaceToMainPanel, constraint);
}
return componentPanel;
}
public void actionPerformed (ActionEvent evt)
{
JButton buttonClicked = (JButton) evt.getSource();
if(buttonClicked != null)
{
if(buttonClicked.getName().equals(MAIN_TO_ACCOUNT))
{
mainPanel.setVisible(false);
accountPanel.setVisible(true);
}
else if(buttonClicked.getName().equals(ACCOUNT_TO_MAIN))
{
mainPanel.setVisible(true);
accountPanel.setVisible(false);
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
SwingSolution main = new SwingSolution();
frame.setTitle("Simple example");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setContentPane(main.getComponentPanel());
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Categories

Resources