adding a jpanel into a jpanel in java - java

I have a Jpanel named mainPanel and another class named MyPanel that extends JPanel. I want to add MyPanel into mainPanel. I did this code and getting no result .
This is my Main class that holds mainPanel:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Main extends JFrame {
private JPanel contentPane;
private final JPanel mainPanel = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
inItGUI();
}
private void inItGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 662, 417);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
mainPanel.setBounds(25, 11, 611, 341);
contentPane.add(mainPanel);
mainPanel.setLayout(null);
mainPanel.add(new MyPanel());// **Here i added MyPanel**
mainPanel.revalidate();
repaint();
}
}
and this is my MyPanel class that has beeb added to mainPanel earlier:
import java.awt.Component;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MyPanel extends JPanel {
private final JButton btnNewButton = new JButton("New button");
private final JButton btnNewButton_1 = new JButton("New button");
public MyPanel() {
inItGUI();
}
private void inItGUI() {
setLayout(null);
btnNewButton.setBounds(60, 49, 106, 43);
add(btnNewButton);
btnNewButton_1.setBounds(189, 49, 89, 43);
add(btnNewButton_1);
}
}

Welcome to one of the wonderful pitfalls of null layout managers
If you remove the layout manager, you remove any chance of your components from being automatically size and positioned.
Basically what's happening is that MyPanel is being added to mainPanel and position 0x0 with a size of 0x0, so nothing is begin displayed.
The real solution is use an appropriate layout manager
Don't fool your self. Managing the position and size of components, especially the relationship between the components, in the field of modern computer systems is a complex one. You have to be able to take into account how each component is rendered based on the font, DPI, orientation, etc... of the current system, then take into account how that might effect other components that share the same container...You also have to monitor for changes in the hierarchy of components that you are attached to...
This is the job that layout managers provide...Swing is designed around the use of layout managers and you should have a VERY good reason to ignore them...IMHO

Related

How to refresh JInternalFrame or JPanel form on button click where JPanel is a separate class and used in JInternalFrame

Iam trying to build a desktop application with multiple screens inside one single JFrame.
So each button click event will take us to the separate screen with refreshed components in the screen. So far this approach is working for me but the problem I am facing is even after using ".dispose(), .repaint(), .revalidate(), .invalidate()" functions. JInternalFrame or Jpanel seems to not refresh its components.
Which works something like below gif.
Tabbed Style
I do know JtabbedPane exists but for my method JtabbedPane is not viable.
Below I am posting minified code by replicating the problem I am facing.
MainMenu.Java(file with Main Class)
package test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JInternalFrame;
public class MainMenu extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenu frame = new MainMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 841, 522);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 10, 807, 63);
contentPane.add(panel);
panel.setLayout(new GridLayout(1, 0, 0, 0));
JButton Tab1 = new JButton("Tab1");
panel.add(Tab1);
JButton Tab2 = new JButton("Tab2");
panel.add(Tab2);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 88, 807, 387);
contentPane.add(scrollPane);
JInternalFrame internalFrame1 = new JInternalFrame();
JInternalFrame internalFrame2 = new JInternalFrame();
Tab1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Panel1 panel1 = new Panel1();
if(internalFrame1 !=null) {
internalFrame1.dispose();
panel1.invalidate();
panel1.revalidate();
panel1.repaint();
}
internalFrame1.setTitle("Panel 1");
scrollPane.setViewportView(internalFrame1);
internalFrame1.getContentPane().add(panel1);
internalFrame1.setVisible(true);
}
});
Tab2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Panel2 panel2 = new Panel2();
if(internalFrame2 !=null) {
internalFrame2.dispose();
panel2.invalidate();
panel2.revalidate();
panel2.repaint();
}
internalFrame2.setTitle("Panel 2");
scrollPane.setViewportView(internalFrame2);
internalFrame2.getContentPane().add(panel2);
internalFrame2.setVisible(true);
}
});
}
}
and the corresponding Jpanel class files where JInternal Frames
Panel1.java
package test;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Panel1 extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public Panel1() {
setLayout(null);
textField = new JTextField();
textField.setBounds(10, 60, 430, 19);
add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Example Button");
btnNewButton.setBounds(10, 156, 430, 21);
add(btnNewButton);
}
}
Panel2.java
package test;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Panel2 extends JPanel {
private JTextField textField;
/**
* Create the panel.
*/
public Panel2() {
setLayout(null);
textField = new JTextField();
textField.setBounds(10, 60, 430, 19);
add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button2");
btnNewButton.setBounds(21, 157, 419, 21);
add(btnNewButton);
}
}
P.S: This is my first time asking question in Stackoverflow so forgive me and if possible guide me if i miss anything
Thank you :)
Edit:
The problem I am facing is on the surface it looks like the Jpanel has been refreshed but the components like JtextField Still hides the previously written text in it and only show the text when i click on that JTextField
Below I am Attaching another gif which show highlights the issue. I have highlighted the part where I am facing issue.
Issue I am Facing
The dispose() method does not remove components so you keep adding components to the internal frame when you use the following:
internalFrame1.getContentPane().add(panel1);
Instead you might do something like:
Container contentPane = internalFrame1.getContentPane();
contentPane.removeAll();
contentPane.add( panel1 );
contentPane.revalidate();
contentPane.repaint();
You can use the JPanels in the Jframes and then use the CardLayout to change the panel ( which could than act like the different screens )

