JPanel filling whole window - java

I'm trying to make chess in java, but I'm stuck on the panel's size and location. When I try to change any of them, it does nothing and I don't know why. Could someone explain it to me?
package Chess;
import javax.swing.*;
import java.awt.*;
public class Window extends Component{
public void addChessWindow() {
JFrame chessWindow = new JFrame("Chess");
chessWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chessWindow.setResizable(false);
chessWindow.setExtendedState(JFrame.MAXIMIZED_BOTH);
chessWindow.setUndecorated(true);
chessWindow.setBackground(Color.decode("#4D6713"));
chessWindow.setVisible(true);
JPanel field = new JPanel();
field.setBackground(Color.BLACK);
field.setBounds(30,15,2,1);
chessWindow.add(field);
}
}
Note: everything starts in the main method.

I think you could do something like this:
chessWindow.add(field, BorderLayout.CENTER);

Related

why does text make my jbutton take up my whole jframe?

so i am using intellij and am trying to make a jbutton with text. it works fine without the text but when i put the text on it takes up the whole jframe and i do not know why. if you could help me i would greatly appreciate it. here is my code. Edit thank you Manchi for your answer it worked perfectly and i am no longer looking for answers but i do not know how to close the question.
package com.company;
import javax.swing.*;
import java.awt.*;
class Fantasyrpglifesim implements JButton {
Fantasyrpglifesim() {
}
public static void main(String[] args) {
MouseInputAdapter();
//Frame//
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
frame.setSize(1500000, 1500000);
frame.getContentPane();
frame.setVisible(true);
//Buttons//
frame.add(BUTTON).setBounds(570,500,150,150);
BUTTON.setText("Age up");
}
private static void MouseInputAdapter() {
}
}
You just need to change the layout of the JFrame. Add the next line to your code:
frame.setLayout(new FlowLayout());

How is JFrame.setResizable supposed to be used?

