Cannot set the location for java widget - java

The problem is that I can't position the button where I want to. So I wrote this code to set again the location:
button.setLocation(new Point(100, 60));
import javax.swing.*;
import java.awt.*;
public class gui {
public static void main(String [] args){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.ORANGE);
frame.add(panel);
JButton button = new JButton("Button");
button.setPreferredSize(new Dimension(200,25));
button.setLocation(new Point(100, 60));
panel.add(button);
frame.setSize(new Dimension(500,400));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("GUI App");
frame.setResizable(false);
frame.setVisible(true);
}
}

You have to use the method setBounds()! This method requires 4 parameters: The x & y coordinate and the width and height your button should have. Also you have to set the Layout to null... So try this:
button.setBounds(100, 60, 100, 50) //just an example
frame.setLayout(null)

add below to your component:
//JPanel layout
panel.setLayout(null);
// postioning
button.setLocation(100,60);
As panel.setLayout(null) set your content panel to use absolute layout. Which you'd always have to set your component's bounds explicitly by using setBounds method.
Better to choose here the most suitable layout than using absolute layout.
ex:panel.setLayout(new FlowLayout());

Related

How to add scrollbar automatic in jscrollpane?

I try to program a GUI like this. When a button clicked every time a new button is created and placed at specific position but after adding some buttons in jscrollpane, scrollbar not activated, so I unable to see all created buttons.
My code is here:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test{
private JFrame frame;
private JPanel panel1,panel2;
private JScrollPane pane;
private JButton button;
int i = 1, y = 10;
public Test()
{
panel2 = new JPanel(null);
panel2.setBounds(0,0,280,300);
button = new JButton("Add Button");
button.setBounds(90,10,120,30);
pane = new JScrollPane();
pane.setBounds(10,50,280,300);
panel1 = new JPanel(null);
panel1.setPreferredSize(new Dimension(300,400));
panel1.setBackground(Color.WHITE);
frame = new JFrame("Test");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1);
frame.pack();
panel1.add(pane);
panel1.add(button);
pane.add(panel2);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panel2.add(new JButton("Button "+i)).setBounds(80,y,120,30);
i += 1;
y += 35;
}
});
}
public static void main(String[] args) {
new Test();
}
}
Don't use a null layout. Don't use setBounds().
The scrollbars will only appear automatically when the preferred size of the panel is greater that the size of the scroll pane.
It is the job of the layout manager to:
set the location of a component
set the size of a component
calculate the preferred size of the panel.
So the solution is to use the appropriate layout manager on your panel.
So for example you can use a BoxLayout:
//panel2 = new JPanel(null);
panel2 = new JPanel();
panel2.setLayout( new BoxLayout(panel2, BoxLayout.Y_AXIS) );
And then when you add components to a visible frame you need to revalidate() the panel to invoke the layout manager:
//panel2.add(new JButton("Button "+i)).setBounds(80,y,120,30);
panel2.add(new JButton("Button "+i));
panel2.revalidate();
There is no need for panel1. Just add the components to the frame:
//panel1.add(pane);
//panel1.add(button);
frame.add(button, BorderLayout.PAGE_START);
frame.add(pane, BorderLayout.CENTER);
But there are other issues:
pane = new JScrollPane();
You actually need to add the panel to the scroll pane. So the code should be:
pane = new JScrollPane(panel2);
Since a component can only have a single parent, you need to remove:
pane.add(panel2);
Since the panel2 has been added to the scroll pane.
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1);
frame.pack();
The above logic is wrong.
You should only invoked pack() and setVisible( true ) AFTER all the component have been added to the frame.
So most of the code posted is wrong.
Start by reading the section from the Swing turtorial on Layout Managers. Download the working demo code and learn how to better structure your code. The modify the code for your specific example.

Java Graphics AWT

When I run the below code, I am unable to see the background color as red. It's showing default one. Is there anything that I have to add to these lines?
import java.awt.*;
import java.awt.Graphics;
import javax.swing.*;
public class gfix extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(80, 100, 150, 75);
}
public static void main(String[] args){
gfix gg=new gfix();
JFrame frame = new JFrame("RISK");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(null);
frame.add(panel);
JButton button = new JButton("test");
button.setBounds(100, 100, 150, 150);
panel.add(button);
frame.setVisible(true);
}
}
Your are overriding painGraphics() in gfix class so add gfix class object into your frame not Java provided JPanel class object.
gfix gg=new gfix();
JFrame frame = new JFrame("RISK");
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel panel = new JPanel(); Not needed
//panel.setLayout(null);
frame.add(gg);
JButton button = new JButton("test");
button.setBounds(100, 100, 150, 150);
gg.add(button);
frame.setVisible(true);
for g.fillRect(80, 100, 150, 75); give proper panel bounds to fill complete panel background. OR use int width = getWidth();
int height = getHeight(); in paintGraphics to get actual height and width.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class gfix {
public static void main(String[] args) {
JFrame frame = new JFrame("RISK");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
frame.add(panel);
JButton button = new JButton("test");
// adjust numbers as needed
button.setMargin(new Insets(20,40,20,40));
panel.add(button);
// adjust numbers as needed
panel.setBorder(new EmptyBorder(10,40,50,200));
frame.pack();
frame.setVisible(true);
}
}
Other tips:
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Provide ASCII art or a simple drawing of the intended layout of the GUI at minimum size, and if resizable, with more width and height - to show how the extra space should be used.
Please learn common Java nomenclature (naming conventions - e.g. EachWordUpperCaseClass, firstWordLowerCaseMethod(), firstWordLowerCaseAttribute unless it is an UPPER_CASE_CONSTANT) and use it consistently.

