My Java GUI application wont display data from the PersonUI.java class with the layout details im using MIGLayout in Netbeans 8.0.
All the files i n the project have no errors it wont display the GUI. May help me with displaying the MIGlayout .
package View;
import Model.Person;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import net.miginfocom.swing.MigLayout;
/**
/**
*
* #author Mbano
*/import Controller.PersonBean;
public class PersonUI extends JPanel {
private JTextField idField = new JTextField(10);
private JTextField fNameField = new JTextField(30);
private JTextField mNameField, lNameField, emailField, phoneField;
private JButton createButton = new JButton("New...");
private JButton updateButton, deleteButton, firstButton, prevButton, nextButton,
lastButton;
private PersonBean bean = new PersonBean();
public PersonUI() {
setBorder(new TitledBorder
(new EtchedBorder(),"Person Details"));
setLayout(new BorderLayout(5, 5));
add(initFields(), BorderLayout.NORTH);
add(initButtons(), BorderLayout.CENTER);
setFieldData(bean.moveFirst());
}
private JPanel initButtons() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
panel.add(createButton);
createButton.addActionListener(new ButtonHandler());
//...
panel.add(lastButton);
lastButton.addActionListener(new ButtonHandler());
return panel;
}
private JPanel initFields() {
JPanel panel = new JPanel();
panel.setLayout(new MigLayout());
panel.add(new JLabel("ID"), "align label");
panel.add(idField, "wrap");
idField.setEnabled(false);
panel.add(new JLabel("First Name"), "align label");
panel.add(fNameField, "wrap");
//...
panel.add(new JLabel("Phone"), "align label");
panel.add(phoneField, "wrap");
return panel;
}
private Person getFieldData() {
Person p = new Person();
p.setPersonId(Integer.parseInt(idField.getText()));
p.setFirstName(fNameField.getText());
p.setMiddleName(mNameField.getText());
p.setLastName(lNameField.getText());
p.setEmail(emailField.getText());
p.setPhone(phoneField.getText());
return p;
}
private void setFieldData(Person p) {
idField.setText(String.valueOf(p.getPersonId()));
fNameField.setText(p.getFirstName());
mNameField.setText(p.getMiddleName());
lNameField.setText(p.getLastName());
emailField.setText(p.getEmail());
phoneField.setText(p.getPhone());
}
private boolean isEmptyFieldData() {
return (fNameField.getText().trim().isEmpty()
&& mNameField.getText().trim().isEmpty()
&& lNameField.getText().trim().isEmpty()
&& emailField.getText().trim().isEmpty()
&& phoneField.getText().trim().isEmpty());
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Person p = getFieldData();
switch (e.getActionCommand()) {
case "Save":
if (isEmptyFieldData()) {
JOptionPane.showMessageDialog(null,
"Cannot create an empty record");
return;
}
if (bean.create(p) != null)
JOptionPane.showMessageDialog(null,
"New person created successfully.");
createButton.setText("New...");
break;
case "New...":
p.setPersonId(new Random()
.nextInt(Integer.MAX_VALUE) + 1);
p.setFirstName("");
p.setMiddleName("");
p.setLastName("");
p.setEmail("");
p.setPhone("");
setFieldData(p);
createButton.setText("Save");
break;
case "Update":
if (isEmptyFieldData()) {
JOptionPane.showMessageDialog(null,
"Cannot update an empty record");
return;
}
if (bean.update(p) != null)
JOptionPane.showMessageDialog(
null,"Person with ID:" + String.valueOf(p.getPersonId()
+ " is updated successfully"));
break;
case "Delete":
if (isEmptyFieldData()) {
JOptionPane.showMessageDialog(null,
"Cannot delete an empty record");
return;
}
p = bean.getCurrent();
bean.delete();
JOptionPane.showMessageDialog(
null,"Person with ID:"
+ String.valueOf(p.getPersonId()
+ " is deleted successfully"));
break;
case "First":
setFieldData(bean.moveFirst()); break;
case "Previous":
setFieldData(bean.movePrevious()); break;
case "Next":
setFieldData(bean.moveNext()); break;
case "Last":
setFieldData(bean.moveLast()); break;
default:
JOptionPane.showMessageDialog(null,
"invalid command");
}
}
}
}
package View;
import java.awt.FlowLayout;
import javax.swing.JFrame;
/**
*
* #author Mbano
*/
public class AppMain {
public static void main(String[] args) {
JFrame f =new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
f.getContentPane().add(new PersonUI());
f.setSize(600, 280);
f.setVisible(true);
}
}
Check the console for any exceptions. Try
new MigLayout("debug")
to see your Layout in debg mode.
You could also set different background colors to the differen JPanels, to see what size they have.
Related
I want to do the same like this:
Here's the code:
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
class QuizGUI {
public static void main(String args[]) {
JFrame frm = new JFrame("Simple Quiz");
frm.setLayout(null);
JLabel lbl1 = new JLabel("Which Animal can fly?");
JLabel lbl2 = new JLabel("You have selected: ");
JLabel lblOutput = new JLabel();
JRadioButton rCat = new JRadioButton("Cat");
JRadioButton rBird = new JRadioButton("Bird");
JRadioButton rFish = new JRadioButton("Fish");
ButtonGroup bg = new ButtonGroup();
bg.add(rCat);
bg.add(rBird);
bg.add(rFish);
lbl1.setBounds(0, 0, 200, 20);
rCat.setBounds(0, 20, 100, 20);
rBird.setBounds(0, 40, 100, 20);
rFish.setBounds(0, 60, 100, 20);
lbl2.setBounds(0, 80, 200, 20);
lblOutput.setBounds(0, 105, 200, 20);
frm.add(lbl1);
frm.add(rCat);
frm.add(rBird);
frm.add(rFish);
frm.add(lbl2);
frm.add(lblOutput);
rCat.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (rCat.isSelected()) {
lblOutput.setText("Cat can't fly, Try again.");
}
}
});
rBird.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (rBird.isSelected()) {
lblOutput.setText("Bird can fly, Excellent.");
}
}
});
rFish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (rFish.isSelected()) {
lblOutput.setText("Cat can't fly, Try again.");
}
}
});
frm.setVisible(true);
frm.setSize(350, 200);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The problem is, I want the colors of window like image the background is white and the background for choices is gray.
I tried frame.setBackground but doesn't work.
I tried some codes for another examples and the color was white. I don't know why the window is all gray like this:
From the code you posted in your question:
frm.setLayout(null);
This is not a good idea. I recommend always using a layout manager. JFrame is a top-level container. It has a content pane which, by default, is a JPanel. The default layout manager for the content pane is BorderLayout. You can refer to the source code for JFrame in order to confirm this.
In my opinion BorderLayout is suitable for your GUI. One JPanel is the NORTH component and it displays the question, namely Which Animal can fly?, the radio buttons are the CENTER component and the text You have selected: is the SOUTH panel.
Each JPanel can then have its own background color. I am using JDK 13 on Windows 10 and the default background color is gray. Hence, in the code below, I set the background color for the NORTH and SOUTH panels and leave the CENTER panel with its default background color.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
public class QuizGUI implements ActionListener, Runnable {
private static final String BIRD = "Bird";
private static final String CAT = "Cat";
private static final String FISH = "Fish";
private JFrame frame;
private JLabel resultLabel;
#Override // java.awt.event.ActionListener
public void actionPerformed(ActionEvent event) {
String actionCommand = event.getActionCommand();
switch (actionCommand) {
case BIRD:
resultLabel.setText(BIRD + " can fly. Excellent.");
break;
case CAT:
resultLabel.setText(CAT + " can't fly. Try again.");
break;
case FISH:
resultLabel.setText(FISH + " can't fly. Try again.");
break;
default:
resultLabel.setText(actionCommand + " is not handled.");
}
}
#Override // java.lang.Runnable
public void run() {
createAndShowGui();
}
private void createAndShowGui() {
frame = new JFrame("Simple Quiz");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createQuestionPanel(), BorderLayout.PAGE_START);
frame.add(createChoicesPanel(), BorderLayout.CENTER);
frame.add(createOutcomePanel(), BorderLayout.PAGE_END);
frame.setSize(350, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void createRadioButton(String text, ButtonGroup bg, JPanel panel) {
JRadioButton radioButton = new JRadioButton(text);
radioButton.addActionListener(this);
bg.add(radioButton);
panel.add(radioButton);
}
private JPanel createChoicesPanel() {
JPanel choicesPanel = new JPanel(new GridLayout(0, 1));
ButtonGroup bg = new ButtonGroup();
createRadioButton(CAT, bg, choicesPanel);
createRadioButton(BIRD, bg, choicesPanel);
createRadioButton(FISH, bg, choicesPanel);
return choicesPanel;
}
private JPanel createOutcomePanel() {
JPanel outcomePanel = new JPanel(new GridLayout(0, 1, 0, 5));
outcomePanel.setBackground(Color.WHITE);
JLabel promptLabel = new JLabel("You have selected:");
setBoldFont(promptLabel);
outcomePanel.add(promptLabel);
resultLabel = new JLabel(" ");
outcomePanel.add(resultLabel);
return outcomePanel;
}
private JPanel createQuestionPanel() {
JPanel questionPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
questionPanel.setBackground(Color.WHITE);
JLabel questionLabel = new JLabel("Which Animal can fly?");
setBoldFont(questionLabel);
questionPanel.add(questionLabel);
return questionPanel;
}
private void setBoldFont(JLabel label) {
Font boldFont = label.getFont().deriveFont(Font.BOLD);
label.setFont(boldFont);
}
public static void main(String[] args) {
String slaf = UIManager.getSystemLookAndFeelClassName();
try {
UIManager.setLookAndFeel(slaf);
}
catch (ClassNotFoundException |
IllegalAccessException |
InstantiationException |
UnsupportedLookAndFeelException x) {
System.out.println("WARNING (ignored): Failed to set [system] look-and-feel");
x.printStackTrace();
}
EventQueue.invokeLater(new QuizGUI());
}
}
First create a private JPanel called contentPane in your QuizGUI class. Then in your main method, type:
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frm.setContentPane(contentPane);
contentPane.setLayout(null);
then, change all frm.add() with contentPane.add()
I hope this helped!
The JFrame window needs to display a random dice image. When the button is clicked, the random dice image needs to change. I have figured out how to display the random dice image, but I cannot figure out how to use the actionlistener to generate a new random dice image. I am only in my third Java class, so any guidance would be greatly appreciated!
package guiDice;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.util.Random;
import java.awt.event.ActionEvent;
public class LabGuiDice extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LabGuiDice frame = new LabGuiDice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LabGuiDice() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JButton btnRollem = newDiceRoll();
contentPane.add(btnRollem, BorderLayout.SOUTH);
JLabel lblDice = newDiceImage();
contentPane.add(lblDice, BorderLayout.CENTER);
}
private JLabel newDiceImage() {
Random rnd = new Random();
int rand1 = 0;
rand1 = rnd.nextInt(6)+1;
JLabel lblDice = new JLabel("");
switch (rand1) {
case 1:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-1.png")));
break;
case 2:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-2.png")));
break;
case 3:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-3.png")));
break;
case 4:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-4.png")));
break;
case 5:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-5.png")));
break;
case 6:
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-6.png")));
break;
}
return lblDice;
}
private JButton newDiceRoll() {
JButton btnRollem = new JButton("Roll 'Em");
btnRollem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnRollem.setBorderPainted(false);
btnRollem.setFont(new Font("Bodoni 72 Smallcaps", Font.PLAIN, 27));
btnRollem.setOpaque(true);
btnRollem.setBackground(new Color(255, 0, 0));
return btnRollem;
}
}
Create a method that generates the integer and sets the icon to the label. But in order to do that, label should be a field in the class, so all methods can access it. For example:
private void rollDice() {
Random random = new Random();
int randomInt = random.nextInt(6) + 1;
String resource = String.format("/Dice/die-%d.png", randomInt);
Icon icon = new ImageIcon(LabGuiDice.class.getResource(resource));
diceIconLabel.setIcon(icon);
}
and then:
btnRollem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rollDice();
}
});
with full code:
public class LabGuiDice extends JFrame {
private JPanel contentPane;
private JLabel diceIconLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
LabGuiDice frame = new LabGuiDice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LabGuiDice() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JButton btnRollem = newDiceRoll();
contentPane.add(btnRollem, BorderLayout.SOUTH);
diceIconLabel = newDiceImage();
contentPane.add(diceIconLabel, BorderLayout.CENTER);
rollDice();
pack();
}
private void rollDice() {
Random random = new Random();
int randomInt = random.nextInt(6) + 1;
String resource = String.format("/Dice/die-%d.png", randomInt);
Icon icon = new ImageIcon(LabGuiDice.class.getResource(resource));
diceIconLabel.setIcon(icon);
}
private JLabel newDiceImage() {
JLabel lblDice = new JLabel("");
lblDice.setHorizontalAlignment(SwingConstants.CENTER);
return lblDice;
}
private JButton newDiceRoll() {
JButton btnRollem = new JButton("Roll 'Em");
btnRollem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
rollDice();
}
});
btnRollem.setBorderPainted(false);
btnRollem.setFont(new Font("Bodoni 72 Smallcaps", Font.PLAIN, 27));
btnRollem.setOpaque(true);
btnRollem.setBackground(new Color(255, 0, 0));
return btnRollem;
}
}
I am working on a Java Swing application.
My Requirement :-
In my JFrame, I have a JList with values "One", "Two", "Three" etc. When I select one list item, I want to show "n" buttons where "n" is the value selected.
Example :- If I select "Three" from the list, there should be 3 buttons in the JFrame.
Below is my code :-
public class Details extends JFrame {
String[] navData = new String{"One","Two","Three","Four"};
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Details frame = new Details();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Details() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
//frame.setSize(xSize,ySize);
setTitle("Test");
setBounds(0, 0, 776, 457);
setResizable(false);
//setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JList list = new JList(navData);
list.setBounds(0, 0, 140, ySize);
contentPane.add(list);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setFixedCellHeight(50);
list.setFixedCellWidth(70);
list.setBorder(new EmptyBorder(10,10, 10, 10));
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent arg0) {
int numButtons;
String selectedItem = navData[list.getSelectedIndex()];
switch (selectedItem) {
case "One":
addButtons(1);
break;
case "Two":
addButtons(2);
break;
case "Three":
addButtons(3);
break;
case "Four":
addButtons(4);
break;
default:
break;
}
}
});
list.setSelectedIndex(0);
}
public void addButtons(int n)
{
revalidate();
for(int i = 0; i<n;i++)
{
JButton button = new JButton(" "+navData[i]);
button.setBounds(200 + (i*50), 150, 50, 50);
contentPane.add(button);
}
}
}
- Problem :-
When I change the selected item in the list, the JPanel is not getting updated. In other words, I don't get 3 buttons when I select "Three" from the List. I get only 1 button which was created by the default selection.
I made these changes:
I put the JList in a JPanel, and the JButtons in another JPanel.
I used the FlowLayout for the JList JPanel, and the FlowLayout for the JButtons JPanel. You're free to change these Swing layouts if you wish.
I changed the default to 4 buttons, so the JFrame would pack properly for up to 4 JButtons.
I added a method to remove the JButtons from the JPanel before trying to add JButtons to the JPanel.
I revalidated and repainted the JButton JPanel.
Here's the code:
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Details extends JFrame {
private static final long serialVersionUID = -555805219508469709L;
private String[] navData = { "One", "Two", "Three", "Four" };
private JPanel buttonPanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Details frame = new Details();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Details() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setTitle("Test");
buttonPanel = new JPanel();
JPanel listPanel = new JPanel();
final JList<String> list = new JList<String>(navData);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setFixedCellHeight(50);
list.setFixedCellWidth(70);
list.setBorder(new EmptyBorder(10, 10, 10, 10));
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent event) {
String selectedItem = navData[list.getSelectedIndex()];
switch (selectedItem) {
case "One":
removeButtons(buttonPanel);
addButtons(buttonPanel, 1);
break;
case "Two":
removeButtons(buttonPanel);
addButtons(buttonPanel, 2);
break;
case "Three":
removeButtons(buttonPanel);
addButtons(buttonPanel, 3);
break;
case "Four":
removeButtons(buttonPanel);
addButtons(buttonPanel, 4);
break;
default:
break;
}
}
});
list.setSelectedIndex(3);
listPanel.add(list);
add(listPanel, BorderLayout.WEST);
add(buttonPanel, BorderLayout.CENTER);
pack();
}
public void removeButtons(JPanel panel) {
Component[] components = panel.getComponents();
for (int i = 0; i < components.length; i++) {
panel.remove(components[i]);
}
}
public void addButtons(JPanel panel, int n) {
for (int i = 0; i < n; i++) {
JButton button = new JButton(navData[i]);
panel.add(button);
}
panel.revalidate();
panel.repaint();
}
}
Replace contentPane.setLayout(null); with some kind of layout such as contentPane.setLayout(new GridBagLayout());
Add
contentPane.removeAll() as the first line in addButtons().
You can create a "wrapper" panel for buttons, i.e.
...
private JPanel buttonsWrapper;
...
// in the constructor
buttonsWrapper = new JPanel();
buttonsWrapper.setLayout(null);
buttonsWrapper.setBounds(200, 150, 200, 50);
buttonsWrapper.add(wrapperPanel);
and add buttons to this panel
public void addButtons(int n) {
buttonsWrapper.removeAll();
for(int i = 0; i < n; i++) {
JButton button = new JButton(" " + navData[i]);
button.setBounds((i*50), 0, 50, 50);
buttonsWrapper.add(button);
}
buttonsWrapper.revalidate();
buttonsWrapper.repaint();
}
Sorry if I'm double positing but I totally suck at Java.
I am trying to make my form have the ability to change dynamically if you select a radio button. The functions save, delete, new will remain the same but the contents of the body e.g. the UPC will change to ISBN of the novel and the other fields.
Is there a way to when you press Novel to load the items from Novel to replace Comic book items?
I tried to separate but I've hit a block and with my limited skills unsure what to do.
I just want it to be able to change it so that it works.
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.MenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Scanner;
public class FormFictionCatelogue extends JFrame implements ActionListener {
// Constants
// =========
private final String FORM_TITLE = "Fiction Adiction Catelogue";
private final int X_LOC = 400;
private final int Y_LOC = 80;
private final int WIDTH = 600;
private final int HEIGHT = 450;
private String gradeCode;
//final static String filename = "data/comicBookData.txt";
private JButton firstPageButton;
private JButton backPageButton;
private JButton forwardPageButton;
private JButton lastPageButton;
private JRadioButton comicBookRadioButton;
private JRadioButton novelRadioButton;
private final String FIRSTPAGE_BUTTON_TEXT = "|<";
private final String BACKPAGE_BUTTON_TEXT = "<";
private final String FORWARDPAGE_BUTTON_TEXT = ">";
private final String LASTPAGE_BUTTON_TEXT = ">|";
private final String COMICBOOK_BUTTON_TEXT = "Comic";
private final String NOVEL_BUTTON_TEXT = "Novel";
private final String SAVE_BUTTON_TEXT = "Save";
private final String EXIT_BUTTON_TEXT = "Exit";
private final String CLEAR_BUTTON_TEXT = "Clear";
private final String FIND_BUTTON_TEXT = "Find";
private final String DELETE_BUTTON_TEXT = "Delete";
private final String ADDPAGE_BUTTON_TEXT = "New";
// Attributes
private JTextField upcTextField;
private JTextField isbnTextField;
private JTextField titleTextField;
private JTextField issueNumTextField;
private JTextField bookNumTextField;
private JTextField writerTextField;
private JTextField authorTextField;
private JTextField artistTextField;
private JTextField publisherTextField;
private JTextField seriesTextField;
private JTextField otherBooksTextField;
private JTextField gradeCodeTextField;
private JTextField charactersTextField;
private JButton saveButton;
private JButton deleteButton;
private JButton findButton;
private JButton clearButton;
private JButton exitButton;
private JButton addPageButton;
FictionCatelogue fc;
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) {
try {
FormFictionCatelogue form = new FormFictionCatelogue();
form.fc = new FictionCatelogue();
form.setVisible(true);
//comicBook selected by default
form.populatefields(form.fc.returnComic(0));
//if novel is selected change fields to novel and populate
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
/**
*
*/
public FormFictionCatelogue() {
// Set form properties
// ===================
setTitle(FORM_TITLE);
setSize(WIDTH, HEIGHT);
setLocation(X_LOC, Y_LOC);
// Create and set components
// -------------------------
// Create panels to hold components
JPanel menuBarPanel = new JPanel();
JPanel fieldsPanel = new JPanel();
JPanel buttonsPanel = new JPanel();
JPanel navigationPanel = new JPanel();
//JPanel radioButtonsPanel = new JPanel();
ButtonGroup bG = new ButtonGroup();
// Set the layout of the panels
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
// Menu
JMenuBar menubar = new JMenuBar();
ImageIcon icon = new ImageIcon("exit.png");
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenu about = new JMenu("About");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit", icon);
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JMenuItem eMenuItem1 = new JMenuItem("Reports", icon);
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Reports are located here");
eMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
//calls reports
//System.exit(0);
}
});
file.add(eMenuItem);
about.add(eMenuItem1);
menubar.add(file);
menubar.add(about);
setJMenuBar(menubar);
setTitle("Menu");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//if comic is selected
ComicBookFields(fieldsPanel);
//else
//NovelFields(fieldsPanel);
// Buttons
comicBookRadioButton = new JRadioButton(COMICBOOK_BUTTON_TEXT);
novelRadioButton = new JRadioButton(NOVEL_BUTTON_TEXT);
bG.add(comicBookRadioButton);
bG.add(novelRadioButton);
this.setLayout(new FlowLayout());
this.add(comicBookRadioButton);
this.add(novelRadioButton);
comicBookRadioButton.setSelected(true);
bG.add(comicBookRadioButton);
bG.add(novelRadioButton);
addPageButton = new JButton(ADDPAGE_BUTTON_TEXT);
buttonsPanel.add(addPageButton);
saveButton = new JButton(SAVE_BUTTON_TEXT);
buttonsPanel.add(saveButton);
clearButton = new JButton(CLEAR_BUTTON_TEXT);
buttonsPanel.add(clearButton);
deleteButton = new JButton(DELETE_BUTTON_TEXT);
buttonsPanel.add(deleteButton);
findButton = new JButton(FIND_BUTTON_TEXT);
buttonsPanel.add(findButton);
exitButton = new JButton(EXIT_BUTTON_TEXT);
buttonsPanel.add(exitButton);
firstPageButton = new JButton(FIRSTPAGE_BUTTON_TEXT);
navigationPanel.add(firstPageButton);
backPageButton = new JButton(BACKPAGE_BUTTON_TEXT);
navigationPanel.add(backPageButton);
forwardPageButton = new JButton(FORWARDPAGE_BUTTON_TEXT);
navigationPanel.add(forwardPageButton);
lastPageButton = new JButton(LASTPAGE_BUTTON_TEXT);
navigationPanel.add(lastPageButton);
// Get the container holding the components of this class
Container con = getContentPane();
// Set layout of this class
con.setLayout(new BorderLayout());
con.setLayout( new FlowLayout());
// Add the fieldsPanel and buttonsPanel to this class.
// con.add(menuBarPanel, BorderLayout);
con.add(fieldsPanel, BorderLayout.CENTER);
con.add(buttonsPanel, BorderLayout.LINE_END);
con.add(navigationPanel, BorderLayout.SOUTH);
//con.add(radioButtonsPanel, BorderLayout.PAGE_START);
// Register listeners
// ==================
// Register action listeners on buttons
saveButton.addActionListener(this);
clearButton.addActionListener(this);
deleteButton.addActionListener(this);
findButton.addActionListener(this);
exitButton.addActionListener(this);
firstPageButton.addActionListener(this);
backPageButton.addActionListener(this);
forwardPageButton.addActionListener(this);
lastPageButton.addActionListener(this);
addPageButton.addActionListener(this);
comicBookRadioButton.addActionListener(this);
novelRadioButton.addActionListener(this);
// Exit program when window is closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void Radiobutton (){
this.add(comicBookRadioButton);
this.add(novelRadioButton);
comicBookRadioButton.setSelected(true);
this.setVisible(true);
}
// Populate the fields at the start of the application
public void populatefields(ComicBook cb) {
String gradecode;
// radio button selection = comic do this
if (cb != null) {
upcTextField.setText(cb.getUpc());
titleTextField.setText(cb.getTitle());
issueNumTextField.setText(Integer.toString(cb.getIssuenumber()));
writerTextField.setText(cb.getWriter());
artistTextField.setText(cb.getArtist());
publisherTextField.setText(cb.getPublisher());
gradecode = cb.getGradeCode();
gradeCodeTextField.setText(cb.determineCondition(gradecode));
charactersTextField.setText(cb.getCharacters());
}
//radio button selection = novel do this
// Exit program when window is closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
/**
*
*/
public void actionPerformed(ActionEvent ae) {
try {
if(ae.getActionCommand().equals(COMICBOOK_BUTTON_TEXT)){
//FormFictionCatelogue form = new FormFictionCatelogue();
//form.populatefields(form.fc.returnObject(0));
//ComicBookFields(fieldsPanel);
populatefields(fc.returnComic(0));
} else if (ae.getActionCommand().equals(NOVEL_BUTTON_TEXT)) {
} else if (ae.getActionCommand().equals(SAVE_BUTTON_TEXT)) {
save();
} else if (ae.getActionCommand().equals(CLEAR_BUTTON_TEXT)) {
clear();
} else if (ae.getActionCommand().equals(ADDPAGE_BUTTON_TEXT)) {
add();
} else if (ae.getActionCommand().equals(DELETE_BUTTON_TEXT)) {
delete();
} else if (ae.getActionCommand().equals(FIND_BUTTON_TEXT)) {
find();
} else if (ae.getActionCommand().equals(EXIT_BUTTON_TEXT)) {
exit();
} else if (ae.getActionCommand().equals(FIRSTPAGE_BUTTON_TEXT)) {
// first record
populatefields(fc.firstRecord());
} else if (ae.getActionCommand().equals(FORWARDPAGE_BUTTON_TEXT)) {
// next record
populatefields(fc.nextRecord());
} else if (ae.getActionCommand().equals(BACKPAGE_BUTTON_TEXT)) {
// previous record
populatefields(fc.previousRecord());
} else if (ae.getActionCommand().equals(LASTPAGE_BUTTON_TEXT)) {
// last record
populatefields(fc.lastRecord());
} else {
throw new Exception("Unknown event!");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage(), "Error!",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
void clear() {
upcTextField.setText("");
titleTextField.setText("");
issueNumTextField.setText("");
writerTextField.setText("");
artistTextField.setText("");
gradeCodeTextField.setText("");
publisherTextField.setText("");
charactersTextField.setText("");
}
private void exit() {
System.exit(0);
}
void add() {
try{
clear();
ComicBook cb = new ComicBook();
fc.add(cb);
fc.lastRecord();
} catch (Exception e){
e.printStackTrace();
}
}
void save() throws Exception {
// if radio button = comic do this
ComicBook cb = new ComicBook();
String condition;
if (upcTextField.getText().length() == 16) {
//searches if there is another record if()
cb.setUpc(upcTextField.getText());
} else {
throw new Exception("Upc is not at required length ");
}
cb.setTitle(titleTextField.getText());
cb.setIssuenumber(Integer.parseInt(issueNumTextField.getText()));
cb.setWriter(writerTextField.getText());
cb.setArtist(artistTextField.getText());
cb.setPublisher(publisherTextField.getText());
condition = cb.determineString(gradeCodeTextField.getText());
if (condition.equals("Wrong Input")) {
throw new Exception("Grade code is not valid");
} else {
cb.setGradeCode(condition);
}
cb.setCharacters(charactersTextField.getText());
fc.save(cb);
// if radio button = novels do this
}
private void delete() throws Exception {
fc.delete();
populatefields(fc.getCurrentRecord());
}
private void find() {
// from
// http://www.roseindia.net/java/example/java/swing/ShowInputDialog.shtml
String str = JOptionPane.showInputDialog(null, "Enter some text : ",
"Comic Book Search", 1);
if (str != null) {
ComicBook cb = new ComicBook();
cb = fc.search(str);
if (cb != null) {
populatefields(cb);
} else {
JOptionPane.showMessageDialog(null, "No comic books found ",
"Comic Book Search", 1);
}
}
}
public JPanel ComicBookFields(JPanel fieldsPanel) {
// Create components and add to panels for ComicBook
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
fieldsPanel.setLayout(fieldsPanelLayout);
fieldsPanel.add(new JLabel("UPC: "));
upcTextField = new JTextField(20);
fieldsPanel.add(upcTextField);
fieldsPanel.add(new JLabel("Title: "));
titleTextField = new JTextField(20);
fieldsPanel.add(titleTextField);
fieldsPanel.add(new JLabel("Issue Number: "));
issueNumTextField = new JTextField(20);
fieldsPanel.add(issueNumTextField);
fieldsPanel.add(new JLabel("Writer: "));
writerTextField = new JTextField(20);
fieldsPanel.add(writerTextField);
fieldsPanel.add(new JLabel("Artist: "));
artistTextField = new JTextField(20);
fieldsPanel.add(artistTextField);
fieldsPanel.add(new JLabel("Publisher: "));
publisherTextField = new JTextField(20);
fieldsPanel.add(publisherTextField);
fieldsPanel.add(new JLabel("Grade Code: "));
gradeCodeTextField = new JTextField(20);
fieldsPanel.add(gradeCodeTextField);
fieldsPanel.add(new JLabel("Characters"));
charactersTextField = new JTextField(20);
fieldsPanel.add(charactersTextField);
return fieldsPanel;
}
public JPanel NovelFields(JPanel fieldsPanel) {
// Create components and add to panels for ComicBook
GridLayout fieldsPanelLayout = new GridLayout(9, 6);
fieldsPanel.setLayout(fieldsPanelLayout);
fieldsPanel.add(new JLabel("ISBN: "));
isbnTextField = new JTextField(20);
fieldsPanel.add(isbnTextField);
fieldsPanel.add(new JLabel("Title: "));
titleTextField = new JTextField(20);
fieldsPanel.add(titleTextField);
fieldsPanel.add(new JLabel("Book Number: "));
bookNumTextField = new JTextField(20);
fieldsPanel.add(bookNumTextField);
fieldsPanel.add(new JLabel("Author: "));
authorTextField = new JTextField(20);
fieldsPanel.add(authorTextField);
fieldsPanel.add(new JLabel("Publisher: "));
publisherTextField = new JTextField(20);
fieldsPanel.add(publisherTextField);
fieldsPanel.add(new JLabel("Series: "));
seriesTextField = new JTextField(20);
fieldsPanel.add(seriesTextField);
fieldsPanel.add(new JLabel("Other Books"));
otherBooksTextField = new JTextField(20);
fieldsPanel.add(otherBooksTextField);
return fieldsPanel;
}
}
To swap forms you can use a CardLayout.
Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
The example from the tutorial switches when you make a selection from a combo box. In your case you would change the panel when you click on the radio button. So you might also want to read the section from the tutorial on How to Use Buttons.
Otherwise you can switch JPanels on JRadioButton selection like this:
You've got a JPanel called displayPanel which contains the ComicPanel by default, if you select the Novel RadioButton the displayPanel gets cleared and the NovelPanel will be added.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class AddNovelOrComicPanel extends JPanel implements ActionListener {
private JPanel selectPanel;
private JPanel displayPanel;
private JPanel buttonPanel;
private JRadioButton comic;
private JRadioButton novel;
// we need this ButtonGroup to take care about unselecting the former selected JRadioButton
ButtonGroup radioButtons;
public AddNovelOrComicPanel() {
this.setLayout(new BorderLayout());
initComponents();
this.add(selectPanel, BorderLayout.NORTH);
this.add(displayPanel, BorderLayout.CENTER);
}
/**
* Initializes all Components
*/
private void initComponents() {
selectPanel = new JPanel(new GridLayout(1, 2));
comic = new JRadioButton("Comic");
comic.setSelected(true);
comic.addActionListener(this);
novel = new JRadioButton("Novel");
novel.addActionListener(this);
radioButtons = new ButtonGroup();
radioButtons.add(comic);
radioButtons.add(novel);
selectPanel.add(comic);
selectPanel.add(novel);
displayPanel = new JPanel();
displayPanel.add(new ComicPanel());
}
#Override
public void actionPerformed(ActionEvent e) {
// if comic is selected show the ComicPanel in the displayPanel
if(e.getSource().equals(comic)) {
displayPanel.removeAll();
displayPanel.add(new ComicPanel());
}
// if novel is selected show the NovelPanel in the displayPanel
if(e.getSource().equals(novel)) {
displayPanel.removeAll();
displayPanel.add(new NovelPanel());
}
// revalidate all to show the changes
revalidate();
}
}
/**
* The NovelPanel class
* it contains all the Items you need to register a new Novel
*/
class NovelPanel extends JPanel {
public NovelPanel() {
this.add(new JLabel("Add your Novel components here"));
}
}
/**
* The ComicPanel class
*/
class ComicPanel extends JPanel {
public ComicPanel() {
this.add(new JLabel("Add your Comic components here"));
}
}
So it is your choice what you want to do. Possible is nearly everything ;)
Patrick
i modified my code but still faced problem ,i want to MyPanel2 inside open to MyPanel by clicking button , how do i do that , here is my code given which is pop open after clicking button of Myplanel..
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.jpedal.PdfDecoder;
import org.jpedal.examples.viewer.Viewer;
import org.jpedal.gui.GUIFactory;
import org.jpedal.utils.LogWriter;
public class Button extends Viewer {
private MyPanel panel1;
private MyPanel2 panel2;
private void displayGUI() {
JFrame frame = new JFrame("eBookReader Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
contentPane.add(panel1, "Panel 1");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Button().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JButton jcomp4;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
jcomp4 = new JButton("openNewWindow");
// adjust size and set layout
setPreferredSize(new Dimension(315, 85));
setLayout(null);
jcomp4.setLocation(0, 0);
jcomp4.setSize(315, 25);
jcomp4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception e1) {
LogWriter.writeLog("Exception " + e1
+ " setting look and feel");
}
MyPanel2 a = new MyPanel2();
a.setupViewer();
}
});
add(jcomp4);
}
}
class MyPanel2 extends Viewer {
public MyPanel2() {
// tell user we are in multipanel display
currentGUI.setDisplayMode(GUIFactory.MULTIPAGE);
// enable error messages which are OFF by default
PdfDecoder.showErrorMessages = true;
}
public MyPanel2(int modeOfOperation) {
// tell user we are in multipanel display
currentGUI.setDisplayMode(GUIFactory.MULTIPAGE);
// enable error messages which are OFF by default
PdfDecoder.showErrorMessages = true;
commonValues.setModeOfOperation(modeOfOperation);
}
}
private void displayGUI() {
JFrame frame = new JFrame("eBookReader Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
panel1 = new MyPanel(contentPane);
contentPane.add(panel1, "Panel 1");
frame.setContentPane(contentPane);
// we need to increase the size of the panel so when we switch views we can see the viewer
frame.setPreferredSize(new Dimension(2000, 700));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
Now in the button event handler
jcomp4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception e1) {
LogWriter.writeLog("Exception " + e1
+ " setting look and feel");
}
MyPanel2 a = new MyPanel2();
// inform the viewer of where it is to be displayed
a.setRootContainer(contentPane);
// hide the curently visible panel
MyPanel.this.setVisible(false);
// show the viewer
a.setupViewer();
}
});