Adding onto JPanel - java

I was wondering if it was possible to add dropdown menus to a main JPanel from a different class instead of calling it from that class itself. Mainly because a friend and I are working on a personal project trying to create different programs in different tabs.
Here's our main GUI:
public class GUI extends JFrame {
public GUI() {
setTitle("Andy and Jack's favorite programs");
JTabbedPane jtp = new JTabbedPane();
getContentPane().add(jtp);
JPanel jp1 = new JPanel();
JLabel label1 = new JLabel();
JPanel jp2 = new JPanel();
JLabel label2 = new JLabel();
jp1.add(label1);
jtp.addTab("Andy - Encryption Program");
jp2.add(label2);
jtp.addTab("Andy - Hello World Program");
}
public static void main(String[] args) {
GUI tp = new GUI();
tp.setVisible(true);
tp.setMinimumSize(new Dimension(400, 400));
}
Here's one of our tabs:
public class encryptionPrograms extends GUI {
String[] options = new String[] { "XOR", "RSA" };
ComboBox optionsList = new JComboBox(options);
jp1.add(optionsList, BorderLayout.CENTER);
}
I'm not sure if I'm doing it correctly or not. Just got into Java and we've have been playing around with the GUI buttons and such.

There is a lot of "wrong" here and without you saying what your intention is with adding a comboBox to your jPanel it's hard to tell you the right way to do it but yes it can be done.
But first of: Always declare your variables before you initialize them so that you can access them for other methods in the class:
public class GUI extends JFrame{
private JPanel jp1,jp2;
private JLabel label1,label2;
private JTabbedPane jtp;
public GUI() {
setTitle("Andy and Jack's favorite programs");
jtp = new JTabbedPane();
jp1 = new JPanel();
label1 = new JLabel();
jp2 = new JPanel();
label2 = new JLabel();
jp1.add(label1);
jtp.addTab("Andy - Encryption Program", jp1);
jp2.add(label2);
jtp.addTab("Andy - Hello World Program",jp2);
getContentPane().add(jtp);
}
If you need to access a variable from another class you can write a get method for it.
For example:
public JPanel getMainJPanel(){
return jp1;
}
Now you can call the getMainJPanel() from another class in order to, for instance, add components to it. Just remember to .revalidate() and .repaint() the main frame after adding more components.

Related

CardLayout for JFrames?

I've been looking around, including in the Java documentation, but there isn't a clear answer that I've found for my question : I would like to switch from one JFrame to another at the click of a button; that is, have the old JFrame close while the new one opens. I've heard of "CardLayout" but I'm not so sure how it works. Would anyone mind explaining it, or some other method?
Thanks
Here is an example of a CardLayout
As you've heard other say, don't use multiple JFrames.
import javax.swing.*;
import java.awt.*;
public class MainFrame
{
static JPanel homeContainer;
static JPanel homePanel;
static JPanel otherPanel;
static CardLayout cl;
public MainFrame()
{
JFrame mFrame = new JFrame("CardLayout Example");
JButton showOtherPanelBtn = new JButton("Show Other Panel");
JButton backToHomeBtn = new JButton("Show Home Panel");
cl = new CardLayout(5, 5);
homeContainer = new JPanel(cl);
homeContainer.setBackground(Color.black);
homePanel = new JPanel();
homePanel.setBackground(Color.blue);
homePanel.add(showOtherPanelBtn);
homeContainer.add(homePanel, "Home");
otherPanel = new JPanel();
otherPanel.setBackground(Color.green);
otherPanel.add(backToHomeBtn);
homeContainer.add(otherPanel, "Other Panel");
showOtherPanelBtn.addActionListener(e -> cl.show(homeContainer, "Other Panel"));
backToHomeBtn.addActionListener(e -> cl.show(homeContainer, "Home"));
mFrame.add(homeContainer);
cl.show(homeContainer, "Home");
mFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mFrame.setLocationRelativeTo(null);
mFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mFrame.pack();
mFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}
You don't need to use a CardLayout for anything in this case. In fact, JFrame's don't have layouts.
Here's some code to illustrate that idea (assuming you're using Java 8; otherwise, add the final modifier to oldFrame and newFrame:
JFrame parent = new JFrame();
JDialog oldFrame = new JDialog("My Old Frame's Title");
JDialog newFrame = new JDialog("My New Frame's Title");
JPanel panel = new JPanel();
JButton myButton = new JButton();
myButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
oldFrame.dispose(); //closes your old frame
newFrame.setVisible(true); //opens your new frame
}
});
panel.add(myButton);
oldFrame.add(panek);
oldFrame.setVisible(true);
Whenever you click your button, the old frame closes, and the new one opens.

