how do you customise position of a JPanel within a Jpanel - java

The class extends JPanel,
public void createDisplay(){
frame = new JFrame();
frame.setTitle(title);
frame.setSize(new Dimension(width, height));
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(width, height));
this.setMaximumSize(new Dimension(width, height));
this.setMinimumSize(new Dimension(width, height));
this.setLayout(null); //have tried default and BorderLayout
this.setSize(new Dimension(width, height));
this.setBounds(0, 0, width, height);
//basically trying everything
frame.add(this);
frame.pack();
}
on startup this code works fine and the JPanel completely covers the size of the Parent frame
However my program later tries to add a new JPanel to the class's extend JPanel with:
public void gameOverWindow(){ ;
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(200, 100));
JLabel label = new JLabel("Game Over");
label.setPreferredSize(new Dimension(40, 15));
//trying setPosition also doesn't work with BorderLayout or FlowLayout
JButton button_01 = new JButton("new");
button_01.setPreferredSize(new Dimension(100, 10));
JButton button_02 = new JButton("exit");
button_02.setPreferredSize(new Dimension(100, 10));
panel.add(label, BorderLayout.NORTH);
panel.add(button_01, BorderLayout.WEST);
panel.add(button_02, BorderLayout.EAST);
this.add(panel);
this.revalidate();
}
This new JPanel appears with the contents within the correct BorderLayout format, however the JPanel itself will remain at the top center of the extended JPanel, I know this is because the default Layout is set to FlowLayout, however setting this to BorderLayout will just cause the panel to take up the entire screen. Setting the Layout to null completely breaks the frame and nothing appears but the Minimize and Close buttons of the Frame. Trying to set the position or Bounds of this JPanel doesn't work with any Layout either. I have read a lot of other post online about this but they all seem to differ and become confusing, how do I gain control of the position of my new JPanel?

Normally I'd recommend using a CardLayout for switching between different views, but it's difficult to ascertain from the available information if that would help or not
Instead, you could make use of compounding layouts. That is wrap one container in another using different layouts.
In this example, I simply use a combination of BorderLayout and GridBagLayout
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
JButton gameOver = new JButton("Game over man");
gameOver.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel("Game Over Man", JLabel.CENTER), BorderLayout.NORTH);
panel.add(new JButton("New"), BorderLayout.WEST);
panel.add(new JButton("Exit"), BorderLayout.EAST);
removeAll();
JPanel inner = new JPanel(new GridBagLayout());
inner.add(panel);
add(inner);
revalidate();
repaint();
}
});
JPanel inner = new JPanel(new GridBagLayout());
inner.add(gameOver);
add(inner);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
what is the purpose of removing the components of a different panel instead of just directly adding it to GridBagLayout?
Because they interfere with the layout of other components.
i then want a small Jpanel to popup within and be unobtrusive
You could make use of the frame's glassPane or use a OverlayLayout
For example:
Floating JPanel above a JPanel with BorderLayout
Rectangle is not drawn on top
Placing a marker within the image
Display a message on the screen
Much of this information should have been in your original question, it would have wasted less of each other's time

Related

How do I adjust the button sizes and move them to be in a different place?

