Switching between JPanels in different classes - java

I've stumbled upon this complications and have spent more than 4 hours debugging and googling but to no avail..
Basically what I have here is 1 JFrame, 2 JPanels.
I had my JFrame setContentPane to 1 of the JPanel, and when I run the Application, the JFrame will appear with the JPanel inside.
Now this JPanel have 1 JButton inside it, when I click it I want it to switch to another JPanel. As you can see from the code, when I click the JButton(Add Product), I want the OnlineShopAdPane to switch to AddProduct. I tried using CardLayout but it only has NSEW formatting.
package OnlineShop.ui;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class OnlineShopMainFrame extends JFrame {
/**
* Launch the application.
*/
AddProduct Add;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
OnlineShopMainFrame MainFrame = new OnlineShopMainFrame();
MainFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public OnlineShopMainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
OnlineShopAdPane AdPanel = new OnlineShopAdPane();
setContentPane(AdPanel);
}
}
package OnlineShop.ui;
import javax.swing.JPanel;
import java.awt.CardLayout;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
public class OnlineShopAdPane extends JPanel {
/**
* Create the panel.
*/
public OnlineShopAdPane() {
JLabel lblWhatDoYou = new JLabel("What do you want to do?");
lblWhatDoYou.setBounds(28, 26, 160, 26);
add(lblWhatDoYou);
JButton btnAddProduct = new JButton("Add Product");
btnAddProduct.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
OnlineShopMainFrame MainFrame = new OnlineShopMainFrame();
MainFrame.removeAll();
MainFrame.add(new AddProduct());
MainFrame.revalidate();
MainFrame.repaint();
}
});
btnAddProduct.setBounds(46, 75, 115, 23);
add(btnAddProduct);
}
}
package OnlineShop.ui;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddProduct extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public AddProduct() {
JLabel lblProductName = new JLabel("Product Name:");
lblProductName.setBounds(35, 26, 77, 24);
add(lblProductName);
JLabel lblProductDescription = new JLabel("Product Description:");
lblProductDescription.setBounds(10, 50, 106, 24);
add(lblProductDescription);
textField = new JTextField();
textField.setBounds(116, 28, 141, 20);
add(textField);
textField.setColumns(10);
JTextArea textArea = new JTextArea();
textArea.setBounds(116, 66, 141, 112);
add(textArea);
JButton btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnClose.setBounds(223, 244, 89, 23);
add(btnClose);
}
}

I tried using CardLayout but it only has NSEW formatting.
What does that mean? A CardLayout simply contains two or more panels. Only one panel is visible at a time. Each panel can use whatever layout it wants to layout the components on the panel.
when I click it I want it to switch to another JPanel.
That is exactly what CardLayout does. See the Swing tutorial on How to Use Card Layout for a working example and explanation.
Whenever I see code like remove/add/revalidate/repaint it should almost always be replaced with a CardLayout

I think that with CardLayout you can resolve it, but another way is using for example a Handler to switch your panels.
private JComponent container; // this could be your Frame
private JComponent loadedComponent;
public void loadContent(JComponent component, Object object ) {
if (loadedComponent != null) {
loadedComponent.setVisible(false);
container.remove(loadedComponent);
loadedComponent = null;
}
//TODO may check layout
container.add(component,object);
component.setVisible(true);
loadedComponent = component;
container.validate();
}

The problem is pobably located at the following lines in class OnlineShopAdPane.java
OnlineShopMainFrame MainFrame = new OnlineShopMainFrame();
MainFrame.removeAll();
MainFrame.add(new AddProduct());
MainFrame.revalidate();
MainFrame.repaint();
your not referring to the frame where your JPanel is nested. instead your creating a new OnlineShopMainFrame

Related

JFrame loading glitch