JButton opening new JFrame?

I have been looking for multiple ways to open a JFrame with a button. One of the ways I found was to establish the JFrame with a method and call upon that method with the button. That however does not seem to be working with my program. Could someone please tell me what I am doing wrong? I am pretty new to Java and am trying to learn on my own and seem to be doing a pretty terrible job of it. I am trying to create a Catalog and at the bottom of it have a button called "Make a New Purchase" which will open a new JFrame that will allow someone to enter their information. Much of the code in the program is unnecessary and I will edit it later, such as the multiple JPanels. All I need to do is get the new JFrame to come up with the button click. The showNewFrame() method is what I am trying to have activated by the button press.
public class Catalog extends JFrame
{
//Construct a panel for each row
JPanel firstRow = new JPanel();
JPanel secondRow = new JPanel();
JPanel thirdRow = new JPanel();
JPanel fourthRow = new JPanel();
JPanel fifthRow = new JPanel();
JPanel sixthRow = new JPanel();
JPanel seventhRow = new JPanel();
JPanel eighthRow = new JPanel();
JPanel ninthRow = new JPanel();
JPanel tenthRow = new JPanel();
JPanel eleventhRow = new JPanel();
JPanel twelvethRow = new JPanel();
JPanel thirteenthRow = new JPanel();
JPanel fourteenthRow = new JPanel();
JPanel fifteenthRow = new JPanel();
JPanel sixteenthRow = new JPanel();
JPanel seventeenthRow = new JPanel();
JPanel eighteenthRow = new JPanel();
JPanel nineteenthRow = new JPanel();
JPanel twentiethRow = new JPanel();
JPanel twentyfirstRow = new JPanel();
JPanel twentysecondRow = new JPanel();
JPanel twentythirdRow = new JPanel();
JPanel twentyfourthRow = new JPanel();
//Construct a panel for the fields and buttons
JPanel fieldPanel = new JPanel();
JPanel buttonPanel = new JPanel();
//Construct labels and text boxes
JLabel coatOneLabel = new JLabel("Coat One");
ImageIcon pictureOne = new ImageIcon("C:\\Users\\p6\\Desktop\\prodImage.jpeg");
JLabel picLabelOne = new JLabel(pictureOne);
JLabel priceOneLabel = new JLabel("Price:");
JLabel coatTwoLabel = new JLabel("Coat Two");
ImageIcon pictureTwo = new ImageIcon("snow.png");
JLabel picLabelTwo = new JLabel(pictureTwo);
JLabel priceTwoLabel = new JLabel("Price:");
JLabel coatThreeLabel = new JLabel("Coat Three");
ImageIcon pictureThree = new ImageIcon("snow.png");
JLabel picLabelThree = new JLabel(pictureThree);
JLabel priceThreeLabel = new JLabel("Price:");
JLabel coatFourLabel = new JLabel("Coat Four");
ImageIcon pictureFour = new ImageIcon("snow.png");
JLabel picLabelFour = new JLabel(pictureFour);
JLabel priceFourLabel = new JLabel("Price:");
JLabel coatFiveLabel = new JLabel("Coat Five");
ImageIcon pictureFive = new ImageIcon("snow.png");
JLabel picLabelFive = new JLabel(pictureFive);
JLabel priceFiveLabel = new JLabel("Price:");
JLabel coatSixLabel = new JLabel("Coat Six");
ImageIcon pictureSix = new ImageIcon("snow.png");
JLabel picLabelSix = new JLabel(pictureSix);
JLabel priceSixLabel = new JLabel("Price:");
JLabel coatSevenLabel = new JLabel("Coat Seven");
ImageIcon pictureSeven = new ImageIcon("snow.png");
JLabel picLabelSeven = new JLabel(pictureSeven);
JLabel priceSevenLabel = new JLabel("Price:");
JLabel coatEightLabel = new JLabel("Coat Eight");
ImageIcon pictureEight = new ImageIcon("snow.png");
JLabel picLabelEight = new JLabel(pictureEight);
JLabel priceEightLabel = new JLabel("Price:");
//Construct buttons
JButton submitButton = new JButton("Make A Purchase");
JButton exitButton = new JButton("Not Right Now");
public static void main(String[] args)
{
//set the look and feel of the interface
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"The UIManager could not set the Look and Feel for this application.","Error",JOptionPane.INFORMATION_MESSAGE);
}
Catalog f = new Catalog();
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setSize(800,600);
f.setTitle("Coat Catalog");
f.setResizable(false);
f.setLocation(200,200);
f.setVisible(true);
}
public Catalog()
{
Container c = getContentPane();
c.setLayout((new BorderLayout()));
fieldPanel.setLayout(new GridLayout(20,10));
FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
firstRow.setLayout(rowSetup);
secondRow.setLayout(rowSetup);
thirdRow.setLayout(rowSetup);
fourthRow.setLayout(rowSetup);
fifthRow.setLayout(rowSetup);
sixthRow.setLayout(rowSetup);
seventhRow.setLayout(rowSetup);
eighthRow.setLayout(rowSetup);
ninthRow.setLayout(rowSetup);
tenthRow.setLayout(rowSetup);
eleventhRow.setLayout(rowSetup);
twelvethRow.setLayout(rowSetup);
thirteenthRow.setLayout(rowSetup);
fourteenthRow.setLayout(rowSetup);
fifteenthRow.setLayout(rowSetup);
sixteenthRow.setLayout(rowSetup);
seventeenthRow.setLayout(rowSetup);
eighteenthRow.setLayout(rowSetup);
nineteenthRow.setLayout(rowSetup);
twentiethRow.setLayout(rowSetup);
twentyfirstRow.setLayout(rowSetup);
twentysecondRow.setLayout(rowSetup);
twentythirdRow.setLayout(rowSetup);
twentyfourthRow.setLayout(rowSetup);
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//Add fields to rows
firstRow.add(coatOneLabel);
firstRow.add(coatTwoLabel);
secondRow.add(picLabelOne);
secondRow.add(picLabelTwo);
thirdRow.add(priceOneLabel);
thirdRow.add(priceTwoLabel);
fourthRow.add(coatThreeLabel);
fourthRow.add(coatFourLabel);
fifthRow.add(picLabelThree);
fifthRow.add(picLabelFour);
sixthRow.add(priceThreeLabel);
sixthRow.add(priceFourLabel);
seventhRow.add(coatFiveLabel);
seventhRow.add(coatSixLabel);
eighthRow.add(picLabelFive);
eighthRow.add(picLabelSix);
ninthRow.add(priceFiveLabel);
ninthRow.add(priceSixLabel);
tenthRow.add(coatSevenLabel);
tenthRow.add(coatEightLabel);
eleventhRow.add(picLabelSeven);
eleventhRow.add(picLabelEight);
twelvethRow.add(priceSevenLabel);
twelvethRow.add(priceEightLabel);
//Add rows to panel
fieldPanel.add(firstRow);
fieldPanel.add(secondRow);
fieldPanel.add(thirdRow);
fieldPanel.add(fourthRow);
fieldPanel.add(fifthRow);
fieldPanel.add(sixthRow);
fieldPanel.add(seventhRow);
fieldPanel.add(eighthRow);
fieldPanel.add(ninthRow);
fieldPanel.add(tenthRow);
fieldPanel.add(eleventhRow);
fieldPanel.add(twelvethRow);
fieldPanel.add(thirteenthRow);
fieldPanel.add(fourteenthRow);
fieldPanel.add(fifteenthRow);
fieldPanel.add(sixteenthRow);
fieldPanel.add(seventeenthRow);
fieldPanel.add(eighteenthRow);
fieldPanel.add(nineteenthRow);
fieldPanel.add(twentiethRow);
fieldPanel.add(twentyfirstRow);
fieldPanel.add(twentysecondRow);
fieldPanel.add(twentythirdRow);
fieldPanel.add(twentyfourthRow);
//Add button to panel
buttonPanel.add(submitButton);
buttonPanel.add(exitButton);
//Add panels to frame
c.add(fieldPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent h)
{
if (h.getSource() == exitButton)
{
System.exit(0);
}
}
});
//Add functionality to buttons
submitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent d)
{
if (d.getSource() == submitButton)
{
showNewFrame();
}
}
});
}
private void showNewFrame()
{
JFrame BillPayer = new JFrame("BillPayer");
BillPayer.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
BillPayer.pack();
BillPayer.setVisible(true);
class BillPayer extends JFrame implements ActionListener
{
//Declare output stream
DataOutputStream output;
//Construct a panel for each row
JPanel firstRow = new JPanel();
JPanel secondRow = new JPanel();
JPanel thirdRow = new JPanel();
JPanel fourthRow = new JPanel();
JPanel fifthRow = new JPanel();
JPanel sixthRow = new JPanel();
JPanel seventhRow = new JPanel();
JPanel eighthRow = new JPanel();
//Construct a panel for the fields and buttons
JPanel fieldPanel = new JPanel();
JPanel buttonPanel = new JPanel();
//Construct labels and text boxes
JLabel acctNumLabel = new JLabel("Account Number: ");
JTextField acctNum = new JTextField(15);
JLabel pmtLabel = new JLabel("Payment Amount:");
JTextField pmt = new JTextField(10);
JLabel firstNameLabel = new JLabel("First Name: ");
JTextField firstName = new JTextField(10);
JLabel lastNameLabel = new JLabel("Last Name:");
JTextField lastName = new JTextField(20);
JLabel addressLabel = new JLabel("Address:");
JTextField address = new JTextField(35);
JLabel cityLabel = new JLabel("City: ");
JTextField city = new JTextField(10);
JLabel stateLabel = new JLabel("State:");
JTextField state = new JTextField(2);
JLabel zipLabel = new JLabel("Zip:");
JTextField zip = new JTextField(9);
//Construct button
JButton submitButton = new JButton("Submit");
public void main(String[] args)
{
//set the look and feel of the interface
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"The UIManager could not set the Look and Feel for this application.","Error",JOptionPane.INFORMATION_MESSAGE);
}
BillPayer f = new BillPayer();
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setSize(450,300);
f.setTitle("Crandall Power and Light Customer Payments");
f.setResizable(false);
f.setLocation(200,200);
f.setVisible(true);
}
public BillPayer()
{
Container c = getContentPane();
c.setLayout((new BorderLayout()));
fieldPanel.setLayout(new GridLayout(8,1));
FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
firstRow.setLayout(rowSetup);
secondRow.setLayout(rowSetup);
thirdRow.setLayout(rowSetup);
fourthRow.setLayout(rowSetup);
fifthRow.setLayout(rowSetup);
sixthRow.setLayout(rowSetup);
seventhRow.setLayout(rowSetup);
eighthRow.setLayout(rowSetup);
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//Add fields to rows
firstRow.add(acctNumLabel);
firstRow.add(pmtLabel);
secondRow.add(acctNum);
secondRow.add(pmt);
thirdRow.add(firstNameLabel);
thirdRow.add(lastNameLabel);
fourthRow.add(firstName);
fourthRow.add(lastName);
fifthRow.add(addressLabel);
sixthRow.add(address);
seventhRow.add(cityLabel);
seventhRow.add(stateLabel);
seventhRow.add(zipLabel);
eighthRow.add(city);
eighthRow.add(state);
eighthRow.add(zip);
//Add rows to panel
fieldPanel.add(firstRow);
fieldPanel.add(secondRow);
fieldPanel.add(thirdRow);
fieldPanel.add(fourthRow);
fieldPanel.add(fifthRow);
fieldPanel.add(sixthRow);
fieldPanel.add(seventhRow);
fieldPanel.add(eighthRow);
//Add button to panel
buttonPanel.add(submitButton);
//Add panels to frame
c.add(fieldPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
//Add functionality to buttons
submitButton.addActionListener(this);
//Get the current date and open the file
Date today = new Date();
SimpleDateFormat myFormat = new SimpleDateFormat("MMddyyyy");
String filename = "payments" + myFormat.format(today);
try
{
output = new DataOutputStream(new FileOutputStream(filename));
}
catch(IOException io)
{
JOptionPane.showMessageDialog(null,"The program could not create a storage location. Please check the disk drive and then run the program again.","Error",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent f)
{
int answer = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit and submit the file?", "File Submission",JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION)
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent f)
{
String arg = f.getActionCommand();
if(checkFields())
{
try
{
output.writeUTF(acctNum.getText());
output.writeUTF(pmt.getText());
output.writeUTF(firstName.getText());
output.writeUTF(lastName.getText());
output.writeUTF(address.getText());
output.writeUTF(city.getText());
output.writeUTF(state.getText());
output.writeUTF(zip.getText());
JOptionPane.showMessageDialog(null,"The payment information has been saved.","Submission successful",JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException c)
{
System.exit(1);
}
clearFields();
}
}
public boolean checkFields()
{
if ((acctNum.getText().compareTo("")<1) ||
(pmt.getText().compareTo("")<1) ||
(firstName.getText().compareTo("")<1) ||
(lastName.getText().compareTo("")<1) ||
(address.getText().compareTo("")<1) ||
(city.getText().compareTo("")<1) ||
(state.getText().compareTo("")<1) ||
(zip.getText().compareTo("")<1))
{
JOptionPane.showMessageDialog(null,"You must complete all fields.","Data Entry Error",JOptionPane.WARNING_MESSAGE);
return false;
}
else
{
return true;
}
}
public void clearFields()
{
//Clear fields and reset the focus
acctNum.setText("");
pmt.setText("");
firstName.setText("");
lastName.setText("");
address.setText("");
city.setText("");
state.setText("");
zip.setText("");
acctNum.requestFocus();
}
}
}
}
I tried to make quite a few changes to the program. The issue is that now the button does bring up a new window but the window doesn't include the data I need it to have. It has the title "Coat Payment", so I believe it is getting to everything but the inner class I have in the BillPayer method (the inner class is PaymentScreen). Once again I believe that my ignorance is leading me astray.
//Add functionality to buttons
submitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent d)
{
if (d.getSource() == submitButton)
{
BillPayer();
}
}
});
}
private void BillPayer()
{
JDialog PaymentScreen = new JDialog();
PaymentScreen.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
PaymentScreen.setSize(900,600);
PaymentScreen.setTitle("Coat Payment");
PaymentScreen.setResizable(false);
PaymentScreen.setLocation(200,200);
PaymentScreen.setVisible(true);
class PaymentScreen extends JDialog implements ActionListener
{
Sorry, but that's some schizophrenic code. Maybe I'm reading it wrong, but I see:
You create a JFrame variable called BillPayer, and set it visible. It is a small empty JFrame and nothing else.
You then declare a separate BillPayer class, and don't display it,
Except for in code within its (???) main method, a main method that is within a private inner class, which is (appropriately) never called.
Recommendations:
First and foremost, you probably really don't want to display another JFrame. Most applications should have only one main window, a JFrame.
If you need another window being displayed from a main window, then use a dialog such as a JDialog. This is fairly easy to do, and just like a JFrame involves creating a JPanel filled with your GUI, and then placing that JPanel into the JDialog and setting it visible.
If you use a JDialog, you can choose whether it is modal or not, whether it will freeze the underlying calling window when it is displayed or not.
To display another window from a button press, be it a JFrame or a JDialog, you would call setVisible(true) on the window from within the button press's ActionListener actionPerformed method. It looks like you're doing this. Is anything showing at all? Have you debugged the code to see if code you think is being reached is not being called?
Or if you want to display another view inside of the main window, use a CardLayout.
Don't give your variables the exact same name, spelling and capitalization as your classes.
Learn and follow Java naming conventions: class names begin with an upper case letter and variable and method names with lower-case letters.
Don't confuse your code by burying a main method inside of an inner private class. This makes little sense.
Study up on use of arrays and collections such as ArrayLists which can help you make programs that are much more compact, more readable, and easier to debug and extend. A lot of your code's redundancy can be reduced by doing this.
If you have code for another GUI view that is distinct from the main view, perhaps this code should be in its own top-level class, and not an inner class.
Edit
On review of your code some more, I suggest:
Yes, use a JDialog for the data entry window.
The data would probably be best displayed in a JTable held in a JScrollPane in the main GUI. This would be in place of the rows of JPanels that your current code uses.
This is going to sound rough, but it's more time efficient.
Select project > hit delete
Download Netbeans or Eclipse (or both) and program in these programs. They will help filter out mistakes you've made and provide a help with layout, so that it looks more comprehensible.
Once that's done, follow these tutorials:
http://docs.oracle.com/javase/tutorial/uiswing/start/index.html
The answer above already gave a lot of valuable tips, but your problem is that you simply do not know anything yet on how to properly build a program.
My tip: decide for yourself what would be awesome to make. Something you think is useful for yourself or others, then go through the tutorial and try to build it. This forces you to not only implement what you learn as you go along, but also run into the real issue with any programmming language: learn how to solve problems.

How do I add JPanels, created by methods, to cardLayout.add();

below is my user class for guiFrames. I want a class that creates several JFrames with methods and pass those methods into cardLayout. The reason for this is each JFrame will be have different buttons displayed depending on what the user has selected.
So, I thought I would create methods for the individual panels and depending on the parameter passed have different buttons displayed. I need the panels to be displayed in a cardLayout. But I am unable to pass the pass the methods into the cardLayout.add(); because it says the method type is invalid. So I tried to make the method return a Component but its not working out. Help please.
import javax.swing.*;
import java.awt.*;
public class guiFrames extends JFrame{
public guiFrames(){
}
public Component inputFrame(){
JFrame inputFrame = new JFrame("Input");
JPanel inputPnl = new JPanel();
inputPnl.setLayout(new GridLayout(3,2));
JLabel loginLbl = new JLabel("Login");
inputPnl.add(loginLbl);
JTextField loginTxt = new JTextField();
inputPnl.add(loginTxt);
JLabel pwLbl = new JLabel("Password");
inputPnl.add(pwLbl);
JTextField pwTxt = new JTextField();
inputPnl.add(pwTxt);
JPanel buttonPnl = new JPanel();
buttonPnl.setLayout(new FlowLayout(FlowLayout.LEFT, 1,5));
JButton submit = new JButton("Submit");
buttonPnl.add(submit);
JButton output = new JButton("Output");
buttonPnl.add(output);
JPanel container = new JPanel();
container.setLayout(new BorderLayout());
container.add(inputPnl, BorderLayout.CENTER);
container.add(buttonPnl, BorderLayout.SOUTH);
inputFrame.add(container);
inputFrame.pack();
inputFrame.setVisible(true);
inputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return;
}
public void cardView(){
JFrame cardFrame = new JFrame();
JPanel cardGUI = new JPanel();
CardLayout cards = new CardLayout();
cardGUI.setLayout(cards);
cardGUI.add(inputFrame(), "first");
cardFrame.add(cardGUI, BorderLayout.CENTER);
cardFrame.pack();
cardFrame.setVisible(true);
cardFrame.setDefaultCloseOperation(cardFrame.EXIT_ON_CLOSE);
}
}
At the end of inputFrame() you aren't returning anything. You need to return the inputFrame, like this:
return inputFrame;
Hope that helps.

Button and textfield don't show up in Java

For school I had to make a JFrame and within that One button and Two textfields. Whatever you put in Textfield one have to get into textfield two when the button is pressed. I got the code to the point I should see the textfields and the button when i run the program. For whatever reason it doesn't.
My come so far:
package helloworld;
import javax.swing.*;
import java.awt.event.*;
public class HelloWorld extends JFrame {
public static void main(String[] args) {
JFrame frame = new HelloWorld();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Hello World Button App");
JPanel panel = new JPanel();
frame.setContentPane(panel);
fram.setVisible(true);
}
}
class panel extends JPanel {
public JButton btn1 = new JButton("Klick!");
public JTextField txt1 = new JTextField(10);
public JTextField txt2 = new JTextField(10);
public panel() {
add(btn1);
add(txt1);
add(txt2);
}
}
I am not yet allowed to post images but I will provide a link to the picture down here
I am sorry if this question allready exests but i couldnt's find a similar question.
I am new to programming so please dont yell at me when I forgot something or wrote something wrong in it!
Here i have modified your code a bit, but did in a similar way.
I won't extend JFrame until and unless i don't want to do something creative, but you always CAN.
You had already extended JFrame , so no worth of calling methods with frame.foo()
but simply foo() , and most important JFrame frame = new HelloWorld() , will make no sense, if you have already extended you class with JFrame:
import javax.swing.*;
public class HelloWorld extends JFrame{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new HelloWorld().setVisible(true);
}
});
}
public HelloWorld()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Hello World Button App");
panel pan= new panel();
add(pan.panel);
pack();
setVisible(true);
}
}
class panel {
private JButton btn1 = new JButton("Klick!");
private JTextField txt1 = new JTextField(10);
private JTextField txt2 = new JTextField(10);
JPanel panel;
public panel() {
panel = new JPanel();
panel.add(btn1);
panel.add(txt1);
panel.add(txt2);
}
}
Also, you can also extend your panel class with JPanel :
public HelloWorld()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Hello World Button App");
panel pan= new panel();
add(pan);
pack();
setVisible(true);
}
}
class panel extends JPanel {
private JButton btn1 = new JButton("Klick!");
private JTextField txt1 = new JTextField(10);
private JTextField txt2 = new JTextField(10);
public panel() {
add(btn1);
add(txt1);
add(txt2);
}
}
That is because your class name is panel not JPanel
Modify this:
panel panel = new panel();
frame.setContentPane(panel);
frame.setVisible(true);
You should try to use names for your Class that are not so confusing, and try to declare them with uppercase.
Example:
Class Panel extends JPanel {}
Object:
Panel panel = new Panel()
Here you can clearly read which one is the class name and which is the object (instance of that class) of that class.
You declared a class called panel that you are not using anywhere. Please replace the line bwlow:
JPanel panel = new JPanel();
with:
SomePanel panel = new SomePanel();
Then, your class panel becomes SomePanel to follow correct class naming.
Some thoughts to help you:
Name your classes following the Java style
Don't use public fields
Set layouts on your panels. This time it worked for you as the default is FlowLayout.

