cannot add dynamic jtextfields and save their values - java

In previos my questions I asked similar questions to this. But in my previous projects I used GUI builder, so now I would like to add JTextField to the Panel dynamically without Builder. I don't why but for some reason I cannot execute this code:
public class Reference {
JFrame frame = new JFrame();
JPanel MainPanel = new JPanel();
MainPanel main = new MainPanel();
JPanel SubPanel = new JPanel();
JButton addButton = new JButton();
JButton saveButton = new JButton();
private List<JTextField> listTf = new ArrayList<JTextField>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new Reference();
}
public Reference() {
frame.add(main);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(addButton, BorderLayout.EAST);
frame.add(saveButton, BorderLayout.WEST);
frame.pack();
frame.setSize(500, 300);
frame.setVisible(true);
main.setLayout(new BorderLayout());
main.setBackground(Color.green);
main.add(SubPanel);
SubPanel.setBackground(Color.yellow);
addButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
main.add(new SubPanel());
main.revalidate();
}
});
saveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
for (int i = 0; i < main.getComponentCount();) {
SubPanel panel = (SubPanel)main.getComponent(i);
JTextField firstName = panel.getFirstName();
String text = firstName.getText();
System.out.println( text );
}}
});
}
private class SubPanel extends JPanel {
JTextField firstName = new JTextField(15);
public SubPanel() {
this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
this.add(firstName);
listTf.add(firstName);
}
public JTextField getFirstName()
{
return firstName;
}
}
public class MainPanel extends JPanel
{
List<SubPanel> subPanels = new ArrayList<SubPanel>();
public MainPanel()
{
}
public void addSubPanel()
{
SubPanel panel = new SubPanel();
add(panel);
subPanels.add(panel);
}
public SubPanel getSubPanel(int index)
{
return subPanels.get(index);
}
}
}
And by saveButton trying to get value of JTextField, but without success. In output I can see just JFrame with 2 Buttons, but ActionListener of addButton and saveButton is not active. I cannot understand where is wrong.
Any help would be much appreciated.

In Swing, the order you do some things is very important, for example...
frame.add(main);
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(addButton, BorderLayout.EAST);
frame.add(saveButton, BorderLayout.WEST);
frame.pack();
frame.setSize(500, 300);
frame.setVisible(true);
You add main to your frame
You set the frames layout (!?)
You add your buttons
You pack the frame
You set it's size (!?)
You make it visible
The problem here is step #2. If, instead, we simply remove step #2 (step #4 and #5 aren't great either), you will find that your window now contains main...
frame.add(main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(addButton, BorderLayout.EAST);
frame.add(saveButton, BorderLayout.WEST);
frame.pack();
frame.setVisible(true);
This...
for (int i = 0; i < main.getComponentCount();) {
SubPanel panel = (SubPanel) main.getComponent(i);
a bad idea of three reasons;
Your loop will never advance (i will always be 0)
You are blindly casting the contents of main without actually knowing what's on it
MainPanel already has a List of SubPanels...
You need to make sure that you are adding SubPanels via the addSubPanel method (and this should probably return an instance of the SubPanel) and provide a means by which you can access this List, maybe via a getter of some sort. Although, I'd be more interested in their values (ie the text field text) rather then the SubPanel itself ;)

Related

JPanel won't update

I've hit a problem in getting a JPanel to update.
My simple program uses a custom JPanel which displays a label and a textfield. A Jbutton on the main panel is used to replace the JPanel with a new JPanel. The initial panel shows up fine but when the button is pressed the panel is not updated with a new MyPanel. I can tell that a new object is being created as count is being incremented.
public class SwingTest extends JFrame{
private JPanel mp;
private JPanel vp;
private JButton button;
public static void main(String[] args) {
SwingTest st = new SwingTest();
}
public SwingTest() {
vp = new MyPanel();
mp = new JPanel(new BorderLayout());
mp.add(vp, BorderLayout.CENTER);
button = new JButton("Change");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
vp = new MyPanel();
vp.revalidate();
}
});
mp.add(button, BorderLayout.SOUTH);
this.add(mp);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setSize(250, 150);
pack();
setVisible(true);
}
}
and my custom panel....
public class MyPanel extends JPanel{
private JLabel label;
private JTextField tf;
static int count = 0;
public MyPanel(){
count++;
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
setPreferredSize(new Dimension(400, 200));
c.gridx = 0;
c.gridy = 0;
label = new JLabel(String.valueOf(count));
tf = new JTextField(10);
add(label,c);
c.gridx = 1;
add(tf, c);
}
}
You state:
A Jbutton on the main panel is used to replace the JPanel with a new JPanel.
And yet this code:
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
vp = new MyPanel();
vp.revalidate();
}
});
and yet this code does not do this at all. All it does is change the JPanel referenced by the vp variable, but has absolutely no effect on the JPanel that is being displayed by the GUI, which suggests that you're confusing reference variable with reference or object. To change the JPanel that is displayed, you must do exactly this: add the new JPanel into the container JPanel into the BorderLayout.CENTER (default) position, then call revalidate() and repaint() on the container.
e.g.,
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
// vp = new MyPanel();
// vp.revalidate();
mp.remove(vp); // remove the original MyPanel from the GUI
vp = new MyPanel(); // create a new one
mp.add(vp, BorderLayout.CENTER); // add it to the container
// ask the container to layout and display the new component
mp.revalidate();
mp.repaint();
}
});
Or better still -- use a CardLayout to swap views.
Or better still -- simply clear the value held by the JTextField.
For more on the distinction between reference variable and object, please check out Jon Skeet's answer to this question: What is the difference between a variable, object, and reference?

