How to add a JPanel object, with components, to a JFrame - java

I want to add an object of type JPanel to a JFrame.
I'm trying this, but the Jpanel is not added.
the idea is: Add to P2 a P5 that has the components defined in class P5.
What could be happening ?, I do not want to create all the JPanel in the class First_view, since the code would be messed up a lot.
CODE:
import javax.swing.*;
import java.awt.*;
public class First_view extends JFrame {
Container Frame;
public First_view() {
super("title");
Frame = this.getContentPane();
Frame.setLayout(new BorderLayout());
Frame.add((new P2()), BorderLayout.WEST);
setSize(900, 500);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class P2 extends JPanel {
public P2() {
this.setLayout(new BorderLayout());
add((new P5()), BorderLayout.NORTH);
}
}
class P5 extends JPanel {
JScrollPane informacion = new JScrollPane(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JTextArea T1 = new JTextArea();
public P5() {
setLayout(new FlowLayout());
setBorder(BorderFactory.createEmptyBorder(20, 10, 0, 0));
add(setInformacion());
}
private JScrollPane setInformacion() {
T1.append("Information, bla bla bla");
T1.setEditable(false);
T1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
T1.setLineWrap(true);
informacion.add(T1);
informacion.setBorder(BorderFactory.createLineBorder(Color.BLACK));
return informacion;
}
}
PIC:

The component to display in the JScrollPane should not be added, use setViewportView instead.
private JScrollPane setInformacion() {
T1.append("Information, bla bla bla");
...
informacion.setViewportView(T1);
...
informacion.setBorder(BorderFactory.createLineBorder(Color.BLACK));
return informacion;
}
Obs: the arguments passed to the constructor of JScrollPane are in the wrong order, that is, the vertical police comes first:
JScrollPane informacion = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Edit: as Andrew commented it is not a good idea to extend a class just to use it (JFrame, JPanel). Example, I tried not to change too much of your original flow:
package cfh.test;
import javax.swing.*;
import java.awt.*;
public class FirstView {
private JFrame frame;
private JTextArea informacionText; // not sure if that is needed as field
public FirstView() {
informacionText = new JTextArea();
informacionText.setEditable(false);
informacionText.setBorder(BorderFactory.createLineBorder(Color.BLACK));
informacionText.setLineWrap(true);
informacionText.append("Information, bla bla bla");
JScrollPane scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
scrollPane.setViewportView(informacionText);
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout());
infoPanel.add(scrollPane);
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BorderLayout());
leftPanel.add(infoPanel, BorderLayout.NORTH);
// TODO consider moving above code to an own method returning the left panel
frame = new JFrame("title");
frame.setLayout(new BorderLayout());
frame.add(leftPanel, BorderLayout.WEST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

Related

Adding a Tabbed Pane to a Panel using Layout managers

I am simply trying to add a tabbed pane with 5 tabs onto a panel, although only the final tab (tab e) is being shown.
I am obviously doing something fundamentally wrong here, I have tried changing the layout manager of the Panel the tabbed pane is being added to but I don't think this is the problem. Any adivce would be helpful thanks!
Main Class Code:
public static void main(String[] args) {
JFrame frame = new JFrame("Data Structures Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
GraphicPanel G = new GraphicPanel();
frame.add(G.getPanel());
frame.setVisible(true);
}
Graphics Class
public class GraphicPanel {
public JPanel topPanel;
public GraphicPanel() {
JPanel Panel = new JPanel();
Panel.setLayout(new GridLayout(1, 1));
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("a", Panel);
tabbedPane.addTab("b", Panel);
tabbedPane.addTab("c", Panel);
tabbedPane.addTab("d", Panel );
tabbedPane.addTab("e", Panel );
topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 1));
topPanel.add(tabbedPane);
}
public JPanel getPanel(){
return topPanel;
}
}
you must creates new instance of JPanel if you want to show in JTabbedPane
try this code:
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("a", new Panel());
tabbedPane.addTab("b", new Panel());
tabbedPane.addTab("c", new Panel());
tabbedPane.addTab("d", new Panel());
tabbedPane.addTab("e", new Panel());

Adding Panel to Panel

I anted to add a JPanel to my already existing JPanel so I could have a small window with a JTextField on top with a name and a scrollable JTextArea below it with some description. I made a class that extends JPanel with the following constructor:
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
public class LocationWindow extends JPanel {
public JTextField name;
public JTextArea desc;
public JScrollPane scroll;
public LocationWindow(){
super();
setBorder (new TitledBorder(new EtchedBorder(), "Display Area"));
setLayout(new BorderLayout());
setVisible(true);
setBounds(30, 40, 700, 290);
name = new JTextField(10);
name.setText("name");
desc = new JTextArea(5,10);
scroll = new JScrollPane(desc);
scroll.setVerticalScrollBarPolicy ( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS );
desc.setEditable (true);
desc.setLineWrap(true);
desc.setText("random text");
add(name);
add(desc);
add(scroll);
validate();
}
}
It almost works, as it gives me the window with the borders and a scroll, but both the JTextField and JTextArea are missing.
As you are using BorderLayout for the JPanel,
setLayout(new BorderLayout());
the components will always be added to the center if you dont specify the position. add(scroll); is same as add(scroll,BorderLayout.CENTER); as you're adding all via add the last added component only be visible.Refer this as well
The next is you are adding JTextArea seperately so it will be removed from ScrollPane.Just add scrollpane to Panel no need to add all components.[Add the parent component alone]
add(name,BorderLayout.NORTH);
//add(desc);Noo need to add desc as it is already added in JScrollPane
add(scroll,BorderLayout.CENTER);
There is no need for setVisible for JPanel.JPanel needs to be embedded in Container like JFrame to be visible
//setVisible(true);Wont do anything
So call like this
JFrame frame = new JFrame();
frame.add(new LocationWindow());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
You can use below code to adding panel to panel.
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
LocationWindow loc = new LocationWindow();
frame.add(loc);
frame.setSize(300, 200);
frame.setVisible(true);
}

How to resize a JPanel

I am trying to resize the JPanels but there is a space under it . Here is a link to show :
And this is the code :
import java.awt.*;
import javax.swing.*;
public class Ex1 extends JFrame{
private JTextArea textarea = new JTextArea ();
private JTextField field = new JTextField ();``
private JButton buton = new JButton ("Trimite");
public Ex1(){
JPanel panel = new JPanel (new BorderLayout(2,2));
JPanel panel1 = new JPanel (new BorderLayout(2,2));
JPanel panel2 = new JPanel (new BorderLayout(2,2));
JLabel label1 = new JLabel ("Mesaje");
JLabel label2 = new JLabel ("Scrieti un mesaj");
panel1.setPreferredSize(new Dimension(350,100));
panel2.setPreferredSize(new Dimension(350,25));
panel1.add(label1, BorderLayout.NORTH);
panel1.add(textarea, BorderLayout.CENTER);
panel2.add(label2, BorderLayout.WEST);
panel2.add(field, BorderLayout.CENTER);
panel2.add(buton, BorderLayout.EAST);
setLayout(new GridLayout(2,1,1,1));
panel.add(panel1, BorderLayout.NORTH);
panel.add(panel2, BorderLayout.CENTER);
add(panel);
}
public static void main(String[] args) {
JFrame frame = new Ex1();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
You are setting a layout for a frame to GridLayout in which all components are given equal size. You have two rows, add(panel) adds the panel to the first row of the grid. The second row is left empty. See How to Use GridLayout.
Comment out setLayout(new GridLayout(2,1,1,1)); and the extra space should go away. When you comment this line the layout of frame's content pane will be BorderLayout. The default layout of the JFrame is BorderLayout. So add(panel); will add the panel to the center of the frame's content pane. As a result the panel should occupy all the available space.
As a side note, avoid setPreferredSize(), usually it is not necessary, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing for details.
You can specify the number of rows and columns for a text area and wrap it in the scroll pane, ie:
textArea = new JTextArea(5, 20);
JScrollPane scrollPane = new JScrollPane(textArea);
For more details see How to Use Text Areas
EDIT: example of getPreferredSize()
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
public class Ex1 extends JPanel{
private JTextArea textarea = new JTextArea ();
private JTextField field = new JTextField ();
private JButton buton = new JButton ("Trimite");
public Ex1() {
setLayout(new BorderLayout());
JPanel panel1 = new JPanel (new BorderLayout(2,2));
JPanel panel2 = new JPanel (new BorderLayout(2,2));
JLabel label1 = new JLabel ("Mesaje");
JLabel label2 = new JLabel ("Scrieti un mesaj");
panel1.add(label1, BorderLayout.NORTH);
panel1.add(new JScrollPane(textarea), BorderLayout.CENTER);
panel2.add(label2, BorderLayout.WEST);
panel2.add(field, BorderLayout.CENTER);
panel2.add(buton, BorderLayout.EAST);
add(panel1, BorderLayout.CENTER);
add(panel2, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
Ex1 panel = new Ex1();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
}
}
You need to resize the JFrame not the JPanel. Try:
this.setPreferredSize(new Dimension(350, 25);// in Ex1
Or in your main method:
frame.setPreferredSize(new Dimension(350, 25);

How to make Tabbed Pane Visible

Warning: very ignorant beginner at hand!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TabbedGUI extends JFrame {
private static final long serialVersionUID = 1L;
public TabbedGUI() {
JPanel p1 = new JPanel();
JTabbedPane tab;
tab= new JTabbedPane();
TopPanel tp;
tp=new TopPanel();
Dimension d = new Dimension(800,600);
tp.setPreferredSize(d);
tp.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
setBackground(Color.PINK);
//MiddlePanel
MiddlePanel mp;
mp=new MiddlePanel();
this.add (mp, BorderLayout.CENTER);
mp.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
//BottomPanel
BottomPanel bp;
bp=new BottomPanel();
this.add (bp, BorderLayout.SOUTH);
bp.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
tab.add(tp);
tab.add(bp);
tab.add(mp);
this.add(tab);
p1.add(tp, BorderLayout.NORTH);
p1.add(bp, BorderLayout.SOUTH);
p1.add(mp, BorderLayout.CENTER);
tab.setPreferredSize(d);
tab.setVisible(true);
this.setVisible(true);
TopPanelC tp1;
tp1=new TopPanelC();
BottomPanelC bp1;
bp1=new BottomPanelC();
MiddlePanelC mp1;
mp1=new MiddlePanelC();
JPanel p2 = new JPanel();
JTabbedPane tab1;
tab1= new JTabbedPane();
tab1.add(tp1);
tab1.add(bp1);
tab1.add(mp1);
this.add(tab1);
this.setVisible(true);
p2.add(tp1, BorderLayout.NORTH);
p2.add(bp1, BorderLayout.SOUTH);
p2.add(mp1, BorderLayout.CENTER);
tab1.setPreferredSize(d);
tab1.setVisible(true);
}
public static void main(String[] args){
new TabbedGUI();
}
}
Create a new GUI called “TabbedGUI.java”. Add a TabbedPane to the JFrame. The TabbedPane should have 2 tabs. The First Tab should be the same as #1 above, a form for Student data. The Second Tab should look very similar, but would be used to display and change Course Data. A Course should have 4 textFields, “Course ID”, “Course Name”, “Description” and “Credit Hours”.
JFrame (or any other window based container) can not be added to anything else, you need to change you UI so that the components extend from something like JPanel
Don't ever extend directly from top level containers where possible (applets are a different beast). Instead, build you UI's around a simple container like JPanel. This allows you to decide how and when to use the components, without been locked into a single top level container, as you are now.
The overall process is simple. JTabbedPane is a container, you add other components onto it. You then add that to an instance of JFrame (or what ever container you want to use), for example...
Take a look at How to Use Tabbed Panes for more details
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TabbedExample {
public static void main(String[] args) {
new TabbedExample();
}
public TabbedExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Student", new StudentGUI());
tabbedPane.add("Courses", new CourseGUI());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tabbedPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class StudentGUI extends JPanel {
public StudentGUI() {
setLayout(new BorderLayout());
JPanel top = new JPanel(new BorderLayout());
top.setBackground(Color.BLUE);
top.add(new JLabel("Top"));
JPanel middle = new JPanel(new BorderLayout());
middle.setBackground(Color.GREEN);
middle.add(new JLabel("Middle"));
JPanel bottom = new JPanel(new BorderLayout());
bottom.setBackground(Color.CYAN);
bottom.add(new JLabel("Bottom"));
add(top, BorderLayout.NORTH);
add(middle);
add(bottom, BorderLayout.SOUTH);
}
}
public class CourseGUI extends JPanel {
public CourseGUI() {
setLayout(new BorderLayout());
JPanel top = new JPanel(new BorderLayout());
top.setBackground(Color.RED);
top.add(new JLabel("Top"));
JPanel middle = new JPanel(new BorderLayout());
middle.setBackground(Color.ORANGE);
middle.add(new JLabel("Middle"));
JPanel bottom = new JPanel(new BorderLayout());
bottom.setBackground(Color.MAGENTA);
bottom.add(new JLabel("Bottom"));
add(top, BorderLayout.NORTH);
add(middle);
add(bottom, BorderLayout.SOUTH);
}
}
}

adding jpanels over split pane in java

I am trying to add three panels on a single JFrame form. if i am only adding three panels they are being displayed but if i add the panel on split pane nothing is being displayed
suggest the error in following code
import javax.swing.*;
import java.awt.*;
class paneltest extends JFrame{
paneltest()
{
Container cp=this.getContentPane();
cp.setLayout(null);
panel1 p1= new panel1();
panel2 p2= new panel2();
panel3 p3= new panel3();
cp.add(p1);
cp.add(p2);
cp.add(p3);
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
p1.setBounds(0,0,screenSize.width/3,screenSize.height);
p2.setBounds(screenSize.width/3,0,screenSize.width/3,screenSize.height);
p3.setBounds(2*(screenSize.width/3),0,screenSize.width/3,screenSize.height);
try{
JSplitPane splitPaneLeft = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
JSplitPane splitPaneRight = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPaneLeft.setLeftComponent( p1 );
splitPaneLeft.setRightComponent( p2 );
splitPaneRight.setLeftComponent( splitPaneLeft );
splitPaneRight.setRightComponent( p3 );
JPanel panelSplit = new JPanel();
panelSplit.add(splitPaneRight);
cp.add(panelSplit);
panelSplit.setVisible(true);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"exception occured"+ex);
}
}
public static void main(String arsg[])
{
paneltest frm= new paneltest();
frm.show ();
}
}
class panel1 extends JPanel
{
panel1()
{
setLayout(new FlowLayout());
JLabel l1= new JLabel("panel1");
add(l1);
}
}
class panel2 extends JPanel
{
panel2()
{
setLayout(new FlowLayout());
JLabel l1= new JLabel("panel2");
add(l1);
}
}
class panel3 extends JPanel
{
panel3()
{
setLayout(new FlowLayout());
JLabel l1= new JLabel("panel3");
add(l1);
}
}
Remove the line cp.setLayout(null). This will fix the initial problem.
After that:
indent the code
respect Java naming conventions
don't add panels to the content pane if you add them to the splitpanes right after. A component can be added to a single parent. It doesn't make sense to add them to both
don't use setBounds(). That's the role of the layout manager
don't extend JPanel and JFrame. Use them
Respect Swing's threading policy.
Don't catch (Exception)

Categories

Resources