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.
Related
I am learning Java and I have to develop an application using a GUI. I have the application working in command line already, but the GUI is driving me insane and costing me in lost hours of head banging and research which is leading nowhere. Can you please help me get the basics working so that i can develop further from there. I want to have a single frame application that can switch between frames on a button click. I created a frame and added three panels P1-P3. These are set as Card Layout (from what i read from forums). Then I added additional panels to these to which i have set colour and buttons.
'''
public class MyMainForm extends JFrame{
private JPanel P1;
private JPanel P2;
private JPanel P3;
private JButton btnFrame1;
private JButton btnFrame2;
private JButton button1;
private JTextField thisIsPanel3TextField;
private JButton btn2Frame1;
private final JFrame frame = new JFrame("MyMain Frame");
public MyMainForm() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(P1);
pack();
setSize(1000,800);
//setLocation(null);
btnFrame1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P1.setVisible(false);
setContentPane(new MyMainForm().P2);
}
});
btnFrame2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P2.setVisible(false);
setContentPane(new MyMainForm().P3);
}
});
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P3.setVisible(false);
setContentPane(new MyMainForm().P2);
}
});
btn2Frame1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
P1.setVisible(false);
setContentPane(new MyMainForm().P3);
}
});
}
public static void main(String[] args) {
MyMainForm MyMainForm = new MyMainForm();
MyMainForm.setVisible(true);
}
}
'''
I can display P2 or P3 with this new code example above. When i try to go from P2 or P3 back to P1 the content pane doesn't show? Do i need to revalidate the content pane for this to work? I really need to be able to go from P1 to P2
The easiest way to do this is to use a CardLayout. Just follow this example:
JFrame frame = new JFrame();
JPanel p1 = new JPanel();
p1.setBackground(Color.RED);
JPanel p2 = new JPanel();
p2.setBackground(Color.WHITE);
JPanel p3 = new JPanel();
p3.setBackground(Color.BLUE);
//Create the panel that contains the "cards".
JPanel cards = new JPanel(new CardLayout());
cards.add(p1, "Panel 1");
cards.add(p2, "Panel 2");
cards.add(p3, "Panel 3");
// Add your card container to the frame
Container pane = frame.getContentPane();
pane.add(cards, BorderLayout.CENTER);
JButton btn = new JButton("Click me!");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.next(cards);
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(btn);
pane.add(btnPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
Alternatively, you can switch to a specific panel by calling cl.show(cards, "Panel X") where X is the number of the panel. This is because the swing argument is the name I assigned to each "card" and the show method recalls panels added to CardLayout by name. For your example, each button should have a listener that uses this method to "show" its assigned panel.
I am working on a semester project that I have and I was wondering if it was possible to store 3-4 JPanels instead one single "main" JPanel. The reason for me asking this is because I a trying to make a GUI checkbook program and my checkbook has 7 buttons that should open a new window once I click on it. To switch between each window I'm going to have to use the CardLayout, but my understand of the CardLayout is that I can only assign one single JPanel to that card so I can't assign multiple JPanels to a single Card layout so when the user clicks on a different card 3-4 different JPanels appear.
The reason that I am asking this is because I asked for help earlier and received help for creating my first window in this project, it produces the output I want PERFECTLY, but uses more than 1 JPanel in doing so. Since this prevents me from continuing on to the other steps of my 7 GUI Windows, I am stuck.
Here is the code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class checkbook extends JPanel implements ActionListener {
private static final String title = "Use The Buttons Below To Manage Transactions";
private static final String[] bottomButtons = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
static JButton Button[] = new JButton[8];
static ActionListener AL = new checkbook();
public checkbook() {
JLabel titleLabel = new JLabel(title, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 18));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JTextField textfield = new JTextField();
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(4));
accountBalancePanel.add(new JLabel("Balance:"));
textfield = new JTextField("0.0", 10);
textfield.setHorizontalAlignment(JTextField.RIGHT);
accountBalancePanel.add(textfield);
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
southBtnPanel.add(Button[i]);
Button[i].addActionListener(AL);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(100, 100))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
checkbook mainPanel = new checkbook();
JFrame frame = new JFrame("Checkbook");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowGui();
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button[7]) {
System.exit(0);
}
}
}
Credit goes to Hovercraft Full Of Eels for showing me the above example
If there is anything that is unclear about my question, please ask and I will do the best I can to fix it.
Here is what the code produces:
http://i.stack.imgur.com/WY0c3.png
Picture included I have another issue where my buttons go to the top-right after the user inputs their name. At this point, text shows up in the GUI on the LEFT side of the center which seems it would be "WEST" when I put "CENTER". Code:
public TheDungeon()
{
setTitle("InsertGameNameHere");
setSize(750, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setLocationRelativeTo(null);
buildButtonPanel();
characterInfoPanel = new JLabel("<html>Character information will go here</html>");
gameScreen = new JLabel();
inventoryPanel = new JLabel("<html>This is for the inventory</html>");
add(gameScreen, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
//Program run
userName();
gameScreen.setText("<html>Welcome "+name+", to the game that has no name!</html>");
classWindow();
}
private void buildButtonPanel()
{
// Create a panel for the buttons.
buttonPanel = new JPanel();
// Create the buttons.
b1 = new JButton("Button 1");
b2 = new JButton("Button 2");
b3 = new JButton("Button 3");
b4 = new JButton("Button 4");
b5 = new JButton("Button 5");
// Add the buttons to the button panel.
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
buttonPanel.add(b4);
buttonPanel.add(b5);
}
private void userName() {
name = JOptionPane.showInputDialog("What will your name be?");
}
I'm not sure why your program is behaving as it seems to be since when I ran it, it did not do this. You may wish to check your code to make sure that it's the code you're posting here. But regardless, I do have some suggestions:
Best to not set the sizes of anything, but rather to let the components and the layout managers do this for you.
Consider if you must overriding getPreferredSize() if you need to control the size of a component more fully.
Call pack() on your top level window after adding all components and before calling setVisible(true). This will tell the layout managers to do their things.
Avoid extending JFrame since you will rarely need to override one of its innate behaviors.
If you do add or remove components, or change their preferredSizes somehow after rendering your top-level window, you will want to call revalidate() and then repaint() on the component's container to have the container re-layout the components it holds and then redraw them.
For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
public class TheDungeon2 extends JPanel {
private static final int PREF_W = 750;
private static final int PREF_H = 600;
private static final String[] BUTTON_LABELS = {"Button 1", "Button 2",
"Button 3", "Button 4", "Button 5"};
private static final String WELCOME_TEXT = "Welcome %s to the game that has no name!";
private JLabel welcomeLabel = new JLabel("", SwingConstants.CENTER);
private String name;
public TheDungeon2() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
for (String buttonLabel : BUTTON_LABELS) {
JButton button = new JButton(buttonLabel);
buttonPanel.add(button);
}
setLayout(new BorderLayout());
add(welcomeLabel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public void getAndSetName() {
name = JOptionPane.showInputDialog(this, "What will your name be?");
welcomeLabel.setText(String.format(WELCOME_TEXT, name));
}
private static void createAndShowGui() {
TheDungeon2 dungeon2 = new TheDungeon2();
JFrame frame = new JFrame("Nameless Game");
dungeon2.getAndSetName();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(dungeon2);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I tested your code with an empty classWindow() method and the buttons are correctly placed in south,
for the CENTER issue, you should place something in WEST to have your text centred (even an empty panel) otherwise CENTER will take all the place,
look at this , i added this line :
add(new JButton("a button for test"),BorderLayout.WEST);
and here is the result :
the code is there for clearing the Frame area by clicking the sub menu(sub_menu_purchase and sub_menu_sale) of main menu.
public void clear()
{
Graphics g = getGraphics();
Dimension d = getSize();
g.setColor(Color.WHITE);
g.fillRect(0,0,d.width,d.height);
}
void sale()
{
lblinvoice =new JLabel("Invoice No. : ");
lbldate =new JLabel("Date : ");
lblform =new JLabel("From Party : ");
lblto =new JLabel("To Party : ");
txtto=new JTextField();
txtfrom=new JTextField();
btncancel=new JButton("Cancel");
btnprint=new JButton("Print");
btnreset=new JButton("Reset");
btnsave=new JButton("Save");
lblinvoice.setBounds(50,100,80,25);
lbldate.setBounds(440,100,80,25);
lblto.setBounds(50,135,80,25);
txtto.setBounds(140,135,200,25);
lblform.setBounds(50,170,80,25);
txtfrom.setBounds(140,170,100,25);
btnreset.setBounds(50,450,80,25);
btnsave.setBounds(140,450,80,25);
btnprint.setBounds(230,450,80,25);
btncancel.setBounds(420,450,80,25);
add(lblinvoice);
add(lbldate);
add(lblto);
add(lblform);
add(txtto);
add(txtfrom);
add(btncancel);
add(btnprint);
add(btnreset);
add(btnsave);
setVisible(true);
}
void purchase()
{
lblinvoice =new JLabel("Invoice No. : ");
lbldate =new JLabel("Date : ");
lblparty =new JLabel("Party Name: ");
txtparty=new JTextField();
btncancel=new JButton("Cancel");
btnprint=new JButton("Print");
btnreset=new JButton("Reset");
btnsave=new JButton("Save");
lblinvoice.setBounds(50,100,80,25);
lbldate.setBounds(440,100,80,25);
lblparty.setBounds(50,135,80,25);
txtparty.setBounds(140,135,200,25);
btnreset.setBounds(50,450,80,25);
btnsave.setBounds(140,450,80,25);
btnprint.setBounds(230,450,80,25);
btncancel.setBounds(420,450,80,25);
add(lblinvoice);
add(lbldate);
add(lblparty);
add(txtparty);
add(btncancel);
add(btnprint);
add(btnreset);
add(btnsave);
setVisible(true);
}
public void actionPerformed(ActionEvent event) //set up actionlistening
{
Object source=event.getSource();
if (source.equals(sub_menu_purchase))
{ clear();
purchase();
}
if (source.equals(sub_menu_sale))
{ clear();
sale();
}
}
But it is not clear the area and override to one another.
what code should I write?
There's a lot I would do differently from what you're doing, including
Don't get a component's Graphics via getGraphics(). The Graphics object thus obtained will not persist, and so it is not useful for making stable changes to a GUI's appearance.
Don't clear the GUI's graphics but rather change the view. Even if your code worked, the components would not have been removed from the GUI with your code. They would still exist and still sit on the GUI -- not good.
A CardLayout would work well for allowing you to swap a container's view, and is often used to swap JPanels, each holding its own GUI.
Avoid null layout and using setBounds(...) as this will lead to creation of GUI's that are a "witch" to upgrade and maintain and that look bad on all platforms except for one. Better to nest JPanels, each using its own simple layout, to achieve complex, beautiful and easy to maintain and improve GUI's.
Read/study the Swing tutorials as all of this is well explained there.
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class UglyGui2 {
private static final String SALE = "Sale";
private static final String PURCHASE = "Purchase";
private JMenuItem sub_menu_sale = new JMenuItem(SALE);
private JMenuItem sub_menu_purchase = new JMenuItem(PURCHASE);
private CardLayout cardLayout = new CardLayout();
private JPanel cardPanel = new JPanel(cardLayout);
private JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
public UglyGui2() {
cardPanel.add(new JLabel(), "");
cardPanel.add(createSalePanel(), SALE);
cardPanel.add(createPurchasePanel(), PURCHASE);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(new JButton("Reset"));
buttonPanel.add(new JButton("Save"));
buttonPanel.add(new JButton("Print"));
buttonPanel.add(new JLabel());
buttonPanel.add(new JButton("Cancel"));
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.add(cardPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.PAGE_END);
}
private JComponent createSalePanel() {
JPanel salePanel = new JPanel(new GridBagLayout());
salePanel.add(new JLabel("Sales"));
salePanel.add(new JTextField(10));
return salePanel;
}
private JComponent createPurchasePanel() {
JPanel topPanel = new JPanel();
topPanel.add(new JLabel("Purchases"));
topPanel.add(new JTextField(10));
JPanel purchasePanel = new JPanel(new BorderLayout());
purchasePanel.add(topPanel, BorderLayout.PAGE_START);
purchasePanel.add(new JScrollPane(new JTextArea(30, 60)), BorderLayout.CENTER);
return purchasePanel; }
private Component getMainPanel() {
return mainPanel;
}
private JMenuBar getJMenuBar() {
ActionListener aListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, e.getActionCommand());
}
};
sub_menu_purchase.addActionListener(aListener);
sub_menu_sale.addActionListener(aListener);
JMenu menu = new JMenu("Menu");
menu.add(sub_menu_purchase);
menu.add(sub_menu_sale);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
return menuBar;
}
private static void createAndShowGui() {
UglyGui2 uglyGui = new UglyGui2();
JFrame frame = new JFrame("Ugly Gui Example");
frame.setJMenuBar(uglyGui.getJMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(uglyGui.getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I would like to know what code to insert and where to add a simple label that can just say the word "Label" and a input text box that I can enter a number.
public CalculateDimensions() {
JTabbedPane Tab = new JTabbedPane();
JPanel jplInnerPanel1 = createInnerPanel("First Tab");
Tab.addTab("One", jplInnerPanel1);
Tab.setSelectedIndex(0);
JPanel jplInnerPanel2 = createInnerPanel("Second Tab");
Tab.addTab("Two", jplInnerPanel2);
JPanel jplInnerPanel3 = createInnerPanel("Third Tab");
Tab.addTab("Three", jplInnerPanel3);
JPanel jplInnerPanel4 = createInnerPanel("Fourth Tab");
Tab.addTab("Four", jplInnerPanel4);
JPanel jplInnerPanel5 = createInnerPanel("Fifth Tab");
Tab.addTab("Five", jplInnerPanel5);
setLayout(new GridLayout(1, 1));
add(Tab);
}
protected JPanel createInnerPanel(String text) {
JPanel jplPanel = new JPanel();
JLabel jlbDisplay = new JLabel(text);
jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
jplPanel.setLayout(new GridLayout(1, 1));
jplPanel.add(jlbDisplay);
return jplPanel;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Calculations");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.getContentPane().add(new CalculateDimensions(),
BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
The Swing tutorial is an excellent resource for building GUIs.
Take a look at the visual guide and click on the components you want for detailed how to guides for creating text boxes, and other items.
http://download.oracle.com/javase/tutorial/ui/features/components.html
in your public static void main() method you should not instantiate JFrame frame = new JFrame("Calculations");
This is where you are going wrong!
That line should read:
CalculateDimensions frame = new CalculateDimensions("Calculations");
You will also need to change the line says
public class CalculateDimensions {
(it's near the top) says
public class CalculateDimensions extends JFrame {
then inside the method called public class CalculateDimensions { you need to add a line after JPanel jplInnerPanel1 = createInnerPanel("First Tab"); which says
jplInnerPanel1.add(new JLabel("Label");