Can someone help me with my code, please. I am expiriencing strange behaviour in Eclipse.
Sometimes my application loads correctly and most of times I don't get North and South JPanels loaded properly or not loaded at all.
After loading GUI displays correctly only when I resize JFrame borders, but I would like to load every time correctly. I guess I have some trouble in my code but I can't find it. And btw, I am running Linux Mint 19.1 Tarra with java-11-openjdk-amd64.
Here is code for Main class:
package gui;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
new Dakijevstina();
}
}
And here is GUI class code:
package gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Image;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
#SuppressWarnings("serial")
public class Dakijevstina extends JFrame{
Font font = new Font("TimesNew Roman", Font.PLAIN, 12);
public Dakijevstina() {
initComponents();
}
public void initComponents() {
//setting up JFrame
setTitle("Market garden financial software");
setFont(font);
setLayout(new BorderLayout());
setSize(640, 480);
setDefaultCloseOperation(Dakijevstina.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setVisible(true);
//setting up North JPanel
JPanel pnlNorth = new JPanel(new FlowLayout(FlowLayout.LEFT));
pnlNorth.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(pnlNorth, BorderLayout.NORTH);
//setting up StatusBar
JPanel pnlSouth = new JPanel(new FlowLayout(FlowLayout.LEFT));
pnlSouth.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(pnlSouth, BorderLayout.SOUTH);
//adding buttons to north JPanel
//About
JButton btnAbout = new JButton();
JButton btnExit = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("/images/about.png"));
Image img2 = ImageIO.read(getClass().getResource("/images/exit.png"));
btnAbout.setIcon(new ImageIcon(img));
btnExit.setIcon(new ImageIcon(img2));
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex);
}
btnAbout.setPreferredSize(new Dimension(40, 40));
btnAbout.setMinimumSize(new Dimension(40, 40));
btnAbout.setToolTipText("Information about author");
btnExit.setPreferredSize(new Dimension(40, 40));
btnExit.setMinimumSize(new Dimension(40, 40));
btnExit.setToolTipText("Exit application");
btnExit.addActionListener(e -> exitApp());
pnlNorth.add(btnAbout);
pnlNorth.add(btnExit);
//adding StatusBar to south JPanel
JLabel status = new JLabel("Welcome to Dakijevstina software");
status.setFont(font);
pnlSouth.add(status);
}
//event handlers
public void exitApp() {
this.dispose();
}
This is what I get most of time:
unwanted behaviour
And this is how it supose to be:
this is what I want

JButton does not open JDialog