How to change CardLayout panels from a separate panel?

My software layout is kinda wizard-base. So the base panel is divided into two JPanels. One left panel which never changes. And one right panel that works with CardLayout. It has many sub-panels and show each one of them by a method.
I can easily go from one inner panel to another one. But I want to have a button in left panel and change panels of the right side.
Here is a sample code which you can run it:
BASE:
public class Base {
JFrame frame = new JFrame("Panel");
BorderLayout bl = new BorderLayout();
public Base(){
frame.setLayout(bl);
frame.setSize(800, 600);
frame.add(new LeftBar(), BorderLayout.WEST);
frame.add(new MainPanel(), BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
new Base();
}
}
Left side
public class LeftBar extends JPanel{
JButton button;
MainPanel mainPanel = new MainPanel();
public LeftBar(){
setPreferredSize(new Dimension(200, 40));
setLayout(new BorderLayout());
setBackground(Color.black);
button = new JButton("Show Second Page");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
mainPanel.showPanel("secondPage");
}
});
add(button, BorderLayout.NORTH);
}
}
Right Side
public class MainPanel extends JPanel {
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel(){
FirstPage firstPage = new FirstPage(this);
SecondPage secondPage = new SecondPage(this);
setLayout(new GridLayout(0,1));
panelHolder.add(firstPage, "firstPage");
panelHolder.add(secondPage, "secondPage");
cl.show(panelHolder, "firstPage");
add(panelHolder);
}
public void showPanel(String panelIdentifier){
cl.show(panelHolder, panelIdentifier);
}
}
Inner panels for right side:
public class FirstPage extends JPanel {
MainPanel mainPanel;
JButton button;
public FirstPage(MainPanel mainPanel) {
this.mainPanel = mainPanel;
setBackground(Color.GRAY);
button = new JButton("Show page");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
mainPanel.showPanel("secondPage");
}
});
add(button);
}
}
public class SecondPage extends JPanel{
MainPanel mainPanel;
JButton button;
public SecondPage(MainPanel mainPanel){
this.mainPanel = mainPanel;
setBackground(Color.white);
add(new JLabel("This is second page"));
}
}
And this is a picture to give you the idea:
As I explained, I can travel "from first" page to "second page" by using this method: mainPanel.showPanel("secondPage"); or mainPanel.showPanel("firstPage");.
But I also have a JButton in the left bar, which I call the same method to show the second panel of the CardLayout. But it does not work. It doesnt give any error though.
Any idea how to change these CardLayout panels from outside of panels?
The problem is that LeftBar has mainPanel member that is initialized to a new instance of MainPanel. So you have two instances of MainPanel, one allocated in Base and added to the frame, the other one allocated in LeftBar.
So LeftBar executes mainPanel.showPanel("secondPage"); on a second instance of MainPanel which is not even a part of a visual hierarchy. To fix this just pass an existing instance of MainPanel to the constructor of LeftBar. You already do this in FirstPage and SecondPage.

