Trying to put button and using center mode - java

Im trying to make a option menu to be able to choose flags to be displayed, Im trying to put the tailand button on the left down corner and it seems it does not want to budge.
import java.awt.*;
import javax.swing.*;
public class Flags {
public static void startup() {
Dimension d = new Dimension(400,300);
JFrame menu = new JFrame("Flag Menu");
menu.setResizable(true);
JButton tailand = new JButton("Tailand");
JPanel tailandPanel = new JPanel();
tailand.setLayout(null);
tailandPanel.setLayout(null);
tailand.setBounds(300,100,100,600);
tailandPanel.add(tailand);
menu.add(tailandPanel);
tailandPanel.setBackground(Color.LIGHT_GRAY);
tailand.setBackground(Color.WHITE);
tailandPanel.setPreferredSize(d);
tailand.setPreferredSize(d);
tailandPanel.setLocation(1, 1);
tailand.setLocation(1, 1);
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setLocationRelativeTo(null);
menu.setSize(600, 400);
menu.setResizable(false);
menu.setVisible(true);
menu.setLocationRelativeTo(null);
}
}
I have tried tailand.setPreferredSize(d); and tailandpanel.setPreferredSize(d); but no luck.
Also Is their a way to use center mode? (Eg. Give 300,200 and the center of the button would be their?)

Don't use null layouts
Don't use setPreferredSize(...)
Swing was designed to be used with layout managers
For example:
JButton button = new JButton( "Tailand" );
JPanel left = new JPanel( new BorderLayout() );
left.setBackground( Color.WHITE );
left.add(button, BorderLayout.PAGE_END);
JFrame frame = new JFrame("Flag Menu");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frane.setLocationRelativeTo(null);
frame.add(left, BorderLayout.LINE_START);
frame.setSize(600, 400);
frame.setVisible(true);
Read the section from the Swing tutorial on Layout Manager for more information and example of using each layout manager.

Related

How to add two JPanels to a JFrame in the center?

