How can I switch Panels with ScrollPanes in a Frame? I've tried many possible ways but cannot come up with a solution to.
Actually this is one of the Java Problems my professor gave me and I needed to accomplish this by not using other layouts (such as CardLayout) and I should use the null layout only. Additional classes are allowed as long as I maintain these three classes and the scroll pane.
public class MainDriver {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame");
panel1 p1 = new panel1();
panel2 p2 = new panel2();
JScrollPane jsp = new JScrollPane(panel1.panel);
Container c = frame.getContentPane();
jsp.getVerticalScrollBar().setUnitIncrement(10);
c.add(jsp);
//codes for panel switching from panel1 to panel2 vice versa
frame.setDefaultCloseOperation(JFrame.exit_ON_CLOSE);
frame.setSize(1058, 600);
frame.setLocation(100, 50);
frame.setVisible(true);
}
}
---------------------------------------------
public class panel1{
public JPanel panel(){
JPanel fore = new JPanel();
fore.setLayout(null);
fore.setPreferredSize(new Dimension (1024, 600));
fore.setBackground(Color.decode("#004050"));
fore.setVisible(true);
JButton but = new JButton();
but.setLocation(425, 300);
but.setSize(100, 35);
//button action/mouse listener
fore.add(but);
return fore;
}
}
---------------------------------------------
public class panel2{
public JPanel panel(){
JPanel fore = new JPanel();
fore.setLayout(null);
fore.setPreferredSize(new Dimension (1024, 600));
fore.setBackground(Color.decode("#004050"));
fore.setVisible(true);
JButton but = new JButton();
but.setLocation(425, 300);
but.setSize(100, 35);
//button action/mouse listener
fore.add(but);
return fore;
}
}
How can I switch Panels with ScrollPanes in a Frame?
scrollPane.setViewportView( anotherPanel );
Related
I am fairly new to java and programming overall. I've read quite an amount of information and watched a lot of videos about layouts, but even then upon my first try to make a program my screen goes all empty.
I am trying to make two panels for different usage and I am trying to add components to the sides (Left: one north panel will be used for buttons, Right: north, east and south panels will be used for buttons).
Here is the code:
public class SNGUI {
public JFrame f = new JFrame();
JPanel panelright = new JPanel(); //contains UT/LWmenu/MetaMenu
JPanel panelleft = new JPanel(); //contains TextArea document / TextEditors
JPanel TextEditorsPanel = new JPanel();
JPanel UpperToolsPanel = new JPanel();
JPanel LowerToolsPanel = new JPanel();
JPanel SettingsPanel = new JPanel();
public SNGUI() {
//Frame characteristics
f.setTitle("Study Notes v 0.00.0");
f.setSize(1440,900);
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(1,2));
f.setResizable(true);
f.setVisible(true);
// Main panel layouts
panelright.setLayout(new BorderLayout());
panelleft.setLayout(new BorderLayout());
// Additional panel layouts
//TextEditors.setLayout(new FlowLayout(FlowLayout.LEADING,0,0));
// Lower Tools Buttons
LTButtons[0] = new JButton("Calculator");
// colors (delete later)
panelleft.setBackground(Color.yellow);
panelright.setBackground(Color.DARK_GRAY);
TextEditorsPanel.setBackground(Color.GREEN);
UpperToolsPanel.setBackground(Color.blue);
LowerToolsPanel.setBackground(Color.cyan);
SettingsPanel.setBackground(Color.pink);
//panelright.setPreferredSize(new Dimension(1000,100));
panelleft.add(TextEditorsPanel, BorderLayout.NORTH);
panelright.add(UpperToolsPanel, BorderLayout.NORTH);
panelright.add(LowerToolsPanel, BorderLayout.SOUTH);
panelright.add(SettingsPanel, BorderLayout.EAST);
f.add(panelleft);
f.add(panelright);
}
public static void main(String[] args) {
SNGUI StudyNotes = new SNGUI();
}
}
I have a parent JPanel with child components which are stacked on another. However they do not resize as I'd like to:
This is how it should be
This is what I get
Code:
public class LayoutTest extends JFrame {
public LayoutTest() {
setVisible(true);
setSize(new Dimension(500, 500));
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
for (int i = 0; i < 2; i++) {
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 50));
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel.setBackground(Color.red);
getContentPane().add(panel);
}
}
public static void main(String[] args) {
LayoutTest layoutTest = new LayoutTest();
}
}
The problem mainly is that the components resize vertically when they should not. I'd like them to keep their vertical dimension, but they won't. I've tried multiple layouts e.g. GridBagLayout, FlowLayout, BoxLayout, but none of them worked.
My best try has been with BoxLayout:
Simply: container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS);
and then container.add(component1)...
Any help is appreciated.
Working solution by camickr:
public class LayoutTest extends JFrame {
public LayoutTest() {
setVisible(true);
setSize(new Dimension(500, 500));
JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
for (int i = 0; i < 2; i++) {
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 50));
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel.setBackground(Color.red);
container.add(panel, BorderLayout.PAGE_START);
}
getContentPane().add(container, BorderLayout.NORTH);
}
public static void main(String[] args) {
LayoutTest layoutTest = new LayoutTest();
}
}
A BoxLayout will grow components up to there maximum size when space is available.
When you add your panel to the frame, instead of adding it to the CENTER, which would allow the panel to grow, you add it to the PAGE_START which will respect the height:
JPanel north = new JPanel();
north.setLayout( new BoxLayout(north, BoxLayout.PAGE_AXIS) );
// add loop to add panels to the "north" panel
add(north, BorderLayout.PAGE_START);
Another solution is to wrap the panel using a box layout into another panel.
JPanel panel = new JPanel();
panel.setLayout( new BoxLayout(panel. BoxLayout.PAGE_AXIS) );
// create your loop to add child panels
JPanel wrapper = new JPanel(); // uses FlowLayout by default which respects the preferred size.
wrapper.add( panel );
frame.add( wrapper );
May I know why my jPanel does not appear in the jFrame? I want to make 5 blue jPanel appear in the jFrame but why only 1 blue jPanel appear in my jFrame? Thanks for helping!
public class NewJFrame2 extends javax.swing.JFrame {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
/**
* Creates new form NewJFrame2
*/
public NewJFrame2() {
initComponents();
JPanel[] panelArray = new JPanel[5];
JButton btnArray[] = new JButton[5];
for(int i = 0; i<5;i++)
{
panelArray[i] = new JPanel();
//panelArray[i].setVisible(true);
System.out.println(panelArray[i]);
javax.swing.border.Border border = BorderFactory.createLineBorder(Color.BLUE, 5);
panelArray[i].setBackground(Color.YELLOW);
panelArray[i].setBorder(border);
frame.getContentPane().add(panelArray[i]);
}
frame.setSize(new Dimension(500, 400));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("A Simple JFrame");
frame.setVisible(true);
}
As mentioned in the comments you want a LayoutManager.
The current issue is that you are adding all five panels to the exact same space on your frame. To solve this issue you need to provide a structure for the frame to associate different coordinates with different areas.
This answer contains a good jumping off point for you to start to play with layouts in Java.
Using a container JPanel with a BoxLayout -- see comments below for further info :
initComponents();
JPanel[] panelArray = new JPanel[5];
JButton btnArray[] = new JButton[5];
JPanel container = new JPanel(); // Container JPanel
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS)); // With a BoxLayout
for (int i = 0; i < 5; i++) {
panelArray[i] = new JPanel();
//panelArray[i].setVisible(true);
System.out.println(panelArray[i]);
javax.swing.border.Border border = BorderFactory.createLineBorder(Color.BLUE, 5);
panelArray[i].setBackground(Color.YELLOW);
panelArray[i].setBorder(border);
container.add(panelArray[i]); // Adding 5 JPanels to container JPanel
}
frame.getContentPane().add(container); // Adding container JPanel to JFrame
frame.setSize(new Dimension(500, 400));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("A Simple JFrame");
frame.setVisible(true);
I am attempting to make a PC Application using Java and JFrame. I'm trying to format 2 transparent buttons, each sized half of the full screen shown (vertically). The top half of the screen will hold to option to debate someone and the bottom half of the screen will hold the option to spectate a debate if clicked on. Here is what I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame {
JButton b1;
JButton b2;
JPanel j1;
JPanel j2;
public BackgroundImageJFrame() {
setTitle("Background Color for JFrame");
setSize(340,563);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
/*
One way
-----------------
setLayout(new BorderLayout());
JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful design.png"));
add(background);
background.setLayout(new FlowLayout());
l1=new JLabel("Here is a button");
b1=new JButton("I am a button");
background.add(l1);
background.add(b1);
*/
// Another way
setLayout(new BorderLayout());
setContentPane(new JLabel(new ImageIcon("C:\\Users\\MLH-User\\Downloads\\Front.jpg")));
setLayout(new FlowLayout());
j1 = new JPanel();
j1.setLayout(null);
b1 = new JButton("Spectate");
//b1.setBounds(0,0,50,50);
b1.setOpaque(false);
b1.setContentAreaFilled(false);
b1.setBorderPainted(false);
j1.add(b1);
b2 = new JButton("Debate");
b2.setLocation(0,0);
b2.setOpaque(false);
b2.setContentAreaFilled(false);
b2.setBorderPainted(false);
j1.add(b2);
add(j1);
// Just for refresh :) Not optional!
setSize(339,562);
setSize(340,563);
}
public static void main(String args[]) {
new BackgroundImageJFrame();
}
}
This is some stuff I experimented with so far, can anyone help me out about where I went wrong?
You should use a layout manager. Here is an example with GridLayout:
public class Example extends JFrame {
private static final int SIZE = 300;
public Example() {
setLayout(new GridLayout(2, 1, 0, 5));
getContentPane().setBackground(Color.WHITE);
JButton debate = new JButton("DEBATE") {
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
};
Font font = debate.getFont().deriveFont(30f);
debate.setFont(font);
// debate.setBorderPainted(false);
debate.setBackground(Color.BLUE.brighter());
debate.setForeground(Color.WHITE);
JButton spectate = new JButton("SPECTATE") {
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
};
spectate.setFont(font);
// spectate.setBorderPainted(false);
spectate.setBackground(Color.RED.brighter());
spectate.setForeground(Color.WHITE);
add(debate);
add(spectate);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(() -> new Example());
}
}
Notes:
You have to realize that screen sizes vary. Setting SIZE to 300 was an arbitrary choice for presentation, screens might not have the required size. You can also set the insets or an empty border instead of specifying the size of the component directly.
You can consider creating a class for these buttons if you have more of them.
This is an example of setting the sizes. I don't know about the location part though.
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));
for(int i=0 ; i<16 ; i++){
JButton btn = new JButton(String.valueOf(i));
btn.setPreferredSize(new Dimension(40, 40));
panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
I have a JFrame and a Jpanel over that in which various buttons are placed.so on click of a button I have called a new class which is also having containers placed in a Jpanel.so I want to show that new class panel over the main Jframe panel.How can I do that?
And if we use card layout in it then how can i use that as on click button i have called an object of a new class.
as
Card layout consider each component in a container as card and i want whole Jpanel as a card so is it possible to do that???
Can We do nesting of Jpanels in it?
Please suggest me a right way to do that?
here is SSCCE:
// this is the main class on which i want to use panel of other class
public class mymain
{
JFrame jframe = new JFrame();
JPanel panel = new JPanel();
BorderLayout borderlayout = new BorderLayout();
public mymain()
{
jframe.setLayout(borderlayout);
JMenuBar menubar = new JMenuBar();
jframe.setJMenuBar(menubar);
JButton home_button = new JButton("HOME");
menubar.add(home_button);
jframe.getContentPane().add(panel,BorderLayout.CENTER);
panel.setLayout(new GridBagLayout());
//here used containers over that frame
and call it from main()
}
here is another class to manage category is
public class manageCategory
{
JPanel panel = new JPanel();
GridBagLayout gridbglayout = new GridBagLayout();
GridBagConstraints gridbgconstraint = new GridBagConstraints();
public manageCategory()
{
panel.setLayout(new BorderLayout());
// i have again here used containers placed with grid bag layout
}
}
So now i want that as i click on home button used in mymain class then the panel that is used in manageCategory() should be displayed on the same panel.and when i again click on home button then the mymain panel get displayed.how can i do that???
I would advise you to use a CardLayout for this task.
Updated example with JPanel and "classes":
static class MainPanel extends JPanel {
public MainPanel(final Container frame) {
add(new JButton(new AbstractAction("Click to view next") {
#Override
public void actionPerformed(ActionEvent e) {
frame.add(new NextPanel(), "NextPanel");
((CardLayout) frame.getLayout()).show(frame, "NextPanel");
}
}));
}
}
static class NextPanel extends JPanel {
public NextPanel() {
add(new JLabel("Next page in the card layout"));
}
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Test");
frame.setLayout(new CardLayout());
frame.add(new MainPanel(frame.getContentPane()), "MainPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);
}
CardLayout is one of possible ways, but there are another options valid or required by most completed GUI
1) BorderLayout, because there only one JComponent can occupate decision area
someContainer.add(myPanel, BorderLayout.CENTER)
revalidate();
repaint();
2) GridBagLayout
before anything you have to get declared GridBagConstraints from myOldComponent layed by GridBagLayout
myContainer.setVisible(myOldComponent);
//or
myContainer.remove(myOldComponent);
myContainer.add(myNewComponent, gbc);
revalidate();
repaint();
You can
JFrame myFrame = new JFrame();
JPanel panel1 = new JPanel();
Panel1.setVisible(true);
myFrame.add(panel1);
JPanel panel2 = new JPanel();
Panel2.setVisible(false);
myFrame.add(panel2);
//Here you setup your panels and your actionlisteners etc and when
//you wish for your second panel to show up just run the code below.
panel1.setVisible(false);
panel2.setVisible(true);
Obviously you first have to add both panels to your Jframe. Panel1 will be at first visible, as it is the one shown by default. Panel2 must be set to be invisible in the beginning.