Tic-Tac-Toe I can't setBounds of the x button - java

In my Tic-Tac-Toe game, I have painted the lines and I am now trying to put in the buttons. The first button I am trying to put in, I am trying to set the bounds of, and It doesn't set the bounds. It just fills the whole screen. How do I get button to only be in the top right square?
public class Project extends JFrame{
static JButton button = new JButton("");
static JButton button2 = new JButton("");
static JButton button3 = new JButton("");
static JButton button4 = new JButton("");
static JButton button5 = new JButton("");
static JButton button6 = new JButton("");
static JButton button7 = new JButton("");
static JButton button8 = new JButton("");
static JButton button9 = new JButton("");
public Project(){
setSize(1000, 750);
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
Line2D line = new Line2D.Float(100, 100, 100, 400);
Line2D line2 = new Line2D.Float(200, 100, 200, 400);
Line2D line3 = new Line2D.Float(0, 200, 300, 200);
Line2D line4 = new Line2D.Float(0, 300, 300, 300);
g2.draw(line);
g2.draw(line2);
g2.draw(line3);
g2.draw(line4);
}
public static void main(String[] args){
Project t = new Project();
t.setVisible(true);
button.setBounds(0, 0, 50, 50);
t.add(button);
}
}

Your Project class extends JFrame, and the JFrame contentPane, the JFrame container that accepts new components, uses BorderLayout by default. When you add a component to a BorderLayout-using container without specifying where the component goes, it is by default added to the BorderLayout.CENTER position, effectively filling up your GUI. Several options exist to solve your dilemma:
Use a GridLayout as suggested by PM77-1. This way a 3x3 grid will hold all 9 buttons in equal sized cells, filling up the container.
Not using buttons and ActionListeners at all, but rather using a MouseListenerListener to check where a button press has occurred, deciding if its an empty cell, and acting accordingly.

Related

When I run my code in Eclipse, my JLabel's disappear until I resize the window