Center panel when window resized

I would like to keep a panel I have created using an absolute layout in the center of my window even when the window is resized (if possible). I've come across a couple of suggestions here and [here][2] but no dice! Below is my sample code, any ideas or suggestions? I have no problems centered a single component like a JLable but I want to center a panel with many components!
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.JLabel;
public class TestPanel extends JFrame {
private JLabel lblSetupTitle;
private Border compoundBorder, outlineColorBorder, outlineBorder;
private JTextArea txtrManageData;
private JPanel childPanel;
public TestPanel()
{
setBackground(Color.white);
outlineColorBorder = BorderFactory.createLineBorder(Color.gray);
outlineBorder = BorderFactory.createEmptyBorder(20, 20, 20, 20);
compoundBorder = BorderFactory.createCompoundBorder(outlineColorBorder, outlineBorder);
lblSetupTitle = new JLabel("Setup");
lblSetupTitle.setBounds(443, 288, 44, 23);
txtrManageData = new JTextArea("Text Area Text");
txtrManageData.setBounds(393, 322, 142, 61);
childPanel = new JPanel();
childPanel.setLocation(89, 38);
childPanel.setSize(921, 452);
childPanel.setBorder(compoundBorder);
setupGUIElements();
setupPanel();
}
private void setupGUIElements()
{
txtrManageData.setBackground(null);
txtrManageData.setLineWrap(true);
txtrManageData.setWrapStyleWord(true);
}
private void setupPanel()
{
getContentPane().setLayout(new GridBagLayout()); // set layout of parent panel to GridBagLayout
childPanel.setLayout(null); // set layout of child panel to AbsoluteLayout
childPanel.add(lblSetupTitle);
childPanel.add(txtrManageData);
getContentPane().add(childPanel, new GridBagConstraints());
this.setSize(1020, 500);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestPanel ex = new TestPanel();
ex.setVisible(true);
}
});
}
}
EDIT: Any tips, links, guidance on creating something like this
I'd nest layouts.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class ThreeButtonTextFieldCombo {
private JPanel ui = null;
ThreeButtonTextFieldCombo() {
initUI();
}
public final void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
ui.setBorder(new TitledBorder("Parent Panel"));
JPanel controls = new JPanel(new GridLayout(1,0,10,10));
ui.add(controls);
controls.setBackground(Color.RED);
controls.setBorder(new TitledBorder("Child Panel"));
for (int ii=1; ii<4; ii++) {
addLabelAndField(controls, "String " + ii);
}
}
public JComponent getUI() {
return ui;
}
private void addLabelAndField(JPanel panel, String text) {
JPanel controls = new JPanel(new BorderLayout(3, 3));
controls.setBorder(new EmptyBorder(20,20,20,20));
JLabel l = new JLabel(text);
controls.add(l, BorderLayout.PAGE_START);
JTextArea ta = new JTextArea(text, 2, 8);
controls.add(new JScrollPane(ta));
panel.add(controls);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Three Button/Text Field Combo");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
ThreeButtonTextFieldCombo tbtfc =
new ThreeButtonTextFieldCombo();
f.setContentPane(tbtfc.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
The first problem with your code is that you are adding your child panel using an empty instantiation of GridBagConstraints. I have never seen it used like that before.
getContentPane().add(childPanel, new GridBagConstraints());
Do not set any layout to content pane and just add it like this :
getContentPane().add(childPanel);
Now if you run it you will get the two components in the middle, where you defined them using the setBounds(..) method.
Like almost everyone commenting on your question, you should not use null layout, and use some other layout instead. I would use a GridBagLayout to organise the three buttons and three textfields in your diagram. You could then setBounds(..) on your child panel.
If you really must use absolute layout then you will have to do a bit of maths.
If your first label is like this :
labell1.setBounds(443, 288, 44, 23);
then your second label should be something like this :
labell2.setBounds(443 + someXDisplacement, 288, 44, 23);
..and third :
labell3.setBounds(443 + (someXDisplacement x 2), 288, 44, 23);
You get the picture.

trying yo update my JFrame [duplicate]

This question already has answers here:
Replacing JPanel with JPanel in a JFrame
(3 answers)
Closed 8 years ago.
In my Frame i have have a title screen(J Panel) and when i click a button i want it to be replaced with the game screen(another J Panel). i have this code to replace it, but when i click the button to send it to my start method it clears the GUI and it just stays blank.
public void start() {
frame.remove(titlePanel);
frame.repaint();
frame.add(gamePanel);
}
if i add the gamePanel to the frame where i did the titlePanel it works fine so i know it is finding the image.
any help would be much appreciated.
A preferred solution would be to use CardLayout, which will allow you to switch out views easily...
The direct approach (which you are doing now) should be fixed by calling frame.revalidate() after you've added the gamePanel...but I'd still recommend the CardLayout
You have to use frame.revalidate() to get changes working.
Try this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
public class test extends JFrame {
private JPanel contentPane;
JPanel panel1;
JPanel panel2;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test frame = new test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public test() {
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);
panel1 = new JPanel();
contentPane.add(panel1, BorderLayout.NORTH);
panel1.setBackground(Color.red);
panel2 = new JPanel();
panel2.setBackground(Color.blue);
JButton btnNewButton = new JButton("New button");
contentPane.add(btnNewButton, BorderLayout.SOUTH);
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
remove(panel1);
contentPane.add(panel2, BorderLayout.NORTH);
repaint();
validate();
}
});
}
}