Add Jpanel to Jframe NetBeans

Hi all, I was in a development of my college mini project. It was a Library Management system , which i should do in Java swing using Net-beans IDE. First I was doing manual coding. It takes time.
In manual coding I create single JFrame with Menu bar and and items, on all action performed I wrote codes for all Jpanels. It made the file and code huge. and confusing too.
Now I need your help.
I have created a Main JFrame with Menu
A JPanel - ADD Book
another Jpanel - On add book success (demo! , for Actions happening in ADD Book )
I had made action listener
addBook addbk = new addBook();
this.getContentPane().add(addbk);
wrote this code.
I doesn't make sense.
Friends, As a new to java, What i need to study is
1.) How cal and Show an external Jpanel an action performed
2.) How to show another JPanel to same root JFrame if any event has occurred in external JPanel.
In sort, something like Iframe in HTML
Thank you all.
http://compilr.com/abelkbil/openlib/OpenLibMainGUI.java
http://compilr.com/abelkbil/openlib/addBook.java
http://compilr.com/abelkbil/openlib/bookAdded.java
CardLayout, is exactly what you need for this situation. And do learn Java Naming Conventions and stick to them, as you are a beginner, so to be on the right track from the start is always GOOD.
Here is one example, that you can look at :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel panel2;
private MyPanel panel3;
private JComboBox choiceBox;
private String[] choices = {
"Panel 1",
"Panel 2",
"Panel 3"
};
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
choiceBox = new JComboBox(choices);
panel1 = new MyPanel(contentPane
, Color.RED.darker().darker(), this);
panel2 = new MyPanel(contentPane
, Color.GREEN.darker().darker(), this);
panel3 = new MyPanel(contentPane
, Color.DARK_GRAY, this);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
contentPane.add(panel3, "Panel 3");
frame.getContentPane().add(choiceBox, BorderLayout.PAGE_START);
frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JComboBox getChoiceBox()
{
return choiceBox;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel
{
private JButton jcomp1;
private JPanel contentPane;
private Color backgroundColour;
private JComboBox choiceBox;
public MyPanel(JPanel panel, Color c, CardLayoutExample cle)
{
contentPane = panel;
backgroundColour = c;
choiceBox = cle.getChoiceBox();
setOpaque(true);
setBackground(backgroundColour);
//construct components
jcomp1 = new JButton ("Show New Panel");
jcomp1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String changeToPanel = (String) choiceBox.getSelectedItem();
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, changeToPanel);
}
});
add(jcomp1);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
Else you can have a look at this example also.

Categories

Resources