So when I run this code:
public class Game
{
// DECLARING Java objects to later use
JFrame window;
Container con;
JPanel titleNamePanel, startButtonPanel, signaturePanel;
JLabel titleNameLabel, signatureLabel;
Font titleFont = new Font("Britannic Bold", Font.BOLD, 80);
Font signature = new Font("Arial", Font.ITALIC, 15);
Font normalFont = new Font("Times New Roman", Font.PLAIN, 30);
JButton startButton;
public static void main(String[] args)
{
// calling constructor
new Game();
}
public Game() {
// GAME WINDOW creation
window = new JFrame();
window.setSize(800,600);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.black);
window.setLayout(null);
window.setVisible(true);
con = window.getContentPane();
// TITLE NAME PANEL for title text
titleNamePanel = new JPanel();
titleNamePanel.setBounds(100, 100, 600, 150);
titleNamePanel.setBackground(Color.black);
titleNameLabel = new JLabel("GAME");
titleNameLabel.setForeground(Color.white);
titleNameLabel.setFont(titleFont);
// START BUTTON PANEL for button housing
startButtonPanel = new JPanel();
startButtonPanel.setBounds(300, 400, 200, 100);
startButtonPanel.setBackground(Color.black);
// START BUTTON customization
startButton = new JButton("START");
startButton.setBackground(Color.black);
startButton.setForeground(Color.white);
startButton.setFont(normalFont);
// SIGNATURE PANEL for text and customization
signaturePanel = new JPanel();
signaturePanel.setBounds(640, 525, 150, 40);
signaturePanel.setBackground(Color.black);
signatureLabel = new JLabel("coded by connor");
signatureLabel.setForeground(Color.white);
signatureLabel.setFont(signature);
// ADDING both labels to panels and retrieving content pane information
titleNamePanel.add(titleNameLabel);
signaturePanel.add(signatureLabel);
startButtonPanel.add(startButton);
con.add(titleNamePanel);
con.add(startButtonPanel);
con.add(signaturePanel);
}
}`
My code works but my window just displays black until I maximize the window and then return it back to normal like this: black window with JLabels gone-----------------JLabels back when I maximize the screen and then minimize it back to it's original dimensions
I'm just wondering if anyone knows a fix for this that I'm overlooking. Thank you so much for your time.

Can't add scroll bar to JTextarea

Hello Everyone I am new to Java so I am sure I am doing something obviously wrong here but I just keep going in circles.
I am trying to add a scroll to a JTextarea. Here is what I have tried but it doesn't show up.
textarea1 = new JTextArea();
textarea1.setBounds(251,26,795,345);
textarea1.setBackground(new Color(255,255,255));
textarea1.setForeground(new Color(0,0,0));
textarea1.setEnabled(true);
textarea1.setFont(new Font("sansserif",0,12));
textarea1.setText("");
textarea1.setBorder(BorderFactory.createBevelBorder(1));
textarea1.setVisible(true);
JScrollPane ScrollPane1 = new JScrollPane(textarea1);
ScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//adding components to contentPane panel
contentPane.add(browseFileOne);
contentPane.add(browseOutput);
contentPane.add(button1);
contentPane.add(button2);
contentPane.add(button4);
contentPane.add(fileOneText);
contentPane.add(fileTwoText);
contentPane.add(label1);
contentPane.add(label2);
contentPane.add(label3);
contentPane.add(outputTextFile);
contentPane.add(textarea1);
see working example:
https://repl.it/repls/DimpledDefensiveSourcecode
Code:
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
public static void main(String[] args) {
new Main();
}
public Main() {
this.setSize(400, 400);
this.setLocation(0, 0);
this.setResizable(false);
this.setTitle("Application");
JPanel painel = new JPanel(null);
// Creating the Input
JTextField tf1 = new JTextField("Some random text", 15);
tf1.setBounds(5, 5, this.getWidth() - 120, 20);
tf1.setColumns(10);
tf1.setText("Omg");
// resultsTA,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
painel.add(tf1);
// Creating the button
JButton button1 = new JButton("Send");
button1.setBounds(290, 5, 100, 19);
painel.add(button1);
// Creating the TextArea
JTextArea ta1 = new JTextArea(15, 20);
JScrollPane scr = new JScrollPane(ta1,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);// Add your text area to scroll pane
ta1.setBounds(5, 35, 385, 330);
ta1.setLineWrap(true);
ta1.setWrapStyleWord(true);
scr.setBounds(20, 30, 100, 40);// You have to set bounds for all the controls and containers incas eof null layout
painel.add(scr);// Add you scroll pane to container
this.add(painel);
this.setVisible(true);
}
}

Why after I added a JComboBox into one of the JPanels, all JPanels were not rendered

When the JComboBox, cmbox was not added to a JPanel, two panels, p1 & p2 could be rendered. You may comment out the combo box portion to see the result. But after I added the combo box into one of the panels, all panels were not rendered.
My code is like the following:
import java.awt.*;
import javax.swing.*;
public class TestCombo {
public static void main(String[] args) {
JFrame frame = new JFrame("康樂彩歌");
frame.setVisible(true);
frame.setBounds(0, 0, 1368, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p1 = new JPanel();
p1.setBackground(Color.CYAN);
JRadioButton rb1 = new JRadioButton("加簡譜", false);
rb1.setFont(new Font("新細明體", Font.PLAIN, 20));
JRadioButton rb2 = new JRadioButton("加人聲", false);
rb2.setFont(new Font("新細明體", Font.PLAIN, 20));
rb1.setBounds(450, 180, 50, 50);
rb2.setBounds(500, 180, 50, 50);
JButton btPlay = new JButton("PLAY");
btPlay.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 25));
btPlay.setBounds(100, 20, 100, 20);//x axis, y axis, width, height
JButton btStop = new JButton("STOP");
btStop.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 25));
btStop.setBounds(140, 20, 100, 20);//x axis, y axis, width, height
//p1.add(cmbox);
p1.add(rb1);
p1.add(rb2);
p1.add(btPlay);
p1.add(btStop);
p1.setBorder(BorderFactory.createLineBorder(Color.black));
JPanel p2 = new JPanel();
p2.setBackground(Color.PINK);
p2.setBorder(BorderFactory.createLineBorder(Color.red));
JComboBox cmbox = new JComboBox(); //The JComboBox to be added to a JPanel
cmbox.setFont(new Font("新細明體", Font.PLAIN, 20));
cmbox.addItem("紫竹調");
cmbox.addItem("走一同去郊遊");
cmbox.addItem("大野狼");
cmbox.addItem("歸來吧蘇連多");
cmbox.addItem("追尋");
cmbox.addItem("三輪車");
cmbox.addItem("我家門前有小河");
cmbox.addItem("漁家樂");
cmbox.addItem("嚕啦啦");
cmbox.addItem("踏雪尋梅");
p2.add(cmbox);
frame.add(p1, BorderLayout.PAGE_START);
frame.add(p2, BorderLayout.CENTER);
}
}
Implementing the changes as detailed below the code, solves the problem.
import java.awt.*;
import javax.swing.*;
public class TestCombo {
public static void main(String[] args) {
JFrame frame = new JFrame("康樂彩歌");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p1 = new JPanel();
p1.setBackground(Color.CYAN);
JRadioButton rb1 = new JRadioButton("加簡譜", false);
rb1.setFont(new Font("新細明體", Font.PLAIN, 20));
JRadioButton rb2 = new JRadioButton("加人聲", false);
rb2.setFont(new Font("新細明體", Font.PLAIN, 20));
JButton btPlay = new JButton("PLAY");
btPlay.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 25));
JButton btStop = new JButton("STOP");
btStop.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 25));
p1.add(rb1);
p1.add(rb2);
p1.add(btPlay);
p1.add(btStop);
p1.setBorder(BorderFactory.createLineBorder(Color.black));
JPanel p2 = new JPanel();
p2.setBackground(Color.PINK);
p2.setBorder(BorderFactory.createLineBorder(Color.red));
JComboBox cmbox = new JComboBox(); //The JComboBox to be added to a JPanel
cmbox.setFont(new Font("新細明體", Font.PLAIN, 20));
cmbox.addItem("紫竹調");
cmbox.addItem("走一同去郊遊");
cmbox.addItem("大野狼");
cmbox.addItem("歸來吧蘇連多");
cmbox.addItem("追尋");
cmbox.addItem("三輪車");
cmbox.addItem("我家門前有小河");
cmbox.addItem("漁家樂");
cmbox.addItem("嚕啦啦");
cmbox.addItem("踏雪尋梅");
p2.add(cmbox);
frame.add(p1, BorderLayout.PAGE_START);
frame.add(p2, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
btPlay.setBounds(100, 20, 100, 20); Do not set the bounds of components. Let the layouts (padding and borders) do their job.
frame.setBounds(0, 0, 1368, 500); That's just a guess, and if it's the right guess on one OS, it will be the wrong guess on others. Instead pack() the window after components are added.
Sidebar: GUIs should be started on the EDT. (Not implemented above: 'batteries not included'.)

GUI RadioButtonJPanel

I need to create a GUI that has red, green and blue radiobuttons. When a radiobutton is clicked they should cause a panel in the centre of the frame to change to the corresponding backcolour colour. Here is my code below: what am I doing wrong. Here is my code below(please help; it compiles but the frame appears tiny and displays nothing):
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class RadioButtons extends JFrame implements ActionListener {
JFrame f;
JPanel panel = new JPanel();
JRadioButton rb1, rb2, rb3;
JButton b1;
JButton b2;
JButton b3;
public RadioButtons() {
f = new JFrame();
rb1 = new JRadioButton("Green");
//rb1 = new JLabel(, JLabel.RIGHT);
rb1.setBounds(100, 70, 100, 40);
rb2 = new JRadioButton("Red");
rb2.setBounds(100, 90, 100, 40);
//rb2 = new JLabel("Red", JLabel.RIGHT);
rb3 = new JRadioButton("Blue");
rb3.setBounds(100, 100, 100, 40);
//rb3 = new JLabel("Blue", JLabel.RIGHT);
ButtonGroup s1 = new ButtonGroup();
s1.add(rb1);
s1.add(rb2);
s1.add(rb3);
this.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
f.setTitle("GUI Background Changer");
b1 = new JButton("Change background color");
b1.setBounds(200, 200, 50, 50);
b1.addActionListener(this);
b2 = new JButton("Change background color");
b2.setBounds(200, 200, 50, 50);
b2.addActionListener(this);
b3 = new JButton("Change background color");
b3.setBounds(200, 200, 50, 50);
b3.addActionListener(this);
add(rb1);
add(rb2);
add(rb3);
f.add(panel);
//x.setDefaultCloseOperation(XFrame.EXIT_ON_CLOSE);
}//constructor
public static void main(String[] args) {
RadioButtons radiobuttons = new RadioButtons();
radiobuttons.setJpanelSize(200, 200, 50, 50);//setJPanelSize(200,200,50,50);
radiobuttons.setDefaultCloseOperation(EXIT_ON_CLOSE);
}// main
public void backgroundChanged(ActionEvent e) {
Color initialcolor1 = Color.RED;
Color initialcolor2 = Color.BLUE;
Color initialcolor3 = Color.GREEN;
if (rb1.isSelected()) {
panel.setBackground(initialcolor1);
}// if
else
if (rb2.isSelected()) {
panel.setBackground(initialcolor2);
}// else if
else {
panel.setBackground(initialcolor2);
}// else
}
public void setJpanelSize(int v, int w, int x, int y) {
}// setJPanel size
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}//class
it compiles but the frame appears tiny and displays nothing):
That is probably because you forgot to pack your JFrame after adding the components. Invoke pack() for your frame after adding the components.
You will also want to:
Call setVisible(true) after all other actions.
Prevent from using null layout.

Using JButtons, JLabels, and JTextFields within a JPanel over a painted background

I'm pretty new to Java, but have been using JPanels, JButtons, JLabels and JTextFields successfully in other parts of my program, but I'm running into trouble when trying to have a JPanel with a couple JButtons, JLabels, and JTextFields inside of it overtop of a painted background.
Here is all of the relevant code for this portion of the program. Currently, when the program runs the only thing that will display is the p1_fireButton, player1PowerField, and player1AngleField overtop of the background (Even though I have the components created for player 2, I purposely commented out adding the p2_Panel so that I could concentrate on p1_Panel.
The weird thing is that those JComponents will only display if I hit the TAB key after the program is running for whatever reason, which I'm also hoping someone could help me fix. My goal will be to have the p1_panel occupy the left orange box and the p2_panel occupy the right orange box. Help would be greatly appreciated!
public class GameFrame extends JFrame
{ //start class GameFrame
ImageIcon background = new ImageIcon("background.jpg");
ImageIcon terrain1 = new ImageIcon("terrain1.png");
//ImageIcon tank_red = new ImageIcon("tank_red.png");
//ImageIcon tank_red = new ImageIcon(player1Tank);
private int x_rectangle = 50;
private int y_rectangle = 50;
private JButton p1_fireButton;
private JButton p2_fireButton;
private JPanel p1_Panel;
private JPanel p2_Panel;
private JLabel player1PowerLabel;
private static JTextField player1PowerField;
private JLabel player1AngleLabel;
private static JTextField player1AngleField;
private JLabel player2PowerLabel;
private static JTextField player2PowerField;
private JLabel player2AngleLabel;
private static JTextField player2AngleField;
String player1Name;
String player2Name;
final Timer gameTimer = new Timer(8, new timer());
Projectile projectile = new Projectile(200, 300);
public GameFrame(String title)
{ //start GameFrame constructor
super(title);
Dimension size = getPreferredSize();
size.width = 1000;
setPreferredSize(size);
setResizable(false);
setLayout(null);
Color trans = new Color(0, 0, 0, 0);
//player1 panel
p1_Panel = new JPanel();
p1_Panel.setLayout(null);
p1_Panel.setBounds(0, 0, 500, 300);
p1_Panel.setBackground(trans);
p2_Panel = new JPanel();
p2_Panel.setLayout(null);
p2_Panel.setBounds(500, 0, 500, 300);
p2_Panel.setBackground(trans);
//player2 panel
/*p2_fireButtonPanel = new JPanel();
p2_fireButtonPanel.setBounds(400, 85, 100, 100);
p2_fireButtonPanel.setBackground(trans);*/
//player1 angle/power fields
player1PowerLabel = new JLabel("Power");
player1PowerLabel.setLayout(null);
player1PowerLabel.setBounds(400, 20, 50, 50);
player1PowerField = new JTextField(3);
player1PowerField.setLayout(null);
player1PowerField.setBounds(400, 10, 50, 25);
player1AngleLabel = new JLabel("Angle");
player1AngleLabel.setLayout(null);
player1AngleLabel.setBounds(30, 10, 50, 50);
player1AngleField = new JTextField(3);
player1AngleField.setLayout(null);
player1AngleField.setBounds(300, 10, 50, 25);
//player2 angle/power fields
player2PowerLabel = new JLabel("Power");
player2PowerLabel.setLayout(null);
player2PowerLabel.setBounds(0, 0, 10, 10);
player2PowerField = new JTextField(3);
player2PowerField.setLayout(null);
player2PowerField.setBounds(10, 10, 10, 10);
player2AngleLabel = new JLabel("Angle");
player2AngleLabel.setLayout(null);
player2AngleLabel.setBounds(30, 10, 10, 10);
player2AngleField = new JTextField(3);
player2AngleField.setLayout(null);
player2AngleField.setBounds(60, 10, 10, 10);
//player1 fire button
p1_fireButton = new JButton("Fire!");
p1_fireButton.setLayout(null);
p1_fireButton.setBounds(430, 70, 50, 50);
ActionListener fireListener = new fireButtonListener();
p1_fireButton.addActionListener(fireListener);
//player2 fire button
p2_fireButton = new JButton("Fire AGAIN!");
p2_fireButton.setLayout(null);
p2_fireButton.setBounds(530, 70, 50, 50);
//add components to player1 panel
p1_Panel.add(p1_fireButton);
p1_Panel.add(player1PowerLabel);
p1_Panel.add(player1PowerField);
p1_Panel.add(player1AngleLabel);
p1_Panel.add(player1AngleField);
//add components to player2 panel
p2_Panel.add(p2_fireButton);
p2_Panel.add(player2PowerLabel);
p2_Panel.add(player2PowerField);
p2_Panel.add(player2AngleLabel);
p2_Panel.add(player2AngleField);
//add components to GameFrame
add(p1_Panel);
//add(p2_Panel);
projectile.fireProjectile(60, -60 * Math.PI / 180.0);
} //end GameFrame constructor
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Image bg = background.getImage();
Image t1 = terrain1.getImage();
Image p1tank = StartPanel.getPlayer1Tank();
Image p2tank = StartPanel.getPlayer2Tank();
//Image tank1 = tank_red.getImage();
g2.drawImage(bg, 0, 0, 1000, 800, this);
g2.drawImage(t1, 0, 420, 1000, 380, this);
g2.drawImage(p1tank, 50, 300, 66, 50, null);
g2.drawImage(p2tank, 500, 300, 66, 50, null);
player1Name = new String(StartPanel.getPlayer1Name());
player2Name = new String(StartPanel.getPlayer2Name());
g.drawString(player1Name, 50, 50);
g.drawString(player2Name, 525, 50);
g2.setColor(Color.green);
g2.fillOval((int)projectile.getXPosition(), (int)projectile.getYPosition(), 15, 15);
}
public class timer implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//TanksGUI.gameFrame.moveRectangle(1, 1);
projectile.advanceProjectile(0.05);
if (projectile.getYPosition() > 400)
{
gameTimer.stop();
}
repaint();
}
}
public class fireButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
gameTimer.start();
}
}
} //end class GameFrame
Check out BackgroundPanel to help you with this. The basic code would be:
JPanel north = new JPanel();
north.add( new JLabel(...) );
north.add( new JTextField(10) );
JPanel gamePanel = new GamePanel();
BackgroundPanel background = new BackgroundPanel(...);
background.add(north, BorderLayout.North);
background.add(gamePanel);
frame.add(background);
The GamePanel is the panel where you do all the custom painting for your game characters. As noted by MadProgrammer, this painting should never be done in the paint() method of the frame.
Don't extend from JFrame you're not adding any functionality to it that creating an instance couldn't achieve. It also makes you're project unportable.
Don't override paint of top level containers. If for no other reason they are not double buffered, which will cause you problems if you want to perform animation. The paint chain for a top level container is rather complex and you've just circumvent the whole process.
Instead, create a custom component (from something like JPanel) and use it as you primary canvas. Override it's paintComponent method and render your background to it, making sure you call super.paintComponent first.
Make sure that any containers you are placing on this "canvas" are transparent, otherwise your background won't show up.
Have a look at Performing Custom Painting and Painting in AWT and Swing for more information

Categories