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

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);
}
}
}

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

JTextPane - get component values

I have JTextPane, where are inserted 2 JLabels. If any of the labels are clicked, they change content from AAA to clicked.
This code iterates over the elements in the JTextPane:
for(int i = 0; i < tp.getDocument().getLength(); i++) {
System.out.println(((StyledDocument) tp.getDocument()).getCharacterElement(i));
}
How can I access the labels to print "clicked" "AAAA" to the std out?
package texteditor;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
import javax.swing.JButton;
public class JTextPaneExample extends JPanel {
private JTextPane tp;
public JTextPaneExample() {
setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Text Content", TitledBorder.LEADING, TitledBorder.TOP, null, null));
add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane, BorderLayout.CENTER);
tp = new JTextPane();
tp.setEditable(false);
scrollPane.setViewportView(tp);
JLabel lbl = new JLabel("AAAA ");
lbl.setOpaque(true);
lbl.setBorder(BorderFactory.createLineBorder(Color.black, 1));
lbl.addMouseListener(new LabelAdapter2(lbl));
tp.insertComponent(lbl);
lbl = new JLabel("BBBB ");
lbl.setOpaque(true);
lbl.setBorder(BorderFactory.createLineBorder(Color.black, 1));
lbl.addMouseListener(new LabelAdapter2(lbl));
tp.insertComponent(lbl);
JButton btnNewButton = new JButton("Write content");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
iterateOverContent(tp);
}
});
panel.add(btnNewButton, BorderLayout.SOUTH);
}
private void iterateOverContent(JTextPane tp2) {
for(int i = 0; i < tp.getDocument().getLength(); i++) {
System.out.println(((StyledDocument) tp.getDocument()).getCharacterElement(i));
}
}
private class LabelAdapter2 extends MouseAdapter {
private JLabel lblNewLabel;
public LabelAdapter2(JLabel lbl) {
this.lblNewLabel = lbl;
}
public void mouseClicked(MouseEvent evt) {
lblNewLabel.setText("clicked");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("GoBoard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JTextPaneExample());
frame.setPreferredSize(new Dimension(400, 400));
frame.pack();
frame.setVisible(true);
}
}
i looked into your Question and found a Solution:
just replace your method to iterate the elements of the TextPane with this:
private void iterateOverContent(JTextPane tp2) {
for(int i = 0; i < tp.getDocument().getLength(); i++) {
Element elem = ((StyledDocument) tp.getDocument()).getCharacterElement(i);
AttributeSet as = elem.getAttributes();
if (as.containsAttribute(AbstractDocument.ElementNameAttribute, StyleConstants.ComponentElementName)) {
if(StyleConstants.getComponent(as) instanceof JLabel) {
JLabel myLabel = (JLabel)StyleConstants.getComponent(as);
System.out.println(myLabel.getText());
}
}
System.out.println(((StyledDocument) tp.getDocument()).getCharacterElement(i));
}
}
as you can see, i first save the element into a new variable and then read out all the attributes (yes, the code could be alot shorter, but this way it is more clear - i hope :-) )
After that, we check if the attributes say, that this element is a component.
then the important part: we can get a Component from the attribute set via the StyleConstants.getComponent Method.
Finally just some sanity checks, to see if we can really typecast it to a JLabel.
Best regards,
David

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.

JScrollPane doesn't work/show scroll Bars