I am creating a game which has a background image with cards displayed overtop. I would like to place the background image and cards such that they're always centered vertically and horizontally, even upon resizing the JFrame.
Currently, I am creating the cards (each a JPanel) and adding them into a container JPanel (no layout manager), then I add that Jpanel to the JFrame. After that I place the background image in a JPanel, then add that JPanel to the JFrame. The result is: The background image is hidden behind the cards and revealed when removing each card as desired. The background image is always centered but the card's JPanel does not move around upon resize. I am having a hard time getting the cards to always be centered, no matter what I try. I also need to add another JPanel to the JFrame in the South border, so that will need to work as well. I appreciate your assistance!
In the class that extends JFrame:
setSize(1060,700);
cardPanel = new JPanel();
cardPanel.setSize(1060,700);
cardPanel.setOpaque(false);
cardPanel.setLayout(null);
...card.setLocation(x, y); //loop through cards
...cardPanel.add(card); //and add each one
add(cardPanel, BorderLayout.CENTER); //add cardPanel to JFrame
//Add background image
bgPanel = new JPanel();
URL url = getClass().getResource("images/dragon_bg.png");
imgIcon = new ImageIcon(url);
JLabel background = new JLabel(imgIcon);
bgPanel.setLayout(new BorderLayout());
bgPanel.add(background);
add(bgPanel, BorderLayout.CENTER);
setVisible(true);
I would like to place the background image and cards such that they're always centered vertically and horizontally, even upon resizing the JFrame.
Then you need to use layout managers on your panels. The layout manager is responsible for redoing the layout.
How to add two JPanels to a JFrame in the center?
You could try using the OverlayLayout for this. I think the basic code would be:
JPanel contentPane = new JPanel( new GrigBagLayo9ut() );
frame.add(contentPane, BorderLayout.CENTER);
JPanel overlay = new JPanel()
overlay.setLayout( new OverlayLayout(overlay) );
contentPane.add(overlay, new GridBagConstraints()); // this should center the overlay panel
overlay.add(yourCardPanel); // you care panel must use a suitable layout
overlay.add(new JLabel() ); // use a JLabel for the background not a custom panel
I also need to add another JPanel to the JFrame in the South border,
The default layout manager for a JFrame's content pane is a BorderLayout. We already added the game panel to the center, so know you just add your other panel to the SOUTH.
If the OverlayLayout doesn't work the way you want then you will need to nest panels. Something like:
JPanel center = new JPanel( new GridBagLayout() );
frame.add(center, BorderLayout.CENTER);
JLabel background = new JLabel(...);
background.setLayoutManager( new GridBagLayout() );
center.add(background, new GridBagConstraints());
background.add(yourCardPanel, new GridBagConstraints());
Edit:
Using nested panels:
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutCenter extends JPanel
{
public GridBagLayoutCenter()
{
setLayout( new BorderLayout() );
JLabel background = new JLabel( new ImageIcon("mong.jpg") );
background.setLayout( new GridBagLayout() );
add(background, BorderLayout.CENTER);
JPanel tiles = new JPanel();
tiles.setPreferredSize( new Dimension(200, 200) );
tiles.setBackground( Color.RED );
background.add(tiles, new GridBagConstraints());
add(new JLabel("SOUTH"), BorderLayout.SOUTH);
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("GridBagLayoutCenter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new GridBagLayoutCenter() );
frame.setSize(400, 400);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
The preferred size of the "tiles" panel should not be hardcoded. The size should be determined by your custom layout manager based on the tiles that you add to the panel. The size should not change as tiles are removed.
I ultimately decided to place the background image in the card panel itself, then put the card panel in a box layout manager so that it's always centered. I renamed cardPanel to gameBoard. Definitely could be cleaner, but I can only work with my requirements.
setSize(new Dimension(1000, 600));
gameBoard = new JPanel();
gameBoard.setLayout(null);
gameBoard.setOpaque(false);
Dimension expectedDimension = new Dimension(920, 500);
gameBoard.setPreferredSize(expectedDimension);
gameBoard.setMaximumSize(expectedDimension);
gameBoard.setMinimumSize(expectedDimension);
//add cards to gameBoard here
JLabel background = new JLabel( new ImageIcon( getClass().getResource("images/graphic.png") ) );
background.setLocation(79,0); //manually center graphic
background.setBounds(new Rectangle(0, 0, 920, 500));
gameBoard.add(background);
Box centerBox = new Box(BoxLayout.Y_AXIS);
centerBox.setOpaque(true);
centerBox.setBackground(Color.WHATEVER);
centerBox.add(Box.createVerticalGlue());
centerBox.add(gameBoard);
centerBox.add(Box.createVerticalGlue());
add(centerBox);
setVisible(true);

JFrame setComponentZOrder() changes size of the objects

I'm trying to write an undecorated JFrame. I'm trying to put my button over my background label. However setting the button's Z order causes the button streches to size of jframe and neither setBounds() nor setSize() changes the situation. Here is my code:
import javax.swing.*;
public class MyApp {
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
mainFrame.setBounds(0, 112, 100, 50);
mainFrame.setLayout(null);
mainFrame.setUndecorated(true);
JLabel lblBackground = new JLabel(new ImageIcon(JFrame.class.getResource("/res/green.png")));
lblBackground.setBounds(0, 0, 100, 50);
JButton btnStart = new JButton("");
btnStart.setBounds(5, 15, 10, 15);
mainFrame.add(lblBackground);
mainFrame.add(btnStart);
mainFrame.setComponentZOrder(btnStart, 0);
mainFrame.setComponentZOrder(btnStart, 1);
mainFrame.setVisible(true);
}
}
Thanks for replies.
Use a JLayeredPane for this.
You will need to create a new JLayeredPane:
JLayeredPane layered = new JLayeredPane();
Set your JFrame to use this as a content pane:
mainFrame.setContentPane(layered);
And add your components, in this format:
layered.add(Component c, int layerNumber);
Hope that works for you!
More on JLayeredPanes
Don't play with null layouts. Swing was designed to be used with layout managers
Add the button to the label. For example:
JLabel label = new JLabel(...);
label.setLayout( new FlowLayout() );
JButton button = new JButton(...);
label.add( button );
frame.add(label);
frame.pack();
frame.setVisible(true);
Now the frame should be the same size as your image. The button should be centered on the top of the image. If you want the button positioned somewhere else then use a different layout manager.

Java setBounds not working with JPanel

i am doing a small Gui in java. i am using setBounds methods to set the position of buttons etc on my JFrame , but problem is that when i use it with JPanel button is not visible on JFrame , and without JPanel its quite ok ,, see both the codes and please help me as i am beginner and facing these foolish problems .
This one is working fine
JFrame jframe = new JFrame("Working Fine");
jframe.setLayout(null);
JButton jbutton = new JButton("Position Test");
jbutton.setBounds(0, 0, 100, 100);
jframe.add(jbutton);
jframe.setSize(300,300);
jframe.setVisible(true);
Same code when i add Button to Jpanel then it does not work so whats wrong , please guide me
JFrame jframe = new JFrame("causing problem ");
jframe.setSize(300,300);
JPanel p = new JPanel();
jframe.setLayout(null);
JButton jbutton = new JButton("Position Test");
jbutton.setBounds(0, 0, 100, 100);
jframe.add(p);
p.add(jbutton);
p.setVisible(true);
//jframe.add(jbutton);
jframe.setVisible(true);
please help me in this small problem
You must get rid of the JPanel's layout, in order to set absolute positions:
p.setLayout(null);
The problem is that when you use absolute positioning, the JPanel component has no default size so does not appear. To get it to appear you could do
JFrame frame = new JFrame("No Problem");
JPanel panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
};
};
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton button = new JButton("Position Test");
panel.add(button);
frame.add(panel);
frame.pack();
frame.setVisible(true);
From Doing Without a Layout Manager
Although it is possible to do without a layout manager, you should use a layout manager if at all possible. A layout manager makes it easier to adjust to look-and-feel-dependent component appearances, to different font sizes, to a container's changing size, and to different locales.
The choice of layout manager will depend on how you wish to lay out the components.
See A Visual Guide to Layout Managers.