I'm trying to get some of the buttons to be bigger and be able to move them around to get them more to what my professor wants them to be but I'm not sure how to do it.
I decided to use a GridBagLayout but my professor never talked about it so I'm not sure if I'm missing anything or how exactly it works.
The image is what he wants us to get it too. Exactly like this.
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI {
public static JPanel buttonPanel;
private static JFrame frame;
public static void main(String[] args) {
frame = new JFrame("Layout Question");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
frame.add(mainPanel);
buttonPanel = new JPanel();
mainPanel.add(buttonPanel);
buttonPanel.add(new JButton("hi"));
buttonPanel.add(new JButton("long name"));
buttonPanel.add(new JButton("bye"));
buttonPanel.add(new JButton("1"));
buttonPanel.add(new JButton("2"));
buttonPanel.add(new JButton("3"));
buttonPanel.add(new JButton("4"));
buttonPanel.add(new JButton("5"));
buttonPanel.add(new JButton("6"));
buttonPanel.add(new JButton("7"));
buttonPanel.add(new JButton("Cancel"));
}
}
There are some improvements you can do to your code:
Don't use static variables, and place your program on the EDT, an easy way to do this is:
public static void main(String[] args) {
SwingUtilities.invokeLater(new LayoutManagersExample()::createAndShowGUI);
}
Don't call setSize(...) on your JFrame, it's going to make your window smaller than you think, it's taking the frame decorations into the calculation for the size, instead call frame.pack(), or override the getPreferredSize() of your JPanel, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for a more in-depth explanation.
Don't call frame.setVisible(true) before you've added all your components to your JFrame, otherwise you'll get strange bugs related to invisible components, that line should be the last one on your code.
Divide and conquer, you can use multiple JPanels with different Layout Managers, and you can combine them and join them together later on.
One possible approach (which isn't exactly as your teacher wants it to be but is close enough) is this one:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class LayoutManagersExample {
private JFrame frame;
private JPanel pane;
public static void main(String[] args) {
SwingUtilities.invokeLater(new LayoutManagersExample()::createAndShowGUI);
}
private void createAndShowGUI() {
frame = new JFrame("Layout Question");
pane = new JPanel();
JPanel topPanel = getTopPanel();
JPanel boxesPanel = getBoxesPanel();
JPanel buttonsPanel = getButtonsPanel();
pane.add(boxesPanel);
pane.add(buttonsPanel);
frame.add(pane);
frame.add(topPanel, BorderLayout.NORTH);
frame.add(new JButton("Cancel"), BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setSize(500, 500);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel getButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new GridLayout(2, 2));
buttonsPanel.add(new JButton("1"));
buttonsPanel.add(new JButton("2"));
buttonsPanel.add(getInnerButtonsPanel());
buttonsPanel.add(new JButton("7"));
return buttonsPanel;
}
private JPanel getInnerButtonsPanel() {
JPanel innerButtonsPanel = new JPanel();
innerButtonsPanel.setLayout(new GridLayout(2, 2));
innerButtonsPanel.add(new JButton("3"));
innerButtonsPanel.add(new JButton("4"));
innerButtonsPanel.add(new JButton("5"));
innerButtonsPanel.add(new JButton("6"));
return innerButtonsPanel;
}
private JPanel getBoxesPanel() {
JPanel boxesPanel = new JPanel();
boxesPanel.setLayout(new BoxLayout(boxesPanel, BoxLayout.PAGE_AXIS));
boxesPanel.add(new JCheckBox("Bold"));
boxesPanel.add(new JCheckBox("Italic"));
boxesPanel.add(new JCheckBox("Underline"));
boxesPanel.add(new JCheckBox("Strikeout"));
return boxesPanel;
}
private JPanel getTopPanel() {
JPanel topPanel = new JPanel();
JPanel topButtonsPanel = new JPanel();
topButtonsPanel.setLayout(new GridLayout());
topButtonsPanel.add(new JButton("hi"));
topButtonsPanel.add(new JButton("long name"));
topButtonsPanel.add(new JButton("bye"));
topPanel.add(new JLabel("Buttons: "));
topPanel.add(topButtonsPanel);
return topPanel;
}
}
Play around with the code, and try to find a different approach by combining the layouts, divide each piece of the window in your head and see how to apply a different layout manager to each of them, divide them in methods as I did to make things easier to follow.
Find a way to left align the elements in the JCheckBoxes for example, and other things

Issue getting a graphic triangle to show on my JPanel east in BorderLayout