I have a JFrame, that contains a JPanel, which contains a JScrollPane, that contains another JPanel, with two components (JPanels).
For some reason, when I use WindowBuilder's preview option to see the frame, the JScrollPane shows the horizontal scroll bar, but when I compile and run the app, it doesn't.
Here is what it looks like:
from preview option:
When it's compiled:
Here is my code:
package home;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.SystemColor;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Component;
import java.awt.BorderLayout;
import java.awt.Frame;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.Font;
import javax.swing.BoxLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Color;
import java.awt.Dimension;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.ScrollPaneConstants;
public class AtmManeger implements Serializable {
private JFrame frmAtmManeger;
public int NumOfOpenAtmMachines = 0;
private final AtmManeger frame = this;
private ArrayList<ATMmachine> ATMs = new ArrayList<ATMmachine>();//Array list of all the ATM machines that were opened
private AtmAccountDataBase atmDataBase = new AtmAccountDataBase();
private JLabel contLabel = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AtmManeger window = new AtmManeger();
window.frmAtmManeger.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AtmManeger getFrame() {
return this.frame;
}
public AtmManeger() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
frmAtmManeger = new JFrame();
frmAtmManeger.setMinimumSize(new Dimension(615, 420));
frmAtmManeger.getContentPane().setBackground(SystemColor.activeCaption);
JPanel mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(10, 10));
frmAtmManeger.setContentPane(mainPanel);
JScrollPane scrollPane = new JScrollPane();
mainPanel.add(scrollPane, BorderLayout.CENTER);
JPanel subPanel = new JPanel();
subPanel.setSize(new Dimension(1190, 350));
subPanel.setBackground(SystemColor.activeCaption);
subPanel.setPreferredSize(new Dimension(1190, 350));
scrollPane.setViewportView(subPanel);
subPanel.setLayout(new MigLayout("", "[50.00%,grow][50.00%,grow]", "[grow]"));
JPanel panel = new JPanel();
subPanel.add(panel,"cell 0 0,grow");
panel.setBorder(null);
panel.setBackground(SystemColor.textHighlight);
panel.setLayout(new MigLayout("", "[100.00%,grow]", "[71px][13.54%][10.09%][41px][][grow]"));
JPanel panel_1 = new JPanel();
subPanel.add(panel_1, "cell 1 0,grow");
frmAtmManeger.setTitle("ATM Maneger");
frmAtmManeger.setBounds(700, 400, 609, 420);
frmAtmManeger.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I made another app very similar to this one, only that one inherents JFrame. I couldn't find any difference between this code and the one above. code:
package home;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import java.awt.Color;
import java.awt.FlowLayout;
import net.miginfocom.swing.MigLayout;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JButton;
public class test02 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test02 frame = new test02();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public test02() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// Handle exception
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 432, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(800, 220));
panel.setBackground(Color.RED);
scrollPane.setViewportView(panel);
panel.setLayout(new MigLayout("", "[50.00%,grow][50.00%,grow]", "[grow]"));
JPanel panel_1 = new JPanel();
panel.add(panel_1, "cell 0 0,grow");
panel_1.setLayout(new MigLayout("", "[][][][][][][]", "[][][][][][]"));
JLabel lblNewLabel = new JLabel("New label");
panel_1.add(lblNewLabel, "cell 2 1");
JButton btnNewButton_1 = new JButton("New button");
panel_1.add(btnNewButton_1, "cell 3 3");
JButton btnNewButton = new JButton("New button");
panel_1.add(btnNewButton, "cell 2 5");
JLabel lblNewLabel_1 = new JLabel("New label");
panel_1.add(lblNewLabel_1, "cell 6 5");
JPanel panel_2 = new JPanel();
panel.add(panel_2, "cell 1 0,grow");
}
}
So it's probably just a silly mistake, but what is it?
I don't see you changing the scrollbar policy.
Since there is no overflow, without changing that setting, you will not see the scrollbar appear.
try:
scrollbar.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
I have written a program to display panels as per the requirements.
Code:
private void createUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JScrollPane pane = new JScrollPane();
JPanel leftPnl = new JPanel(new BorderLayout());
JPanel rightPnl = new JPanel(new BorderLayout());
leftPnl.add(new JLabel("Left"), BorderLayout.CENTER);
leftPnl.setBorder(new LineBorder(Color.black, 5));
leftPnl.setPreferredSize(new Dimension(400, 400));
rightPnl.add(new JLabel("Right"), BorderLayout.CENTER);
rightPnl.setBorder(new LineBorder(Color.black, 5));
rightPnl.setPreferredSize(new Dimension(400, 400));
panel.add(leftPnl);
panel.add(rightPnl);
panel.add(pane);
frame.setPreferredSize(new Dimension(400, 400));
frame.setTitle("ScrollPane Example");
frame.add(new JScrollPane(panel));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Switching between JPanels in different classes

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

Categories