Why won't my JPanel show?

So I'm just checking and when I click my button it won't show my JPanel, any idea why?
Thanks.
I want the third class to show, really do appreciate the help - Thanks allot.
First class - JFrame class.
import javax.swing.JFrame;
public class Frame {
public static void main(String[] args ) {
JFrame frame = new JFrame("JFrame Demo");
Panel panel1 = new Panel();
frame.add(panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.setVisible(true);
}
}
Second class - Panel 1
import javax.swing.JPanel;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Panel extends JPanel{
public Panel() {
setLayout(null);
final Panel2 panel2 = new Panel2();
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
panel2.setVisible(true);
}
});
btnNewButton.setBounds(62, 197, 224, 122);
add(btnNewButton);
}
}
Third class - Panel 2 (I want this to show)
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.CardLayout;
import javax.swing.JTextField;
public class Panel2 extends JPanel {
private JTextField textField;
public Panel2() {
setLayout(null);
setVisible(true);
textField = new JTextField();
textField.setBounds(84, 84, 290, 77);
add(textField);
textField.setColumns(10);
}
}
You never add panel2 to anything. A JPanel isn't like a JFrame where setVisible makes it magically appear. You need to add it to a container. Just add it to your Panel.
Also avoid using null layouts. Learn to use Layout Managers
Also see Initial Threads. You want to run your swing apps from the Event Dispatch Thread like this
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new Frame();
}
});
}
This looks like a case where you may have been trying to do something along the lines of what a CardLayout achieves. See this example for a basic use. Also see How to Use Card Layout
In the second class, after the second line in the constructor, have you tried?
add(panel2);
See if this works.
Modify Panel.java to look like below. Tell me if this is good for your needs:
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Panel extends JPanel{
Panel2 panel2 = null;
JButton btnNewButton = null;
public Panel() {
setLayout(null);
panel2 = new Panel2();
panel2.setBounds(5,5,300,500);
add(panel2);
showPanel2(false);
btnNewButton = new JButton("New button");
btnNewButton.setBounds(62, 197, 224, 122);
add(btnNewButton);
showButton(true);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showButton(false);
showPanel2(true);
}
});
}
public void showPanel2(boolean bshow)
{
panel2.setVisible(bshow);
}
public void showButton(boolean bshow)
{
btnNewButton.setVisible(bshow);
}
}