I've made a GUI using swing with a BorderLayout and GridLayout in the center. I want to add a triangle I've made in another class to the JPanel east in my BorderLayout but cant get it to show.
When I set a bgcolor for said JPanel I got a weird little result, if you like you can have a look at the code: gistlink
I have a feeling the issue is in the TriGoButton constructor but I'm not sure how to test further. I've tried different variations of paint() but have never been able to see the green triangle.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
#SuppressWarnings("serial")
public class TestGUI extends JFrame implements ActionListener {
private JPanel content;
private JTextField placeTxtField;
public static void main(String[] args) {
TestGUI frame = new TestGUI();
frame.pack();
frame.setVisible(true);
}
#SuppressWarnings("rawtypes")
public TestGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
content = new JPanel();
content.setLayout(new BorderLayout());
setContentPane(content);
// issue
JPanel rightPanel = new JPanel();
content.add(rightPanel, BorderLayout.EAST);
rightPanel.add(new TriGoButton());
// issue?
JPanel leftPanel = new JPanel();
content.add(leftPanel, BorderLayout.WEST);
JPanel centerPanel = new JPanel();
content.add(centerPanel, BorderLayout.CENTER);
centerPanel.setLayout(new GridLayout(3, 3, 0, 20));
JLabel countyLbl = new JLabel("County");
centerPanel.add(countyLbl);
JComboBox countyDropDown = new JComboBox();
centerPanel.add(countyDropDown);
JLabel muniLbl = new JLabel("Munipalicity");
centerPanel.add(muniLbl);
JComboBox muniDropDown = new JComboBox();
centerPanel.add(muniDropDown);
JLabel placeLbl = new JLabel("City or place");
placeLbl.setToolTipText("search");
centerPanel.add(placeLbl);
placeTxtField = new JTextField();
centerPanel.add(placeTxtField);
placeTxtField.setColumns(15);
placeTxtField.setToolTipText("enter w/e");
JPanel bottomPanel = new JPanel();
content.add(bottomPanel, BorderLayout.SOUTH);
JButton goBtn = new JButton("Clicky");
bottomPanel.add(goBtn);
goBtn.setToolTipText("Please click.");
goBtn.addActionListener(this);
JPanel topPanel = new JPanel();
content.add(topPanel, BorderLayout.NORTH);
JLabel headlineLbl = new JLabel("headline");
topPanel.add(headlineLbl);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class TriGoButton extends JPanel {
public TriGoButton() {
add(new JPanel(), BorderLayout.EAST);
setBackground(new Color(100,100,250)); //blue //wtf
}
public void paint(Graphics g) {
super.paint(g);
int[]x={90,90,300};
int[]y={150,0,90};
g.setColor(new Color(23,201,10)); //green
g.fillPolygon(x,y,3);
}
}
EDIT:
////////////
I don't know why you are adding a JPanel to your TriGoButton class, but this is going to cause you issues.
It's not recommended that you override paint, this can cause no end of issues, as the parent container isn't always included in updates when it's children are painted. See Painting in AWT and Swing and Performing Custom Painting for more details.
BorderLayout will use the component's preferredSize tomake decisions about how it should sized. Your TriGoButton class should override the getPreferredSize method and return an appropriate default size..
I've added your code. I think that your issue is that your TriGoPanel doesn't override getPreferredSize, and so it may be sizing itself quite small. Consider adding to the class something like:
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
where you have int constants, PREF_W, PREF_H, for your width and height dimensions.
__________________________________________________
Edit: and I strongly second everything that MadProgrammer recommended!

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);
}
}
}

How to stop JTextArea from being placed on top of JTabbedPane?

I am trying to design a layout with a JTabbedPane at the top of the frame and then a jLogArea below the tabbed pane.
I am using this code:
setLayout(new BorderLayout());
tabbedPane.setSize(WIDTH, HEIGHT);
add(tabbedPane, BorderLayout.PAGE_START);
tabbedPane.add("Tab 0", null);
scrollableTextArea = new JScrollPane(jTextArea);
jTextArea.setEditable(false);
jTextArea.setLineWrap(true);
scrollableTextArea.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scrollableTextArea, BorderLayout.PAGE_END);
However, the result of this is that the text area is placed behind the tabbed pane:
Does anyone know what I am doing wrong and how I can fix it? Thanks.
EDIT: Just to be clear, I am looking for the text area to be below the JTabbedPane, not in the tab iself.
Using BorderLayout.NORTH and BorderLayout.SOUTH does not help either. I added a label into the tab's contents just to see if that would make a difference but the text area still goes behind, this is how it looks:
Further code (the class extends JFrame):
public MainGUI() {
init();
pack();
super.setTitle("test");
}
public void init() {
setLayout(new BorderLayout());
setPreferredSize(new Dimension(WIDTH, HEIGHT + TEXT_AREA_HEIGHT));
setMaximumSize(new Dimension(WIDTH, HEIGHT + TEXT_AREA_HEIGHT));
setMinimumSize(new Dimension(WIDTH, HEIGHT + TEXT_AREA_HEIGHT));
tabbedPane = new JTabbedPane();
textArea = new JTextArea(WIDTH, TEXT_AREA_HEIGHT);
scrollableTextArea = new JScrollPane(textArea);
JLabel testLabel = new JLabel("Test!");
tabbedPane.add("Tab 0", testLabel);
tabbedPane.setBorder(null);
tabbedPane.setSize(WIDTH, HEIGHT);
add(tabbedPane, BorderLayout.NORTH);
textArea.setEditable(false);
textArea.setLineWrap(true);
scrollableTextArea.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scrollableTextArea, BorderLayout.SOUTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
UPDATE I think you are looking for something like this:
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
public class TabSample extends JFrame{
public void createAndShowGUI() {
JPanel panel = new JPanel();
JTextArea ta = new JTextArea(100,50);
JScrollPane jsp = new JScrollPane(ta);
JTabbedPane tabbedPane = new JTabbedPane();
panel.setLayout(new BorderLayout());
tabbedPane.addTab("Tab one", panel);
JSplitPane vPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tabbedPane, jsp);
getContentPane().add(vPane);
setSize(400,500);
vPane.setDividerLocation(getHeight()/2);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[])
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
TabSample ts = new TabSample();
ts.createAndShowGUI();
}
});
}
}
Your code should be like this:
setLayout(new BorderLayout());
tabbedPane.setSize(WIDTH, HEIGHT);
add(tabbedPane, BorderLayout.PAGE_START);
scrollableTextArea = new JScrollPane(jTextArea);
jTextArea.setEditable(false);
jTextArea.setLineWrap(true);
scrollableTextArea.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollableTextArea.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
tabbedPane.addTab("Tab 0", scrollableTextArea);
The problem in your code was that you added the JScrollPane at the same level as you added your JTabbedPane. Actually your JScrollPane has to be a tab component:
tabbedPane.addTab("Tab 0", scrollableTextArea);
EDIT: to have the scroll pane below the tabbed pane:
...
add(tabbedPane, BorderLayout.NORTH);
...
add(scrollableTextArea, BorderLayout.SOUTH);
Hope this works for you.

