I've been having trouble recreating this GUI:
We've been told to use the BorderLayout with grids inside each section. I've been trying to head the header to work (the top square of the GUI with the class name and person name), but I can't seem to get anything to show up. This is what I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Display extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 350;
private static final int FRAME_X_ORIGIN = 100;
private static final int FRAME_Y_ORIGIN = 75;
public static void main(String[] args) {
Display frame = new Display();
frame.setVisible(true);
}
public Display() {
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setLayout(null);
setTitle("CSCE155A Course Offering Viewer");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// header
JPanel header = new JPanel();
header.setLayout(new GridLayout(2, 1));
header.setSize(380, 50);
header.setLocation(0, 0);
header.setBorder(BorderFactory.createLineBorder(Color.BLACK));
header.add(new JLabel("CSCE155A Course Offering Viewer"));
header.add(new JLabel("First Last"));
}
public void actionPerformed(ActionEvent event) {
}
}
The only thing that shows up is the window with nothing inside it.
We've been told to use the BorderLayout with grids inside each section
setLayout(null);
So why are you using a null layout on the frame?
Where do you add the panel to the frame?
You where given a link yesterday in your question: JPanels and GridLayouts to the Swing tutorial on How to Use a Border Layout. You where also given example code that showed you how to add the panel to the frame.
Read the tutorial, download the working example and then customize the example for your needs.
Don't keep repeating questions in the forum when you don't listen to previous advice!
I think you need to create a container-object where you can put your panels. Here I put two panels within a BorderLayout
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(inputPanel, BorderLayout.EAST);
contentPane.add(rightPanel, BorderLayout.CENTER);
Related
I am attempting to make a Chess game and while trying to work on the GUI, I encountered this issue:
I cannot seem to be able to vertically center my chess board on my JFrame. The JPanel is horizontally centered, but it is off-center, stuck to the top, vertically.
Code where the panel using GridLayout is added to its container and the frame is initialized:
public class ChessGUI extends JFrame
{
private static final long serialVersionUID = 1L;
private static Dimension appDimention = new Dimension(1000, 600);
public static JFrame frame = new JFrame("Chess");
public static JPanel background = new JPanel();
public static BoardGUI board = new BoardGUI();
public static int width;
public static int height;
public static void createFrame()
{
JFrame.setDefaultLookAndFeelDecorated(true);
//Set stuff that JFrame needs
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
//Set stuff that JPanel needs
background.setPreferredSize(appDimention);
frame.getContentPane().add(background);
frame.pack();
//This 'board' is my Chess Board JPanel which I can't seem to centre
//'background' is a JPanel which is, as the name suggests, the background
background.add(board);
//Set the location of the JFrame and set it visible
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
BoardGUI
#SuppressWarnings("serial")
public class BoardGUI extends JPanel
{
GridLayout chessBoard = new GridLayout(8, 8);
Dimension boardDims = new Dimension(500, 500);
public BoardGUI()
{
this.setLayout(chessBoard);
this.setBackground(Color.BLACK);
this.setPreferredSize(boardDims);
}
}
I'm not really doing anything in the code above to center the BoardGUI object, but I did tried the following two ways with negative results:
background.add(board, JPanel.CENTER_ALLIGNMENT)
background.add(board, BorderLayout.CENTER)
The result I'm getting at the moment:
As you can see it is not vertically centered, and my desired behavior is for it to be both horizontally and vertically centered on the frame.
Any help or insights on any mistakes I might be making would be very welcome! Thanks!
background is a JPanel which has a default layout of FlowLayout, which is where your problem is coming from.
I would change
public static JPanel background = new JPanel();
to
public static JPanel background = new JPanel(new GridBagLayout());
Suggestions...
Okay, so suggestions.
Avoid static, especially if all you want to do is access information from one class in another - there are better ways to achieve this that won't tightly couple your code
Avoid setPreferredSize - it's not a recommend way of defining custom sizing hints, override getPreferredSize instead, this prevents other people from changing it.
Instead of setting the preferredSize of the background panel, I would simple make use of either an EmptyBorder or the margins/inserts support of GridBagLayout
I have created my own version of a panel so I can create some dragable tables but at the moment nothing is being added on to the panel I have created
panel class:
import javax.swing.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.awt.Point;
public class Workspace extends JPanel implements MouseListener,MouseMotionListener{
private JTable t;
private DatabaseHandler d;
public Workspace(DatabaseHandler d ){
super();
this.d = d;
setPreferredSize(new Dimension(1000, 1000));
this.setLayout(null);
addMouseListener(this);
addMouseMotionListener(this);
}
public void load(String table){
t = new JTable(d.getTable(table));
//JScrollPane js=new JScrollPane(t);
this.add(t);
}
}
the code which calls it:
public class Display{
private JPanel leftPanel = new JPanel(new BorderLayout());
public JList list;
public JFrame frame;
private DatabaseHandler d = new DatabaseHandler("imdb");
private Workspace w = new Workspace(d);
public Display(){
//create the window
frame = new JFrame("FYP - Database Refactoring");
frame.getContentPane().add(w, BorderLayout.CENTER);
frame.setSize(1000,1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
list = new JList(d.getTableNames());
list.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
JList l = (JList)e.getSource();
w.load((String)l.getSelectedValue());
frame.setVisible(true);
}
});
leftPanel.add(list);
JLabel l = new JLabel("workbench");
w.add(l);
frame.getContentPane().add(leftPanel, BorderLayout.LINE_START);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new Display();
}
}
Any help would be appricated
Avoid null layouts, and in fact this one is messing you up, since with null layouts, you must fully specify call component sizes and locations. Just don't do it.
Don't re-add JTables in the MouseListener. Rather give your JPanel a JTable, and change its model from the MouseListener. Otherwise you're adding multiple JTables which doesn't make sense.
Put your JTable into a JScrollPane
And best to have your JPanel use BorderLayout and put the JScrollPane into the BorderLayout.CENTER position.
so I can create some dragable tables
If you need the ability to drag a JTable I would suggest that you should be using a JDesktopPane with JInternalFrames. You can easily drag an internal frame around the desktop. Then you just add the JTable\JScrollPane to the internal frame like you would to a normal JFrame.
Read the section from the Swing tutorial on How to Use Internal Frames for more information and working examples.
I am trying to place a JPanel on top of another JPanel which contains a JTextArea and a button and i want to the upper apnel to be transparent. I have tried it by making the setOpaque(false) of the upper panel. but it is not working. Can anyone help me to get through this? Thanks in advance!
public class JpanelTest extends JPanel
{
public JpanelTest()
{
super();
onInit();
}
private void onInit()
{
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JTextArea(100,100),BorderLayout.CENTER);
panel.add(new JButton("submit"),BorderLayout.SOUTH);
JPanel glass = new JPanel();
glass.setOpaque(false);
add(panel,BorderLayout.CENTER);
add(glass,BorderLayout.CENTER);
setVisible(true);
}
public static void main(String args[])
{
new JpanelTest();
}
}
Indeed, it would be useful to tell the reason why you want panels one over another.
Starting with your code, and changing it a lot, I got it to work, but it might not do what you expect...
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame
{
public Test()
{
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 200);
onInit();
setVisible(true);
}
private void onInit()
{
JLayeredPane lp = getLayeredPane();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JTextArea(), BorderLayout.CENTER);
panel.add(new JButton("Submit"), BorderLayout.SOUTH);
panel.setSize(300, 150); // Size is needed here, as there is no layout in lp
JPanel glass = new JPanel();
glass.setOpaque(false); // Set to true to see it
glass.setBackground(Color.GREEN);
glass.setSize(300, 150);
glass.setLocation(10, 10);
lp.add(panel, Integer.valueOf(1));
lp.add(glass, Integer.valueOf(2));
}
public static void main(String args[])
{
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Test();
}
});
}
}
If totally transparent, well, it is like it isn't here! When opaque, it just covers some of the GUI, but doesn't prevent mouse clicks, for example.
1) there are a few ways, there no issue to put JPanel, with covering full JFrames/JPanel area or only part of Rectangle / Dimension that returns JFrames/JPanel
use JLayer(Java7) based on JXLayer (Java6)
use GlassPane
use JViewport
use OverlayLayout
use transucent JDialog / JWindow
2) everything depends of if you want to protect against mouse and key events from the top layer to bottom, or not (to avoiding redispatch events from - to and vice versa)
Check out this tutorial on using Swing Root Panes.
The glass pane is useful when you want to be able to catch events or paint over an area that already contains one or more components. For example, you can deactivate mouse events for a multi-component region by having the glass pane intercept the events. Or you can display an image over multiple components using the glass pane.
I am really new to GUI programming in Java, I did a lot of research and I couldn't find an answer to this problem.
I have a simple JFrame with a menu, and inside this JFrame I have a JPanel with a log in form (were users input their username and password), and then I want to change that JPanel to another JPanel depending on what users want to do.
What would be the best way of doing this? I think that stacking JPanels is OK. But after I add new JLayeredPanels in Netbeans they don't stack. I read somewhere that I should use Z ordering or something like that, but I can't find it on the designer view.
Well, thank you very much for your patience!
CardLayout class has a useful API that can serve your requirements. Using methods like next(), first(), last() can be helpful.
I've prepared a simple demonstration of changing panels within a parent panel and/or frame.
Take a look at it:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelChanger implements ActionListener
{
JPanel panels;
public void init(Container pane)
{
JButton switcher = new JButton("Switch Active Panel!");
switcher.addActionListener(this);
JPanel login = new JPanel();
login.setBackground(Color.CYAN);
login.add(new JLabel("Welcome to login panel."));
JPanel another = new JPanel();
another.setBackground(Color.GREEN);
another.add(new JLabel("Yeah, this is another panel."));
panels = new JPanel(new CardLayout());
panels.add(login);
panels.add(another);
pane.add(switcher, BorderLayout.PAGE_START);
pane.add(panels, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent evt)
{
CardLayout layout = (CardLayout)(panels.getLayout());
layout.next(panels);
}
public static void main(String[] args)
{
JFrame frame = new JFrame("CardLayoutDemo");
PanelChanger changer = new PanelChanger();
changer.init(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
}
I am not able to use scroll bars with absolute layout in Swing.
I don't wish to use this layout but I have to display dynamic objects on my panel on click of a button and align them using setBounds which can be done using this layout only (I guess).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class clothes2 extends javax.swing.JFrame {
JTextField n=null;
JButton m=null;
public clothes2(){
initComponents();
}
public void initComponents() {
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
final JPanel jp = new JPanel();
contentPane.setPreferredSize(new Dimension(320,200));
jp.setLayout(null);
m=new JButton("add");
m.setBounds(0,0,50,50);
jp.add(m);
m.addMouseListener( new MouseAdapter() {
int x=0;
int y=0;
public void mouseClicked(MouseEvent me){
x+=100;
y+=100;
jp.add(n=new JTextField("Name"));
n.setBounds(x, y, 50, 50);
jp.add(n=new JTextField("code"));
x+=100;
n.setBounds(x,y, 50, 50);
jp.revalidate();
jp.repaint();
x=0;
}
});
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
JScrollPane jsp = new JScrollPane(jp, v, h);
contentPane.add(jsp, BorderLayout.CENTER);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f= new clothes2();
f.setVisible(true);
f.setSize(640,320);
}
});
}
}
Set preferred size of the container.
JScrollBar uses the preferred size of the component inside it to determine how large the scroll bars should be, and if they should be displayed.
Usually, the layout manager handles this using the preferredLayoutSize method. This can be overriden by explicitly setting the preferred size of the component.
So either you have to set the preferred size, or use a custom layout manager that calculates it for you.
see also here
might help you.
display dynamic objects .. which can be done using this layout only (I guess).
You guess wrong.
See this GUI, that can not only change PLAFs at run-time, but also dynamically add new components1. Click to..
Add Another Label
This example adds the new labels to a GridLayout - but the principle is the same for any layout (or any component).
add layout
jp.setLayout(new FlowLayout());