Java layout with frames and panels

I'm building my first Java swing GUI, but I cannot manage to have the layout as I wanted.
Can you help me to understand how the layout should be set to have the desired result (see image below)?
This is what I get (wrong):
and if I resize it manually I get the desired result:
Here is my code:
public class MainClass implements Runnable {
private JButton load = new JButton("Load..");
private JButton save = new JButton("Save..");
private JButton clear = new JButton("Clear");
private JLabel displayFile = new JLabel();
List<String> lines;
JFrame frame = new JFrame("SimpleDrawing");
public static void main(String[] args) {
MainClass maincl = new MainClass();
SwingUtilities.invokeLater(maincl);
}
#Override
public void run() {
DrawingArea area = new DrawingArea();
frame.setLayout(new FlowLayout());
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
//buttonPane.add(Box.createHorizontalGlue());
buttonPane.add(load);
//buttonPane.add(Box.createRigidArea(new Dimension(5,0)));
buttonPane.add(save);
//buttonPane.add(Box.createRigidArea(new Dimension(5,0)));
buttonPane.add(clear);
buttonPane.add(displayFile);
frame.add(buttonPane, BorderLayout.PAGE_START);
frame.add(area, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Your Frame has the FlowLayout.
frame.setLayout(new FlowLayout());
Give it a BorderLayout.
frame.setLayout(new BorderLayout());
Layout- Informations:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

adding new jpanel with default components in swing

can any one tell me how to add a panel in a jtabbedPane whenever i am clicking on a "add" button.Its like google chrome new tab.But the thing is ,the generated panel must contains some default components.Thanks in advance.
Please see the code below. It shows you how to do what you need.
public class DemoApp {
private JTabbedPane tabPane = new JTabbedPane();
public DemoApp() {
initComponents();
}
private void initComponents() {
JFrame frame = new JFrame("Test");
frame.setSize(500, 400);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
frame.getContentPane().add(panel);
JButton btn = new JButton("Add panel");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int index = tabPane.getTabCount() + 1;
JPanel newPanel = new JPanel();
newPanel.setLayout(new FlowLayout());
newPanel.add(new JLabel("Panel " + index));
tabPane.addTab("Tab " + index, newPanel);
}
});
panel.add(tabPane, BorderLayout.CENTER);
panel.add(btn, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
new DemoApp();
}
}

Swing Methods on submission of button

How to close current frame (Frame1) and open a new frame (Frame2) already created and pass the data to frame2 from frame1 on the clicking of button?
Use a CardLayout1. Either that or one JFrame and one or more JDialog2 instances.
How to Use CardLayout
How to Make Dialogs
The very best way to accomplish this, is very much told to you by #Andrew Thompson.
And the other way to accomplish, the motive of the question as described in the code. Here as you make object of your new JFrame, you have to pass the things you need in the other class as an argument to the other class, or you can simply pass the object(with this you be passing everything in one go to the other class)
A sample code for a bit of help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFramesExample
{
public JFrame frame;
private JPanel panel;
private JButton button;
private JTextField tfield;
private SecondFrame secondFrame;
public TwoFramesExample()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
tfield = new JTextField(10);
tfield.setBackground(Color.BLACK);
tfield.setForeground(Color.WHITE);
button = new JButton("NEXT");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
// Here we are passing the contents of the JTextField to another class
// so that it can be shown on the label of the other JFrame.
secondFrame = new SecondFrame(tfield.getText());
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(tfield, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFramesExample();
}
});
}
}
class SecondFrame
{
private JFrame frame;
private JPanel panel;
private JLabel label;
private JButton button;
private TwoFramesExample firstFrame;
public SecondFrame(String text)
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BorderLayout());
label = new JLabel(text);
button = new JButton("BACK");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
firstFrame = new TwoFramesExample();
frame.dispose();
}
});
frame.setContentPane(panel);
panel.add(label, BorderLayout.CENTER);
panel.add(button, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
}
Hope this be of some help.
Regards

Categories

Resources