Centering Panel in Java

For some reason i am having problems centering my panel vertically that is located inside another panel. I do exactly as the examples i studied but still no luck.
Down there is my code. Despite using setAlignmentY(0.5f) on my container panel, it still wont center when i resize the window.
Also the components inside container panel wont center either, despite setAligenmentX(0.5f).
I wonder if there is a solution for this, I pretty much tried everything out there but couldnt find a solution.
JLabel idLabel;
JLabel passLabel;
JTextField id;
JTextField pass;
JButton enter;
JPanel container;
public JournalLogin()
{
//setLayout(new FlowLayout());
//setPreferredSize(new Dimension(500, 500));
//setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
container = new JPanel();
container.setLayout(new MigLayout());
container.setAlignmentX(0.5f);
container.setAlignmentY(0.5f);
container.setPreferredSize(new Dimension(300, 300));
container.setBorder(BorderFactory.createTitledBorder("Login"));
add(container);
idLabel = new JLabel("ID:");
idLabel.setAlignmentX(0.5f);
container.add(idLabel);
id = new JTextField();
id.setText("id");
id.setAlignmentX(0.5f);
id.setPreferredSize(new Dimension(80, 20));
container.add(id, "wrap");
setAlignmentX and Y are not the way to go about doing this. One way to center a component in a container is to have the container use GridBagLayout and to add the component without using any GridBagConstraints, a so-called default addition. There are other ways as well.
For example to alter Nick Rippe's example (1+ to him):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.*;
public class UpdatePane2 extends JPanel {
private static final int PREF_W = 300;
private static final int PREF_H = 200;
public UpdatePane2() {
JPanel innerPanel = new JPanel();
innerPanel.setLayout(new BorderLayout());
innerPanel.add(new JLabel("Hi Mom", SwingConstants.CENTER),
BorderLayout.NORTH);
innerPanel.add(new JButton("Click Me"), BorderLayout.CENTER);
setLayout(new GridBagLayout());
add(innerPanel);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("UpdatePane2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new UpdatePane2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Alignments tend to be pretty picky in Swing - they do [usually] work... but if all you're looking for is a panel that's centered, I'd recommend using Boxes in the BoxLayout (My personal favorite LayoutManager). Here's an example to get you started:
import java.awt.Dimension;
import javax.swing.*;
public class UpdatePane extends JPanel{
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
//Create Buffers
Box verticalBuffer = Box.createVerticalBox();
Box horizontalBuffer = Box.createHorizontalBox();
verticalBuffer.add(Box.createVerticalGlue()); //Top vertical buffer
verticalBuffer.add(horizontalBuffer);
horizontalBuffer.add(Box.createHorizontalGlue()); //Left horizontal buffer
//Add all your content here
Box mainContent = Box.createVerticalBox();
mainContent.add(new JLabel("Hi Mom!"));
mainContent.add(new JButton("Click me"));
horizontalBuffer.add(mainContent);
horizontalBuffer.add(Box.createHorizontalGlue()); //Right horizontal buffer
verticalBuffer.add(Box.createVerticalGlue()); //Bottom vertical buffer
// Other stuff for making the GUI
verticalBuffer.setPreferredSize(new Dimension(300,200));
JFrame frame = new JFrame();
frame.add(verticalBuffer);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
You will need to get the LayoutManager to center the layout for you. Currently it looks like the implementation of "MigLayout" does not honor the Alignment. Try changing it or creating a subclass.

Categories

Resources