I'm trying to followed java tutorials and now I am going over JFrame.
This is a information inquiry more than help question.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Login {
public static void main(String[] args){
//Creating object of LoginFrame class and setting some of its properties
LoginFrame frame = new LoginFrame();
frame.setTitle("LoginForm");
frame.setVisible(true);
frame.setBounds(10, 10, 370, 600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
This code will cause the frame to be resized to a very small size at the top left corner regardless of the bounds I set.
A simple fix for this is to place frame.setResizable() before setting its bounds.
Does anyone know why this happens or am I doing something wrong?
I'm also on Ubuntu 20.04, maybe this matters but I haven't found an answer.
Tutorial shows above code.
The following is the code for LoginFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//Creating LoginFrame class
public class LoginFrame extends JFrame implements ActionListener {
//Creating constructor of LoginFrame() class
LoginFrame(){
}
//Overriding actionPerformed() method
#Override
public void actionPerformed(ActionEvent e){
}
}
Like I was saying I was only following a tutorial. This was only the beginning of the tutorial but I had the same issue when starting another very simple frame tutorial.
The following works fine for me :
import javax.swing.*;
class Scratch extends JFrame {
public Scratch() {
super();
}
public static void main(String[] args){
//Creating object of LoginFrame class and setting some of its properties
Scratch frame = new Scratch();
frame.setTitle("LoginForm");
frame.setVisible(true);
frame.setBounds(10, 10, 370, 600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Result : I see a big rectangular window - in the shape of a smart phone screen I'd say.
setResizable(false) means you cannot resize the frame. I suspect the problem you're trying to identify lies somewhere in the LoginFrame class... no code for this was included though so hard to comment furhter.

Add Textfields on Jframe at Runtime

I am trying to create text-fields on frame by getting input at run-time. Is it possible? Or I have to create another frame for that. I tried this code, but it's not working. Please Help me out, and tell me what's wrong with this code.
import java.awt.BorderLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Check extends JFrame implements ActionListener
{
JTextField txtqty;
JTextField[] tfArr;
JPanel p1,p2;
JButton bsmbt;
public Check()
{
GUIDesign();
}
public void GUIDesign()
{
p1 = new JPanel();
txtqty = new JTextField(10);
JButton bsmbt= new JButton("OK");
p1.add(txtqty);
p1.add(bsmbt);
p2=new JPanel();
p2.setLayout(null);
add(p1,BorderLayout.NORTH);
setSize(500, 500);
setVisible(true);
setLocation(100, 100);
bsmbt.addActionListener(this);
}
public static void main(String[] args)
{
new Check();
}
public void TFArray(JTextField[] temp)
{
int x,y,width,height;
x=10;y=30;width=50;height=20;
int no_of_textboxes = Integer.parseInt(txtqty.getText());
temp=new JTextField[no_of_textboxes];
for(int i=0;i<no_of_textboxes;i++)
{
temp[i]= new JTextField(10);
temp[i].setBounds(x, y, width, height);
x+=(width+10);
p2.add(temp[i]);
}
add(p2);
}
#Override
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(this, txtqty.getText());
TFArray(tfArr);
}
}
->Method TFArray() isn't working.
You have many errors in your code:
public void TFArray(JTextField[] temp): method names should start with lowerCamelCase
You're extending JFrame, you shouldn't extend JFrame, because when you extend it your class is a JFrame, JFrame is rigid so you can't place it inside anything else, instead you might consider creating a JFrame instance and if you ever need to extend JComponent extend from JPanel.
JButton bsmbt= new JButton("OK"); the variable bsmbt is a local variable inside your constructor, your global variable bsmbt is not used anywhere, and if you try to use it later you'll get a NullPointerException, instead change that line to:
bsmbt= new JButton("OK");
You're using null layout for p2, instead use a proper Layout manager and read Null layout is evil and Why is it frowned upon to use a null layout in swing?. Swing was designed to work with different PLAFs, screen sizes and resolutions, while pixel perfect GUIs (with setBounds()) might seem like the best and faster way to create a complex GUI in Swing, the more GUIs you make, the more errors you'll get due to this.
To solve your problem call revalidate() and repaint()
The above code creates 2 textfields. but when I again put some value and submit it, it doesn't seem to reflect any changes.
That might be because you're overriding x, y, height and width variables each time you enter TFArray method. But that is a guess, if you want a real answer, follow the suggestions above and post a proper and valid Minimal, Complete, and Verifiable example

Java Swing. Need to open 3 separate windows

Suppose to pull up 3 different windows with different Labels and Strings in the frames. Below is a picture of the projected output
I have three classes.
P1Panel that extends JPanel
P1Frame that extends JFrame
P1Driver used for main
----------------------------------------------------------P1Panel class below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class P1Panel extends JPanel
{
private String s0;
public P1Panel(String s0){
{
add(new P1Panel(s0));
}
}
}
---------------------------------------------This is P1Frame class below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class P1Frame extends JFrame
{
private String s1;
public P1Frame (String s1){
this.s1 = s1;
{
add(new P1Panel(s1));
}
P1Frame p1 = new P1Frame(s1);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1.setSize(300,200);
p1.setVisible(true);
}
}
----------------------------------------This is P1Driver class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class P1Driver
{
public static void main(String [] args)
{
P1Frame p1 = new P1Frame("This is window 1");
//JFrame f2 = new JFrame("This is window 2");
//JFrame f3 = new JFrame("This is window 3");
p1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1.setSize(300,200);
p1.setVisible(true);
}
}
I believe my P1Panel class is correct in that I called a constructor and added it to itself. The text in my label is passing the P1Panel constructor as a parameter
My P1Frame class I am having difficult with. In the constructor I am wanting to make a P1Panel object and add it to the P1Frame. I think I need to pass a string into the P1Frame constructor as a parameter and then pass string to P1Panel?
I believe my Driver class is correct too as I am just putting main here and setting items size and visibility.
I believe my fix is a small one, but I am stuck and unsure in how to do so. When I run the program as is, it runs infinite with nothing popping up.
You have an infinitely recursive constructor in P1Panel class and that is why your program gets stuck. Just remove the line
add(new P1Panel(s0));
when you execute this line in the constructor you are essentially calling it again by doing
new P1Panel(s0)
so the constructor never returns and it keeps calling itself recursively. Plus why are you not adding any Swing components to your P1Panel? It will be empty without Swing components. If you want to display a String inside the panel, I suggest you do the below in the constructor.
setLayout(new BorderLayout());
JLabel label = new JLabel(s0);
add(label, BorderLayout.CENTER);

JPanel not showing when added to another JPanel

I'm trying to create a game in Java - the game is going to be a 2-D scrolling game. I have a class called CornPanel which extends JPanel and shows a corn plant - the CornPanel's are what will be moved across the screen. I know the CornPanel class is working because it shows up when I add it directly to a JFrame. However, when I try to add a CornPanel to another JPanel and then add that JPanel to the JFrame, the CornPanel doesn't show up.
Here's my CornPanel class (abbreviated - I took out the stuff I'm pretty sure isn't causing the problem):
package game;
import java.awt.Graphics;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class CornPanel extends JPanel{
BufferedImage cornImage;
public CornPanel(){
loadImages();
}
public void loadImages(){
try{
cornImage = ImageIO.read(new File("src\\cornBasic.png"));
} catch(IOException e){
e.printStackTrace();
}
}
protected void paintComponent(Graphics g){
g.drawImage(cornImage, 0, 0, cornImage.getWidth(), cornImage.getHeight(), this);
}
}
My Game class:
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JFrame{
ArrayList<CornPanel> cornPanels;
JPanel gameContainer;
public Game(){
cornPanels = new ArrayList<CornPanel>();
gameContainer = new JPanel();
setSize(1000, 1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(new Color(98, 249, 255));
setExtendedState(JFrame.MAXIMIZED_BOTH);
getContentPane().add(gameContainer);
addCornPanel();
setVisible(true);
}
public void addCornPanel(){
CornPanel cornPanel = new CornPanel();
cornPanels.add(cornPanel);
gameContainer.add(cornPanel);
cornPanel.setVisible(true);
getContentPane().repaint();
repaint();
}
public static void main(String[] args) {
Game game = new Game();
}
}
Note: I got it to work by setting the LayoutManager for both the JFrame and gameContainer to new GridLayout(1,1), but the problem is that then I can't use setLocation() on the CornPanel in order to make it animate. If there's a way to do it without setLocation() let me know. Also, I took out a lot of code I don't think is necessary for diagnosing the problem - hopefully I didn't take out too much.
Your corn panel doesn't specify a prefered size, so the layout manager probably is just setting it to 0x0.
There is an easier way to add an icon into a pane. JLabel::JLabel(Icon) will create a label that has the image icon specified, and is of the right size to hold it.
If you do need something more complex than a single image, then your JComponent implementation should override getPreferredSize().
You also should call "pack" on your jframe, so that it can figure out the ideal size for display.
A few other comments not related to your original question:
You shouldn't extend JFrame for the main frame, just create a new JFrame instance, and configure it.
You should do the work in the Event Dispatch Thread. See EventQueue and more specifically read through Lesson: Concurrency in Swing
I know the CornPanel class is working because it shows up when I add it directly to a JFrame. However, when I try to add a CornPanel to another JPanel and then add that JPanel to the JFrame, the CornPanel doesn't show up.
The layout of the content pane of a frame is BorderLayout, the default constraint is CENTER which stretches a component to fill the space.
The default layout of a panel is FlowLayout which ..doesn't stretch the component to fit.
The best way to fix this is to (firstly) override the getPreferredSize() method of CornPanel to return a sensible size, then add it to a layout/constraint that has the behavior required when it has more space than it needs.

Categories