Swing: Showing a transparent Panel hovering over another Panel

I want to show a textArea showing some text (will show log lines) , and have an animated gif hoovering above it. I tried the solution described here , but all I get is a grey screen. Hints?
public class TestLayeredPanes {
private JFrame frame = new JFrame();
private JLayeredPane lpane = new JLayeredPane();
public TestLayeredPanes() {
frame.setPreferredSize(new Dimension(600, 400));
frame.setLayout(new BorderLayout());
frame.add(lpane, BorderLayout.CENTER);
//Build the animated icon
JLabel buildingIcon = new JLabel();
buildingIcon.setIcon(new ImageIcon(this.getClass().getResource(
"/com/ct/tasks/cmviewer/gui/progress_bar.gif")));
JPanel iconPanel = new JPanel();
iconPanel.add(buildingIcon);
//Build the textArea
JTextArea textLog = new JTextArea("Say something");
JPanel textPanel = new JPanel();
textPanel.add(new JScrollPane(textLog));
//Add the panels to the layered pane
lpane.add(textPanel, 0);
lpane.add(iconPanel, 1);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new TestLayeredPanes();
}
}
Try putting your animated GIF on the glass pane of your root pane:
http://download.oracle.com/javase/tutorial/uiswing/components/rootpane.html
JXLayer make easier to do that. Look at JXLayer samples.
You also can take a look at code of XSwingX
Since you started with a working example, why did you remove lines of code from the example you copied?
Layered panes don't use a layout manager therefore the size of your components are (0, 0), so there is nothing to display. The setBounds(...) method in the example are there for a reason.

Addin a JLabel in a frame?

I have created a JFrame, and now I want to add a JLabel and textfields in it. Please tell me how to do that. I have used the following code but its not working.
JFrame i_frame = new JFrame("Select Locations");
i_from = new JLabel("From");
i_frame.getContentPane().add(i_from);
i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
Problem is this code is showing frame window but it is not showing label in it. Please help.
That's your first question, later you'll ask:
How do I get the value from my text field
So, I suggest you to take a look at this tutorial
http://java.sun.com/docs/books/tutorial/uiswing/start/index.html
And ask us if you have questions from that tutorial. Using an IDE will simplify your life.
Here's a start anyway:
Code:
import javax.swing.*;
import java.awt.Color;
public class MyApp {
public static void main( String [] args ) {
JFrame frame = new JFrame();
frame.setBackground( new Color(0,0,0,64 ));
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel top = new JPanel();
top.add( new JLabel("What is your name"){{
setForeground(Color.white);
}});
top.add( new JTextField(10) );
frame.add( top );
frame.pack();
frame.setVisible( true );
}
}
EDIT
Dismiss this answer. It was posted when the question was rather ambiguous. I'm leaving it as CW for it may be helpful.
plus OSX frames with alpha background are too cool!
The main issue is the layout being used by the content pane (most likely JRootPane.RootLayout, A custom layout manager that is responsible for the layout of layeredPane, glassPane, and menuBar ) is not the best. This code should work;
JFrame i_frame = new JFrame("Select Locations");
JLabel i_from = new JLabel("From");
i_frame.getContentPane().setLayout(new FlowLayout());
i_frame.getContentPane().add(i_from);
i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
setting a different layout does the trick
The problem is that you are adding a second component (Box.createRigidArea) in the same layout position (BorderLayout.CENTER) as the Label.
JFrame.add() results in the same as JFrame.getContentPane().add()...
So the label is being replaced by the RigidArea.
Try this:
JFrame i_frame = new JFrame("Select Locations");
i_from = new JLabel("From");
i_frame.getContentPane().add(i_from);
// i_frame.add(Box.createRigidArea(new Dimension(2,0)));
i_frame.setLocationRelativeTo(null);
i_frame.setSize(200,200);
i_frame.setVisible(true);
to add more components, change the LayoutManager:
JFrame i_frame = new JFrame("Select Locations");
JLabel i_from = new JLabel("From");
Container pane = i_frame.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS)); // any LayoutManager you need
pane.add(i_from);
pane.add(Box.createRigidArea(new Dimension(2,0))); // space after JLabel ?
i_frame.setSize(200,200); // better done before setLocationRelativeTo
i_frame.setLocationRelativeTo(null);
i_frame.setVisible(true);
Note: if you "just" want to add an empty border to your label, use a setBorder() instead of the RigidArea:
i_from.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
[]]
For adding JLabel to JFrame see the line of code see here
public class JLabelExample extends JFrame {
JLabel jLabel;
public JLabelExample() {
jLabel = new JLabel();
jLabel.setText("tutorialData.com");
jLabel.setForeground(Color.BLUE);
this.add(jLabel);
}
public static void main(String a[]) {
JLabelExample labelExample = new JLabelExample();
labelExample.setSize(250, 200);
labelExample.setTitle("tutorialData.com");
labelExample.setVisible(true);
}
}
Please refer more on JFrame

Categories