Garbled text in OSX Java text field

When I edit text in a JTextField in my Swing application on OSX, the text gets garbled. It's most pronounced when I insert or delete characters but there are artifacts just when moving the cursor around. The data is fine, but the UI rendering is not.
What causes this and how can I fix it?
I'm using com.apple.laf.AquaLookAndFeel, as in this sample program. Type in some text and move the cursor around with the arrow keys to observe the weirdness.
import java.awt.*;
import javax.swing.*;
class TextFieldDisplay {
public static void main(String[] args) {
MainWindow app = new MainWindow();
}
}
class MainWindow extends JFrame {
public MainWindow() {
try {
UIManager.setLookAndFeel("com.apple.laf.AquaLookAndFeel");
} catch(Exception e) {
System.out.println("AquaLookAndFeel is not supported on your platform.");
System.exit(1);
}
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setMinimumSize(new Dimension(300, 100));
JPanel innerPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(250, 20));
scrollPane.setViewportView(innerPanel);
JPanel mainPanel = new JPanel();
getContentPane().add(mainPanel);
mainPanel.add(innerPanel);
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(250, 20));
innerPanel.add(textField);
pack();
}
}
I noticed as I was writing the SSCCE that the display issues seemed to crop up after I added the JScrollPane.
Not sure if it's relevant but I'm using Apple Java version 1.6.0_51 with a retina display.
Two things jump out at me.
Firstly, you're not initalisig your UI in the EDT, secondly, you're messing with the preferred and minimum sizes of your components.
You are not taking into consideration the font metrics when calculating the size of your components, which seems to be causing issues when it is rendering the content
Start by taking a look at Initial Threads.
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
class TextFieldDisplay {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
//UIManager.setLookAndFeel("com.apple.laf.AquaLookAndFeel");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println("AquaLookAndFeel is not supported on your platform.");
System.exit(1);
}
MainWindow app = new MainWindow();
}
});
}
}
class MainWindow extends JFrame {
public MainWindow() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
// setMinimumSize(new Dimension(300, 100));
JPanel innerPanel = new JPanel();
// JScrollPane scrollPane = new JScrollPane();
// scrollPane.setPreferredSize(new Dimension(250, 20));
// scrollPane.setViewportView(innerPanel);
JPanel mainPanel = new JPanel();
getContentPane().add(mainPanel);
mainPanel.add(innerPanel);
JTextField textField = new JTextField(20);
// textField.setPreferredSize(new Dimension(250, 20));
innerPanel.add(textField);
pack();
}
}

Categories

Resources