I am building a simple program. I have a class that extends from JDialog and class that extends from JFrame and is GUI of the application. I implemented ActionListener which should open the dialog after clicking on the JButton. Nothing happens though and I can't figure out why.
GUI
package nemocnice_sam;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class App extends JFrame {
JTable tbl = new JTable();
JButton pridejPacienta = new JButton("Přidej pacienta");
JButton smazPacienta = new JButton("Smaž pacienta");
JButton export = new JButton("Export");
JButton konec = new JButton("Konec");
JPanel panel = new JPanel();
PacientDialog novyPacient;
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == pridejPacienta){
novyPacient = new PacientDialog();
novyPacient.setModal(true);
novyPacient.setVisible(true);
}
}
};
SeznamPacientu pacienti = new SeznamPacientu();
ModelPacientu model = new ModelPacientu(pacienti);
public static void main(String[] args) {
new App();
}
public App() {
setLayout(new BorderLayout());
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.add(pridejPacienta);
panel.add(smazPacienta);
panel.add(export);
panel.add(konec);
add(panel,BorderLayout.NORTH);
tbl.setModel(model);
add(new JScrollPane(tbl), BorderLayout.CENTER);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
}
DIALOG CLASS
package nemocnice_sam;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class PacientDialog extends JDialog {
JTextField jmeno = new JTextField();
JTextField prijmeni = new JTextField();
JTextField rc = new JTextField();
JTextField cp = new JTextField();
JButton ok = new JButton("OK");
public PacientDialog(){
setLayout(new GridLayout(5,2));
add(new JLabel("Jméno:"));
add(jmeno);
add(new JLabel("Příjmení:"));
add(prijmeni);
add(new JLabel("RČ:"));
add(rc);
add(new JLabel("ČP:"));
add(cp);
pack();
}
}
You need to define the actionListener in button.
konec.addActionListener(al);
Defining an ActionListener alone is not sufficient.
In order to do its job, that listener must be registered with some component that actually sends Events to that Listener.
So you have it to add to the corresponding button for example, like:
pridejPacienta.addActionListener(al);
Besides: when you do that, you do not need that if (source == check within your action listener. You see, when each button has a distinct listener, then there will not be different sources.
You only need such kinds of checks when you want to attach the same ActionListener to multiple buttons!

Two JPanels on top of each other with horizontal scrolls [duplicate]

I have this interface to create. I have a problem with the JScrollPane:
I declared a JPanel with a Gridlayout(8,1,0,2), I want 8 rows appear in this panel.
A row is a JPanel to, I set the size to make the 8 row panels appear in the big panel.
If the number of rows pass 8, I get two columns ...
I added a JScrollPane but it doesn't appear.
Testing button at the place of button, the scrollpane appear but returning to panel it disappear..
How can I do ??
I found a solution:
package d06.m03;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.BoxLayout;
public class ActionExample4 extends JFrame {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ActionExample4 frame = new ActionExample4();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ActionExample4() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 778, 426);
getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 101, 742, 276);
//scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
getContentPane().add(scrollPane);
JPanel borderlaoutpanel = new JPanel();
scrollPane.setViewportView(borderlaoutpanel);
borderlaoutpanel.setLayout(new BorderLayout(0, 0));
JPanel columnpanel = new JPanel();
borderlaoutpanel.add(columnpanel, BorderLayout.NORTH);
columnpanel.setLayout(new GridLayout(0, 1, 0, 1));
columnpanel.setBackground(Color.gray);
for(int i=0;i<32;i++) {
JPanel rowPanel = new JPanel();
rowPanel.setPreferredSize(new Dimension(300,30));
columnpanel.add(rowPanel);
rowPanel.setLayout(null);
JButton button = new JButton("New button");
button.setBounds(20, 5, 89, 23);
rowPanel.add(button);
if(i%2==0)
rowPanel.setBackground(SystemColor.inactiveCaptionBorder);
}
}
}

How can we put value on text field on output screen?