How to set size and location of JTextField?

I want to set location and size of my JTextField, how can I do it ? My code doesn't work.
public static void main(String[] args) {
JTextField txt1;
JFrame frame = new JFrame("Hangman");
frame.setSize(1100, 600);
frame.getContentPane().setLayout(new FlowLayout());
frame.setResizable(false);
frame.getContentPane().setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt1 = new JTextField(50);
txt1.setSize(200, 199);
txt1.setLocation(400, 200);
frame.add(txt1);
frame.setVisible(true);
}
txt1.setSize and txt1.setLocaiton doesn't work.
Output
Absolute positioning doesn't work with a layout manager.
If you really need it, you will have to set null as a layout manager, i.e :
frame.getContentPane().setLayout(null);

Strange JFrame size

So I set the setSize(500,500).. add some panels, the sum of panels Y is 500 like the JFrame but executing it shows an count Y of 525 am I missing something?
JPanel panel = new JPanel();
panel.setLayout(null);
getContentPane().add(panel);
//--------------------
JPanel top_panel = new JPanel();
top_panel.setLayout(null);
top_panel.setBackground(Color.blue);
top_panel.setBounds(0, 0, 500, 40);
panel.add(top_panel);
//------------------------------
JPanel middle_panel = new JPanel();
middle_panel.setLayout(null);
middle_panel.setBackground(Color.yellow);
middle_panel.setBounds(0, 40, 500, 385);
panel.add(middle_panel);
//-----------------------------
JPanel bottom_panel = new JPanel();
bottom_panel.setLayout(null);
bottom_panel.setBackground(Color.black);
bottom_panel.setBounds(0, 425, 500, 75);
panel.add(bottom_panel);
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
40+385+75 = 500 but to show all the panels i must
setSize(500,525);
then it fits
here's an image:
The frame size is the light blue rectangle outside bounds including the title bar. Your panels are appearing in the inner bounds which is frame size less than the frame border and frame title bar. Do you see how your marked space at the bottom is strangely the same height as the title bar?
After adding your panels/component to the frame and just before calling frame.setVisible(true), call frame.pack().
It would be also preferable if you embrace a layout manager (such as FlowLayout) and when necessary call setPreferredSize and let the layout manager do the layout. Normally one would call setPreferredSize over setBound, setSize, setMininumSize, setMaximumSize.
import javax.swing.*;
import java.awt.*;
public class FrameSize {
private JFrame frame;
FrameSize create() {
frame = createFrame();
frame.getContentPane().add(createContent());
return this;
}
private JFrame createFrame() {
JFrame frame = new JFrame(getClass().getName());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return frame;
}
void show() {
// frame.setSize(500, 500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
private Component createContent() {
JPanel panel = new JPanel(null);
JPanel topPanel = new JPanel(null);
topPanel.setBackground(Color.blue);
topPanel.setBounds(0, 0, 500, 40);
panel.add(topPanel);
JPanel middlePanel = new JPanel(null);
middlePanel.setBackground(Color.yellow);
middlePanel.setBounds(0, 40, 500, 385);
panel.add(middlePanel);
JPanel bottomPanel = new JPanel(null);
bottomPanel.setBackground(Color.black);
bottomPanel.setBounds(0, 425, 500, 75);
panel.add(bottomPanel);
panel.setPreferredSize(new Dimension(500, topPanel.getBounds().height + middlePanel.getBounds().height + bottomPanel.getBounds().height));
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new FrameSize().create().show();
}
});
}
}
You shouldn't be setting size or calling setSize(...) or setBounds(...) as that's setting you up for similar problems in the future, or worse problems when you try to show your GUI on a different platform. Instead let the preferredSizes of your components and the layout managers do this work for you. If you absolutely must set the size of a component, then override getPreferredSize() and return a Dimension that is calculated to work for you. And yes, as per javajon, you should call pack() on the JFrame before displaying it.
For more discussions on the null layout, please read what one of the best Swing experts on this site, MadProgrammer, has to say in his answer here.

How to place an object in a specific location (x,y) on a JFrame?

How can I place an object in a specific location (x,y) on a JFrame?
Here find the Absolute Positioning Tutorials. Please do read carefully, as to why this approach is discouraged over using LayoutManagers
To add say a JButton to your JPanel, you can use this :
JButton button = new JButton("Click Me");
button.setBounds(5, 5, 50, 30);
panel.add(button);
Here try this example program :
import java.awt.*;
import javax.swing.*;
public class AbsoluteLayoutExample
{
private void displayGUI()
{
JFrame frame = new JFrame("Absolute Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
JLabel label = new JLabel(
"This JPanel uses Absolute Positioning"
, JLabel.CENTER);
label.setSize(300, 30);
label.setLocation(5, 5);
JButton button = new JButton("USELESS");
button.setSize(100, 30);
button.setLocation(95, 45);
contentPane.add(label);
contentPane.add(button);
frame.setContentPane(contentPane);
frame.setSize(310, 125);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new AbsoluteLayoutExample().displayGUI();
}
});
}
}
Try these 2... in combination with each other...
setLocation() and setBounds()
Its even better to use GroupLayout, developed by NetBeans team in 2005. WindowsBuilder Pro is a good tool for Building Gui in java
Check out this absolute layout code sample:
Absolute Layout demo
In the class inheriting the frame:
setLayout(null);
In your component:
setLocation(x,y);

Categories

Resources