I have a problem using JComponent and JButton togather.
public class GameWindow extends javax.swing.JFrame{
private javax.swing.JLabel freeCardLabel;
private javax.swing.JPanel NewGameBody2;
private Game game;
public GameWindow (int rozmer, int numberOfPlayers, int numberOfTreasures){
/*create a mazeboard*/
game = new Game();
game.newGame(rozmer, numberOfPlayers, numberOfTreasures);
/* the graphic rendering */
JFrame gameWindow = new JFrame();
gameWindow.setSize(1000, 730);
/* create panel for button*/
JPanel buttonPanel = new JPanel();
/* create button */
JButton button = new JButton("OK");
//button.setBorder(BorderFactory.createEmptyBorder());
//button.setContentAreaFilled(false);
button.setPreferredSize(new Dimension(40,40));
buttonPanel.add(button);
buttonPanel.setMinimumSize(new java.awt.Dimension(150, 700));
gameWindow.setContentPane(buttonPanel);
GameComponent GC = new GameComponent(rozmer, game);
gameWindow.add(GC);
gameWindow.setTitle("Labyrinth - The Game");
gameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameWindow.setVisible(true);
gameWindow.setResizable(false);
gameWindow.getContentPane().setBackground(Color.gray);
}
this is my GameWindow class. I would like to have something like that:
while GameComponent GC = new GameComponent(rozmer, game); will draw the Labyrinth. With the code posted above the button will display only without labyrinth.
GameComponent is using simply:
#Override
public void paintComponent(Graphics g){
image = null;
offset = calculateOffset(rozmer);
super.paintComponent(g);
/* draw the whole field */
for (int i = 0; i < rozmer; i++){
for (int j = 0; j < rozmer; j++){
selectImage(i, j);
g.drawImage(image, offset+150+j*63+j*1, offset+63*i+i*1, this);
}
}
/* draw free card */
selectImage(-2, -2);
g.drawImage(image, offset+270+(rozmer-1)*63, offset+63*(rozmer-1)-50, this);
}
}
and extends JComponent class.
I would like to have both button and my Labyrint in one window. Can anyone help me please? Thank you so much.
EDIT: After overriding getPreferredSize() in GameComponent it paint both, altough the Labyrinth is cut and button is in the middle right :(
Related
I am trying to display 2 objects Tank on JPanel, the tank gets image with ImageIcon. The JPanel shows up but my Tanks do not. I cannot find where am i wrong. A friend of mine send me the code that he can display tanks but i cannot display it with my computer.
My Tank class to get image
public class Player extends Tank {
private Image img;
public Player(int x, int y){
super(x, y);
ImageIcon ii = new ImageIcon("src/TankD.gif");
img = ii.getImage();
}
public Image getImg() {
return img;
}
public String toString() {
return "This is player tank";
}
}
My class to draw image
public class DrawTanks extends JPanel{ // DRAW IMAGE
private ArrayList<Tank> list = new ArrayList<>();
private Tank a;
public DrawTanks() {
Tank t1 = new Player(100, 200);
Tank t2 = new Bot(200, 100);
a = t1;
list.add(t1);
list.add(t2);
setPreferredSize(new Dimension(100,200));
setLocation(new Point(200, 200));
}
#Override
public void paintComponent(Graphics g){
for (Tank i: list)
g.drawImage(i.getImg(), i.getX(), i.getY(), null);
}
My main class
public class Window extends JFrame{
public static void main(String[]args){
Window win = new Window();
}
public Window(){
JPanel pan = new JPanel();
DrawTanks tanks = new DrawTanks();
this.add(tanks);
this.setTitle("Tank");
this.setSize(900,900);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
JPanel pan = new JPanel();
DrawTanks tanks = new DrawTanks();
this.add(tanks);
Why are you creating the "pan" object?
By default a JPanel uses a FlowLayout which respects the panels size.
In your DrawTanks class you use:
setPreferredSize(new Dimension(100,200));
to randomly set the size of the panel.
But then you create the tanks:
Tank t1 = new Player(100, 200);
Tank t2 = new Bot(200, 100);
where the location of each tank is outside the preferred size of the panel. So the tanks are probably painted but they are outside the bounds of the panel so you can't see them.
The solution:
get rid of the "pan" pane and just add your DrawTanks panel directly to the frame
give your DrawTanks a reasonable preferred size so all components added to it can be painted.
I'm trying to add a small tornado graphic (upside down pyramid) to my Frame. I can get the tornado by adding it to the frame in the main method but when I do that all I see is the tornado graphic and not the GUI underneath it.
So, I'm now trying to add the Tornado graphic to the frame when its created in the createComponents method but it now doesn't appear at all. Instead all I can see it the GUI in the frame.
I' probably missing something easy but I can't seem to figure it out. I'm not sure what I need to to in order to get the GUI and the tornado graphic both to appear.
public class EFScaleViewer {
public static void main(String[] args) {
// TODO Auto-generated method stub
TornadoFrame frame = new TornadoFrame();
frame.setTitle("EF Scale");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Here is where I create the frame and am trying to add the tornado:
public class TornadoFrame extends JFrame{
private JButton submit;
private JLabel label;
static JLabel errorLabel;
static JTextField textBox;
JPanel tornado = new TornadoComponent();
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 300;
//Constructor for the frame
public TornadoFrame() {
super();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
createComponents();
}
private void createComponents()
{
textBox = new JTextField(" ");
submit = new JButton("Submit");
label = new JLabel("Please enter a windspeed:");
errorLabel = new JLabel("Error Message " );
JPanel panel = new JPanel();
panel.add(label);
panel.add(textBox);
panel.add(submit);
panel.add(errorLabel);
panel.add(tornado);
add(panel);
}
}
I know this is working but I may be missing something so here is where I create the tornado:
public class TornadoComponent extends JPanel {
public void paintComponent(Graphics g) {
int[] xPoints = {100,200,0};
int[] yPoints = {0,200,200};
int nPoints = 3;
g.drawPolygon(xPoints, yPoints, nPoints);
}
}
You have to set the JPanels size for it to be able to display Graphics.
static class TornadoComponent extends JPanel {
public TornadoComponent() {
setPreferredSize(new Dimension(500, 500));
}
#Override
public void paintComponent(Graphics g) {
//Whatever
}
}
And in order to trigger paintComponent(Graphics g) you have to add tornado.repaint(); at the end of your createComponents() function.
private void createComponents() {
//All your components
panel.add(tornado);
add(panel);
tornado.repaint();
}
Now the Polygon is shown but not at the right place (slightly off the image)
Therefore we have to arrange your JPanels a bit:
private void createComponents() {
textBox = new JTextField(" ");
submit = new JButton("Submit");
label = new JLabel("Please enter a windspeed:");
errorLabel = new JLabel("Error Message " );
JPanel upper = new JPanel();
upper.setLayout(new BoxLayout(upper,BoxLayout.X_AXIS));
upper.add(label);
upper.add(textBox);
upper.add(submit);
upper.add(errorLabel);
JPanel lower = new JPanel();
lower.setLayout(new BoxLayout(lower,BoxLayout.X_AXIS));
lower.add(tornado);
JPanel over = new JPanel();
over.setLayout(new BoxLayout(over,BoxLayout.Y_AXIS));
over.add(upper);
over.add(lower);
add(over);
tornado.repaint();
}
Basically I make some boxes...
Over
Upper
... your stuff with text
Lower
Our tornado
Now our tornado is the wrong way round...
int[] xPoints = {100,200,150};
int[] yPoints = {0,0,150};
And voilĂ :
We just created a very basic tornado that is not aiming at anything :)
If you want to change the tornados position later you just have to recall tornado.repaint(); and you are all set.
I am trying to repaint a snake game I am creating on the new game action.It is working but it isn't clearing the old snake body or blocks from the screen.
public class View extends JFrame implements ActionListener {
private static final long serialVersionUID = -2542001418764869760L;
public static int viewWidth = 20;
public static int viewHeight = 20;
private SidePanel side;
private JMenuBar menuBar;
private JMenuItem newGameButton;
private JMenu menu, mode;
private SnakeController sController;
private GamePanel gamePanel;
/*
* Initialize the game's panels and add them to the window.
*/
public View() {
menuBar = new JMenuBar();
menu = new JMenu("Menu");
menuBar.add(menu);
newGameButton = new JMenuItem("New Game");
menu.add(newGameButton);
newGameButton.addActionListener(this);
mode = new JMenu("Mode");
menuBar.add(mode);
this.setJMenuBar(menuBar);
this.gamePanel = new GamePanel(this);
this.side = new SidePanel(this);
this.add(gamePanel, BorderLayout.CENTER);
this.add(side, BorderLayout.EAST);
Tuple position = new Tuple(10, 10);
sController = new SnakeController(position, side, gamePanel);
this.addKeyListener((KeyListener) new Listener());
// this.requestFocus();
pack();
}
public static void main(String args[]) {
View window = new View();
window.setTitle("og-snake");
window.setSize(700, 400);
window.setVisible(true);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newGameButton) {
System.out.println("clicked");
gamePanel.removeAll();
gamePanel.revalidate();
gamePanel.repaint();
Tuple position = new Tuple(10, 10);
sController = new SnakeController(position, side, gamePanel);
sController.start();
}
}
This is my main class that basically makes a view adds a side panel and board panel.The action performed is done on the new game action on the game panel.
public class GamePanel extends JPanel {
public static ArrayList<ArrayList<ColorCell>> snakeGrid;
public static int viewWidth = 20;
public static int viewHeight = 20;
ArrayList<ColorCell> data;
SnakeController sc ;
private View game;
public GamePanel(View game) {
this.game = game;
this.snakeGrid = new ArrayList<ArrayList<ColorCell>>();
this.data = new ArrayList<ColorCell>();
for (int i = 0; i < viewWidth; i++) {
data = new ArrayList<ColorCell>();
for (int j = 0; j < viewHeight; j++) {
ColorCell c = new ColorCell(2);
data.add(c);
}
snakeGrid.add(data);
}
setLayout(new GridLayout(viewWidth, viewHeight, 0, 0));
setPreferredSize(new Dimension(400,400));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < viewWidth; i++) {
for (int j = 0; j < viewHeight; j++) {
add(snakeGrid.get(i).get(j).viewCell);
}
}
}
}
gamePanel.removeAll();
gamePanel.fillGrid();
gamePanel.revalidate();
gamePanel.repaint();
Tuple position = new Tuple(10, 10);
this.gamePanel = new GamePanel(this);
this.add(gamePanel,BorderLayout.CENTER);
That code doesn't really do anything. When you add a component to the CENTER of the BorderLayout it does not replace the original component.
The way Swing painting works is that the last component added is painted first. So this means the newly added panel is painted and then the original panel is painted over top of the newly added panel.
So, since you have logic to remove all the components from the original gamePanel, there is no need to create a new gamePanel. Just reset the state of the game panel.
I'm making the game "Who is millionaire".
This is the help panel, which let user choose one of the options such as: calling friend, asking audience, etc.
But I have a problem, the options are ellipses, which are drawn in class Help_Option extends JComponent. When I test this class Help_Option individually, it works fine. But when I add the Help_Option object into the game panel, actually a sub-panel in the frame, it just displays a line on the panel, it doesn't draw my ellipse.
This is my code:
Note: a is JFrame, I don't copy the whole method initialize(JFrame a) cos it's quite long and I don't think that the error comes from there.
/******Helper panel**********/
JPanel help_area_container = new JPanel();
help_area_container.setBorder(BorderFactory.createLineBorder(Color.BLUE, 3));
help_area_container.setLayout(new GridLayout(4,0));
JPanel voting_container = new JPanel();
JPanel calling_container = new JPanel();
JPanel half_container = new JPanel();
JPanel take_container = new JPanel();
JPanel[] all_help_container = new JPanel[]{voting_container, calling_container, half_container, take_container};
for(int i = 0; i < all_help_container.length; i++){
all_help_container[i].setBorder(BorderFactory.createLineBorder(Color.RED));
all_help_container[i].setPreferredSize(new Dimension(350, help_area_container.getPreferredSize().height/4));
}
for(int j = 0; j < all_help_container.length; j++){
help_area_container.add(all_help_container[j]);
}
Help_Option voting_option = new Help_Option(all_help_container[0].getPreferredSize().width, all_help_container[0].getPreferredSize().height);
voting_option.setPreferredSize(new Dimension(all_help_container[0].getPreferredSize().width, all_help_container[0].getPreferredSize().height));
all_help_container[0].add(voting_option);
a.add(help_area_container, BorderLayout.EAST);
/*****************************/
This is the Help_Option class:
class Help_Option extends JComponent implements MouseMotionListener{
private static int x, y;
private Ellipse2D ellipse;
private Color c = Color.BLACK;
public Help_Option(int x, int y){
Help_Option.x = x;
Help_Option.y = y;
ellipse = new Ellipse2D.Double(0, 0, x, y);
this.addMouseMotionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLUE);
g2d.draw(ellipse);
g2d.setColor(c);
g2d.fill(ellipse);
g2d.setColor(Color.RED);
g2d.setFont(new Font("TimesRoman", Font.BOLD, 20));
g2d.drawString("Here I am", 250, 100);
}
public void setColor(Color c){
this.c = c;
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
if(ellipse.contains(e.getX(), e.getY())){
setColor(Color.GREEN);
repaint();
}else{
setColor(Color.BLACK);
repaint();
}
}
}
And this is the class that i used to test Help_Option class:
public class Help extends JFrame{
public static void main(String [] agrs){
Help h = new Help();
h.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
h.init();
}
public void init(){
this.setLayout(new FlowLayout());
this.setSize(2000, 1000);
JPanel a = new JPanel();
a.setPreferredSize(new Dimension((int)a.getSize().width/3, (int)a.getSize().height/2));
a.setBorder(BorderFactory.createLineBorder(Color.yellow, 3));
Help_Option k = new Help_Option(a.getPreferredSize().width, a.getPreferredSize().height/2);
k.setPreferredSize(new Dimension(a.getPreferredSize().width, a.getPreferredSize().height));
a.add(k);
this.add(a);
this.setVisible(true);
}
}
EDIT
This is the link to my classes, please take a look at them. The error is described above.
It is that you haven't set values for your first couple of JPanels and they are returning preferred sizes of 0. Dimensions of 0,0
So you should add values to the JPanels there.
public static void main(String[] args) {
JPanel help_area_container = new JPanel();
help_area_container.setBorder(BorderFactory.createLineBorder(
Color.BLUE, 3));
help_area_container.setLayout(new GridLayout(4, 0));
//Should have set sizes below
JPanel voting_container = new JPanel();
//voting_container.setSize(50,50);
JPanel calling_container = new JPanel();
JPanel half_container = new JPanel();
JPanel take_container = new JPanel();
JPanel[] all_help_container = new JPanel[] { voting_container,
calling_container, half_container, take_container };
for (int i = 0; i < all_help_container.length; i++) {
all_help_container[i].setBorder(BorderFactory
.createLineBorder(Color.RED));
all_help_container[i].setPreferredSize(new Dimension(350,
help_area_container.getPreferredSize().height / 4));
}
for (int i = 0; i < all_help_container.length; i++) {
System.out.println(all_help_container[i].getSize());
}
}
// where you can change the size
all_help_container[0].setSize(50, 50);
System.out.println("----");
for (int i = 0; i < all_help_container.length; i++) {
System.out.println(all_help_container[i].getSize());
}
}
Hopefully this will help you with the sizing of your GUI.
You will have to adjust the different panels to suit your needs. As I'm guessing that this panels will contain some other stuff in them.
You may want to create custom JPanels for each of these, so that you can easily check if they are the right size.
public class VotingPanel extends JPanel {
public VotingPanel(){
//All your variables such as size and color schemes
}
}
I am using Swing and AWT (for the listeners) to make a small program. I have a problem concerning getting the size of my JPanel (the class named Chess).
My Layout:
public class Main extends JFrame implements MouseListener, ActionListener{
Chess chessPanel = new Chess ();
JButton newGameButton = new JButton ("New Game");
JButton loadGameButton = new JButton ("Load Game");
JButton saveGameButton = new JButton ("Save Game");
JButton exitButton = new JButton ("Exit");
public static void main (String [] args) {
new Main();
}
Main () {
super ("Chess");
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setSize(dim);
setLocation(0,0);
setUndecorated(true);
chessPanel.addMouseListener(this);
add(chessPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
newGameButton.addActionListener(this);
loadGameButton.addActionListener(this);
saveGameButton.addActionListener(this);
exitButton.addActionListener(this);
buttonPanel.add(newGameButton);
buttonPanel.add(loadGameButton);
buttonPanel.add(saveGameButton);
buttonPanel.add(exitButton);
add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
// ... Code ...
}
As you can see by the code, I have one JPanel in the CENTER, which takes nearly all the screen. In the bottom I have another JPanel (SOUTH), which has a row of buttons.
What I need is the size that the JPanel in the CENTER takes. When I call the getWidth(), getHeight() or getBounds() methods inherited from JPanel, they all return 0, because of the BorderLayout.
Any idea how to get the real values?
PS: The screen always takes up the entire screen, and will never be resized, if that helps.
You're likely calling getWidth before the JPanel has been rendered, and so it will be 0. The solution is to get the size after rendering, for instance after pack() or setVisible(true) has been called on the root container that holds this JPanel.
Also, I recommend against calling setSize() on anything since most of the standard layout managers observe the preferred size of a component, not the size, and when you call pack() telling the layout managers to do their thing, the set sizes are usually ignored. You may want to make your JPanel that is in the center set its own size by overriding its setPreferredSize method if it needs to be a certain size. Then let the JFrame and its held containers set the bet fit size based on the their layout managers when you call pack.
e.g.,
import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
Chess chessPanel = new Chess();
JButton newGameButton = new JButton("New Game");
JButton loadGameButton = new JButton("Load Game");
JButton saveGameButton = new JButton("Save Game");
JButton exitButton = new JButton("Exit");
public static void main(String[] args) {
new Main();
}
Main() {
super("Chess");
add(chessPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(newGameButton);
buttonPanel.add(loadGameButton);
buttonPanel.add(saveGameButton);
buttonPanel.add(exitButton);
System.out.printf("chessPanel Size before rendering: %s%n", chessPanel.getSize());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(buttonPanel, BorderLayout.SOUTH);
pack();
System.out.printf("chessPanel Size after rendering: %s%n", chessPanel.getSize());
setLocationRelativeTo(null);
setVisible(true);
}
// ... Code ...
}
#SuppressWarnings("serial")
class Chess extends JPanel {
private static final int CHESS_WIDTH = 600;
private static final int CHESS_HEIGHT = CHESS_WIDTH;
private static final int MAX_ROW = 8;
private static final int MAX_COL = 8;
private static final Color LIGHT_COLOR = new Color(240, 190, 40);
private static final Color DARK_COLOR = new Color(180, 50, 0);
#Override
public Dimension getPreferredSize() {
return new Dimension(CHESS_WIDTH, CHESS_HEIGHT);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int panelWidth = getWidth();
int panelHeight = getHeight();
int sqrWidth = panelWidth / MAX_ROW;
int sqrHeight = panelHeight / MAX_COL;
for (int row = 0; row < MAX_ROW; row++) {
for (int col = 0; col < MAX_COL; col++) {
Color c = (row % 2 == col % 2) ? LIGHT_COLOR : DARK_COLOR;
g.setColor(c);
int x = (row * panelWidth) / MAX_ROW;
int y = (col * panelHeight) / MAX_COL;
g.fillRect(x, y, sqrWidth, sqrHeight);
}
}
}
}