I want to put value in txtf1 at output screen and get it. How can we put value on text field on output screen?
import java.awt.Color;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class demog extends JPanel implements ActionListener{
private TextField textf, txtf1;
public void jhand(){
textf = new TextField();
textf.setSize(40, 40);
textf.setText("20");
textf.setEditable(false);
textf.setBackground(Color.WHITE);
textf.setForeground(Color.BLACK);
//textf.setHorizontalAlignment(SwingConstants.CENTER);
textf.setLocation(15, 15);
//textf.addActionListener(this);
txtf1 = new TextField();
txtf1.setSize(40, 40);
txtf1.getText();
txtf1.setEditable(false);
txtf1.setBackground(Color.WHITE);
txtf1.setForeground(Color.BLACK);
//txtf1.setHorizontalAlignment(SwingConstants.CENTER);
txtf1.setLocation(50, 50);
JFrame frame = new JFrame("demo");
JPanel p = new JPanel();
p.setOpaque(true);
p.setBackground(Color.WHITE);
p.setLayout(null);
frame.setContentPane(p);
frame.setSize(500,500);
frame.setVisible(true);
p.add(textf);
p.add(txtf1);
}
public void actionPerformed(ActionEvent evt) {
String text = textf.getText();
System.out.println(text);
}
public static void main(String... args){
demog g = new demog();
g.jhand();
}
}
You have to change some of your code in order to work. You had some problem in your code which I resolved them for you in the following code. See the comments to learn some in swing ;-)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
// Use upper Case in the start of you class names:
public class Demog extends JPanel implements ActionListener {
private JTextField textf, txtf1;
public Demog() {
jhand();
}
public void jhand() {
setLayout(new FlowLayout()); // Always set the layout before you add components
// you can use null layout, but you have to use setBounds() method
// for placing the components. For an advanced layout see the
// tutorials for GridBagLayout and mixing layouts with each other.
textf = new JTextField(); // Do not mix AWT component with
// Swing (J components. See the packages)
//textf.setSize(40, 40); // Use setPreferredSize instead
textf.setPreferredSize(new Dimension(40, 40));
textf.setText("20");
textf.setEditable(false); // Text fields are for getting data from user
// If you need to show something to user
// use JLabel instead.
textf.setBackground(Color.WHITE);
textf.setForeground(Color.BLACK);
add(textf);
txtf1 = new JTextField();
//txtf1.setSize(40, 40); Use setPreferredSize instead
txtf1.setPreferredSize(new Dimension(40, 40));
txtf1.getText();
txtf1.setEditable(false);
txtf1.setBackground(Color.WHITE);
txtf1.setForeground(Color.BLACK);
add(txtf1);
JButton b = new JButton("Click ME!");
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent evt) {
String text = textf.getText();
JOptionPane.showMessageDialog(Demog.this, "\"textf\" text is: "+text);
}
public static void main(String[] args) {
JFrame frame = new JFrame("demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Demog p = new Demog();
p.setBackground(Color.WHITE);
frame.setContentPane(p);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
Good Luck.

Hide a JButton (image) after click

I've create a program with a JButton(image) and a normal image, now if you click the normal button a image will show, now i have program that the JButton(image) will hide if you click the normal button but i dont work and i get a fault code
package View;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
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.JPanel;
import Controller.HideController;
import Controller.HomeController;
import Controller.SelectieController;
public class Selectie extends JFrame{
private static String Vermeer = "Vermeer";
private JLabel label, label1, label2;
private JButton keeper, kruis;
private JPanel panel;
private Container window = getContentPane();
public Selectie()
{
initGUI();
}
public void initGUI()
{
setLayout(null);
setTitle("Jari");
setSize(800,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setBounds(0, 0, 266, 800);
label.setBackground(Color.RED);
label.setOpaque(true);
window.add(label);
label1 = new JLabel();
label1.setBounds(266, 0, 266, 800);
label1.setBackground(Color.BLACK);
label1.setOpaque(true);
window.add(label1);
label2 = new JLabel();
label2.setBounds(532, 0, 266, 800);
label2.setBackground(Color.RED);
label2.setOpaque(true);
window.add(label2);
JLabel foto = new JLabel();
label1.add(foto);
kruis = new JButton(new ImageIcon("../Ajax/src/img/logotje.gif"));
kruis.setBorderPainted(false);
kruis.setBounds(40, 150, 188, 188);
label1.add(kruis);
keeper = new JButton("1. "+""+" Kenneth Vermeer");
Cursor cur = keeper.getCursor();
keeper.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
keeper.setBounds(20, 50, 186, 12);
keeper.setFocusable(false);
keeper.setBorderPainted(false);
keeper.setContentAreaFilled(false);
keeper.setFont(new Font("Arial",Font.PLAIN,17));
keeper.setForeground(Color.WHITE);
keeper.setActionCommand(Vermeer);
label.add(keeper);
SelectieController s1 = new SelectieController(keeper);
keeper.addActionListener(s1);
}
HideController h1 = new HideController(keeper, kruis);
{
keeper.addActionListener(h1);
}
}
The action listener class:
package Controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
public class HideController implements ActionListener {
private JButton keeper, logo;
private static String Vermeer = "Vermeer";
public HideController(JButton vermeer, JButton kruis)
{
keeper = vermeer;
logo = kruis;
//Kenneth Vermeer
try
{
keeper.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
logo.setVisible(false);
}
public void actionPerformed(ActionEvent event)
{
String actionCommand = event.getActionCommand();
// Kenneth Vermeer
if (Vermeer.equals(actionCommand))
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
logo.setVisible(false);
}
});
}
}}
I hope someone could help me, thanks
If you want the button gone you can use window.remove(keeper). If you want no image but still want the button to be there, you can try logo = null, which will set the icon on logo to nothing, leaving you with a white box. If you are coding on Windows, you can add a background color with keeper.setBackgroundColor(Color.Blue) or whatever color your background is, however the Mac OS's look and feel will not allow this for some reason. (you can change the look and feel with, but that is fairly complicated) If you have a more complex background i would suggest taking a sample from the right point with a screenshot (with the button commented out in the code) and setting logo to that image.

Categories