I'm trying to create a panel that uses a JLayeredPane to have a panel centered above another, larger panel. I can't seem to get the smaller panel to display though. Any ideas as to what I'm doing wrong?
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
public class MainPanel extends JPanel {
private JLayeredPane pane;
private AllPlayersPanel players; //Larger panel, uses circleLayout
private GamePanel game; //Smaller panel, simple BorderLayout
public MainPanel(){
super();
setSize(900, 900);
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
pane = new JLayeredPane();
pane.setPreferredSize(new Dimension(900, 900));
players = new AllPlayersPanel();
players.setPreferredSize(players.getPreferredSize());
players.setLocation(0,0);
//players.setOpaque(false);
pane.add(players, new Integer(0));
game = new GamePanel();
game.setPreferredSize(game.getPreferredSize());
game.setLocation(385, 405);
//game.setOpaque(false);
pane.add(game, new Integer(2));
add(pane);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JComponent newPane = new MainPanel();
newPane.setOpaque(true);
frame.setContentPane(newPane);
frame.pack();
frame.setVisible(true);
}
}
I've tried every combination of .setOpaque() I can think of as well.
CircleLayout can be found here
Basically, you're using setSize when you shouldn't be and preferredSize when you don't need to...
For example.
In you constructor of the MainPanel you call setSize(900, 900); when you should have overridden getPreferredSize then on the panels you are adding to the JLayeredPane you're calling setPreferredSize but the JLayeredPane has no layout manager with which to check this value, so the size of these panels remain as 0x0.
Besides, I'm not sure what you expected to gain from calling players.setPreferredSize(players.getPreferredSize());, which basically will set the preferred size to 0x0 any way :P
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class MainPanel extends JPanel {
private JLayeredPane pane;
private JPanel players; //Larger panel, uses circleLayout
private JPanel game; //Smaller panel, simple BorderLayout
public MainPanel() {
super();
// setSize(900, 900);
// setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
setLayout(new BorderLayout());
pane = new JLayeredPane();
// pane.setPreferredSize(new Dimension(900, 900));
pane.setBorder(new LineBorder(Color.RED));
players = new JPanel();
players.setBackground(Color.RED);
players.setSize(getPreferredSize());
players.setLocation(0, 0);
//players.setOpaque(false);
pane.add(players, new Integer(0));
game = new JPanel();
game.setSize(game.getPreferredSize());
game.setBackground(Color.BLUE);
game.setLocation(385, 405);
//game.setOpaque(false);
pane.add(game, new Integer(2));
add(pane);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(900, 900);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JComponent newPane = new MainPanel();
newPane.setOpaque(true);
frame.setContentPane(newPane);
frame.pack();
frame.setVisible(true);
}
}
Related
So for a school project I made a grade book in java. When creating the gui I used hardcoded values in the setBounds() methods. Now this worked when I had a 1024×768 screen resolution it looked alright, but when I got a new laptop and it had a 4k screen it looked super small when I ran the program.
So my question would be is there a way to dynamically change the size of the Jframe and all of the associated objects on the frame so it matches the resolution of the screen?
I know that you can get the screen resolution from this
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
but I do not know what would be the best way to do this.
Taking your approach as example and taking this answer and this tutorial as base, here you have the clues:
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
public class Q1 extends JFrame {
public static void main(String[] args) {
Q1 frame = new Q1();
frame.setSize(300, 300);
frame.setMinimumSize(new Dimension(300, 300));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public Q1() {
this.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
// This is only called when the user releases the mouse button.
System.out.println("componentResized");
}
});
}
#Override
public void validate() {
resize();
super.validate();
};
private void resize() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
System.out.println(width + "," + height);
}
}
This will print the size of the screen when your resize the frame, so you just need to add an if/else in the resize method to make frame bigger
OUTPUT
1366.0,768.0
1366.0,768.0
componentResized
1366.0,768.0
1366.0,768.0
componentResized
1366.0,768.0
1366.0,768.0
componentResized
A layout manager is an object that implements the LayoutManager
interface* and determines the size and position of the components
within a container. Although components can provide size and alignment
hints, a container's layout manager has the final say on the size and
position of the components within the container.
See the example I found using layout managers.Hope you get some idea.THe original author is here Set a layout manager like BorderLayout and then define more specifically, where your panel should go: like
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.See below example for full usage:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestLayoutManagers {
private JPanel northFlowLayoutPanel;
private JPanel southBorderLayoutPanel;
private JPanel centerGridBagLayoutPanel;
private JPanel westBoxLayoutPanel;
private JPanel eastGridLayoutPanel;
private final JButton northButton = new JButton("North Button");
private final JButton southButton = new JButton("South Button");
private final JButton centerButton = new JButton("Center Button");
private final JButton eastButton = new JButton("East Button");
private final JButton westButton = new JButton("West Button");
public TestLayoutManagers() {
northFlowLayoutPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
southBorderLayoutPanel = new JPanel(new BorderLayout());
centerGridBagLayoutPanel = new JPanel(new GridBagLayout());
eastGridLayoutPanel = new JPanel(new GridLayout(1, 1));
Box box = Box.createHorizontalBox();
westBoxLayoutPanel = new JPanel();
northFlowLayoutPanel.add(northButton);
northFlowLayoutPanel.setBorder(BorderFactory.createTitledBorder("Flow Layout"));
southBorderLayoutPanel.add(southButton);
southBorderLayoutPanel.setBorder(BorderFactory.createTitledBorder("Border Layout"));
centerGridBagLayoutPanel.add(centerButton);
centerGridBagLayoutPanel.setBorder(BorderFactory.createTitledBorder("GridBag Layout"));
eastGridLayoutPanel.add(eastButton);
eastGridLayoutPanel.setBorder(BorderFactory.createTitledBorder("Grid Layout"));
box.add(westButton);
westBoxLayoutPanel.add(box);
westBoxLayoutPanel.setBorder(BorderFactory.createTitledBorder("Box Layout"));
JFrame frame = new JFrame("Test Layout Managers");
frame.setLayout(new BorderLayout()); // This is the deafault layout
frame.add(northFlowLayoutPanel, BorderLayout.PAGE_START);
frame.add(southBorderLayoutPanel, BorderLayout.PAGE_END);
frame.add(centerGridBagLayoutPanel, BorderLayout.CENTER);
frame.add(eastGridLayoutPanel, BorderLayout.LINE_END);
frame.add(westBoxLayoutPanel, BorderLayout.LINE_START);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestLayoutManagers testLayoutManagers
= new TestLayoutManagers();
}
});
}
}
I have been trying to learn Buttons but it refuses to resize. Button1 (code below) just takes up the whole screen. I have seen other posts who's problem was that they didn't use
setMaximumSize();
but I'm using it and it still isn't working! I didn't make a JPanel yet. Here is my JFrame:
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame extends JFrame {
private JButton button1;
private JButton button2;
public Frame()
{
button1 = new JButton("Hello button1");
button2 = new JButton("Hello button2");
button2.setMaximumSize(new Dimension(100,100));
button1.setMaximumSize(new Dimension(100,100));
add(button2);
add(button1);
}
}
My main class is plain and simple:
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Panel extends JPanel{
public static void main(String args [])
{
Frame frame = new Frame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
It's because the frame('s contentPane) has a BorderLayout by default. You add the buttons to BorderLayout.CENTER, so the layout manager ignores the minimum-, preferred- and maximumSize.
I just want them to come up small and side by side
For that you could use a simple FlowLayout. (And if you want them to be centered on the frame, a parent JPanel with a GridBagLayout)
If you want a custom width & height for the buttons, override their getPreferredSize method. Overriding this method is safer than calling setPreferredSize.
Example:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Example {
public Example() {
JButton button1 = new JButton("Hello button1");
JButton button2 = new JButton("Hello button2") {
#Override
public Dimension getPreferredSize() {
int width = super.getPreferredSize().width;
return new Dimension(width, width);
}
};;
JPanel buttonPanel = new JPanel();
buttonPanel.add(button1);
buttonPanel.add(button2);
JPanel contentPanel = new JPanel(new GridBagLayout());
contentPanel.add(buttonPanel);
JFrame frame = new JFrame();
frame.setContentPane(contentPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
}
I added a flowlayout and changed setMaximumSize to setPreferredSize. That should fix your problem.
Here try this:
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame extends JFrame {
private JButton button1;
private JButton button2;
public Frame()
{
button1 = new JButton("Hello button1");
button2 = new JButton("Hello button2");
button2.setPreferredSize(new Dimension(100,100));
button1.setPreferredSize(new Dimension(100,100));
add(button2);
add(button1);
}
}
<----now the other class--->
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Panel extends JPanel{
public static void main(String args [])
{
Frame frame = new Frame();
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
There is a frame. There a panel in that frame with BoxLayout. In that panel there is a ScrollPane. There is another panel in ScrollPane with SpringLayout. There is a label in that inner panel.
Here is a code:
package test;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
class MainPanel extends JPanel {
MainPanel() {
JPanel panel = new JPanel();
BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(boxLayout);
panel.setBorder(BorderFactory.createLineBorder(Color.black));
JPanel innerPanel = new JPanel();
SpringLayout springLayout = new SpringLayout();
innerPanel.setLayout(springLayout);
JLabel label = new JLabel("test");
innerPanel.add(label);
springLayout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.WEST, innerPanel);
springLayout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH, innerPanel);
//innerPanel.setBorder(BorderFactory.createLineBorder(Color.black));
innerPanel.setPreferredSize(new Dimension(300, 100));
panel.add(innerPanel);
JScrollPane scrollPane = new JScrollPane(panel);
this.add(scrollPane);
}
}
class MainFrame extends JFrame {
MainFrame() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(new MainPanel());
this.pack();
this.setVisible(true);
}
}
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Label "test" is visible as expected. But when I add a border to inner panel (uncomment the line, see below) the label is disappeare.
//innerPanel.setBorder(BorderFactory.createLineBorder(Color.black));
Can someone explane why?
Try to change
innerPanel.setBorder(BorderFactory.createLineBorder(Color.black));
to
panel.setBorder(BorderFactory.createLineBorder(Color.black));
I hope that's what you meant to do & it fixed your problem :)
JPanel panel = new JPanel(new GridLayout(0,1));
JScrollPane contentpane = new JScrollPane(panel);
JButton add = new JButton("ADD");
add.actionListener(new ActionListener() {
public void actionPerformed(){
MyPanel newpanel = new MyPanel("title","Button"); //MyPanel is a class which extends JPanel and contains constructor MyPanel(String TitleToSet ,String ButtonTitleTOAdd)
panel.add(newpanel);
panel.repaint();
}) ;
I have used this code thinking that it will add the MyPanel to the grid layout dynamically and "panel" would be scrollable if more "MyPanel"s are added. However, this was not the case, 1st "MyPanel" filled whole "panel" and on adding second "MyPanel" (by clicking button "Add"), the 1st "MyPanel" was shrinked to make space for second one to be added.. and on adding more, all the "MyPanel"s were fit in the viewport instead of making the "panel" scrollable.. How to add those "MyPanel"s dynamically and making the "panel" scrollable on adding more of those?? Any help would be appreciated.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html :
By default JScrollPane uses ScrollPaneLayout to handle the layout of
its child Components. ScrollPaneLayout determines the size to make the
viewport view in one of two ways:
[...]
getPreferredSize is used.
You should add the line
panel.setPreferredSize(new Dimension(0, panel.getComponents().size() * SUB_PANEL_HEIGHT));
to your ActionListener.
Full example:
package main;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.Timer;
class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(400, 400));
frame.setSize(400, 400);
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("BOO"));
panel.add(new JButton("BBBB"));
JScrollPane contentpane = new JScrollPane(panel);
frame.add(contentpane);
new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel newpanel = new JPanel();
newpanel.add(new JLabel("LOL"));
panel.add(newpanel);
System.out.println(100 * panel.getComponents().length);
panel.setPreferredSize(new Dimension(0, 100 * panel.getComponents().length));
contentpane.validate();
}
}).start();
frame.setVisible(true);
}
}
Whenever I run my program my JTextArea does not follow the dimension that I have given it, but if I resize my JFrame it updates and sets its size to what I put.
What is the issue?
public ControlPanel() {
// create our list of players
list = new JList(model);
// create our scroll panes
userspane = new JScrollPane(list);
consolepane = new JScrollPane(console);
// set sizes
userspane.setSize(100, 500);
jta.setSize(100, 500);
list.setSize(100, 500);
consolepane.setSize(100, 500);
console.setSize(100, 500);
// add to panel
panel.add(userspane, BorderLayout.CENTER);
panel.add(kick);
panel.add(ban);
panel.add(info);
panel.add(consolepane, BorderLayout.CENTER);
// set frame properties
setTitle("RuneShadows CP");
setSize(280, 400);
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setContentPane(panel);
setVisible(true);
}
Don't set the sizes to anything.
For JTextArea you can use the constructor JTextArea(int rows, int charSpaces)
Just pack() the JFrame and it will respect all the preferred sizes of the components inside.
Also instead of setting the content pane to the panel, just add the panel. That will respect the preffered size of the panel when pack() is called
I'm not exactly sure what variable was what (or the sizes you wanted the), so I assumed text areas, and others as well. See this example where I just used the JTextArea constructor I mentioned and just packed.
EDITED with no sizes set
import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class ControlPanel extends JFrame {
JScrollPane userspane;
JList list;
DefaultListModel model = new DefaultListModel();
JScrollPane consolepane;
JTextArea console = new JTextArea(20, 50);
JTextArea jta = new JTextArea(6, 50);
JPanel panel = new JPanel();
JButton kick = new JButton("Kick");
JButton ban = new JButton("Ban");
JButton info = new JButton("Info");
public ControlPanel() {
// create our list of players
list = new JList(model);
// create our scroll panes
userspane = new JScrollPane(list);
consolepane = new JScrollPane(console);
// add to panel
panel.add(userspane, BorderLayout.CENTER);
panel.add(kick);
panel.add(ban);
panel.add(info);
panel.add(consolepane, BorderLayout.CENTER);
add(panel);
pack();
setTitle("RuneShadows CP");
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new ControlPanel();
}
});
}
}
UPDATE - with positioning
Keep in mind also, with BorderLayout you need to specify a position for every component you add or else it will default to CENTER and each position an only have one component. I noticed you trying to add two components to the CENTER
import java.awt.BorderLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class ControlPanel extends JFrame {
JScrollPane userspane;
JList list;
DefaultListModel model = new DefaultListModel();
JScrollPane consolepane;
JTextArea console = new JTextArea(20, 50);
JTextArea jta = new JTextArea(6, 50);
JPanel panel = new JPanel(new BorderLayout());
JButton kick = new JButton("Kick");
JButton ban = new JButton("Ban");
JButton info = new JButton("Info");
public ControlPanel() {
// create our list of players
list = new JList(model);
// create our scroll panes
userspane = new JScrollPane(list);
consolepane = new JScrollPane(console);
// add to panel
panel.add(userspane, BorderLayout.SOUTH);
JPanel buttonPanel = new JPanel();
buttonPanel.add(kick);
buttonPanel.add(ban);
buttonPanel.add(info);
panel.add(buttonPanel, BorderLayout.CENTER);
panel.add(consolepane, BorderLayout.NORTH);
add(panel);
pack();
setTitle("RuneShadows CP");
//setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new ControlPanel();
}
});
}
}