Java Repaint gridlayout - java

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.

Related

How do I refresh the panel with a two dimensional button array?

I'm making a chess game in Java. And because I'm a beginner at Swing, I ran into a problem right away. I made a two dimensional array of buttons for the chessboard tiles. The problem is when my first button is clicked I do not know how to refresh that button or the panel it is in.
Here is the code.
public class Table extends JFrame implements ActionListener{
public JButton[][]tile = new JButton[8][8];
JPanel gamePAN = new JPanel();
int size=8;
Tile[][] tileList = new Tile[8][8];
private final Color lightTileColor = Color.decode("#FFFACD");
private final Color darkTileColor = Color.decode("#593E1A");
public Table() {
this.setResizable(true);
this.setVisible(true);
this.setTitle("Chess");
initCompoments();
Toolkit tk = Toolkit.getDefaultToolkit();
int xsize = (int) tk.getScreenSize().getWidth();
int ysize = (int) tk.getScreenSize().getHeight();
this.setSize(xsize, ysize);
private void initCompoments() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
gamePAN.setLayout(new java.awt.GridLayout(8, 8, 0, 0));
getContentPane().add(gamePAN);
gamePAN.setBounds(550, 100, 800, 800);
pack();
}
private void initialize() {
//gamePAN = new JPanel();
//gamePAN.setLayout(new GridLayout(size,size));
for(int i=0;i<size;i++) {
for(int j=0; j<size;j++) {
if(i%2==0) {
if(j%2==0) {
tile[i][j] = new JButton();
tile[i[j].setBackground(lightTileColor)
tile[i[j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}else {
tile[i][j] = new JButton();
tile[i[j].setBackground(darkTileColor);
tile[i[j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}
}else {
if(j%2==0) {
tile[i][j] = new JButton();
tile[i[j].setBackground(darkTileColor);
tile[i][j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}else {
tile[i][j] = new JButton();
tile[i[j].setBackground(lightTileColor);
tile[i][j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}
}
}
}
#Override
public void actionPerformed(ActionEvent ae) {
for(int r=0;r<size;r++) {
for(int c=0;c<size;c++) {
if(ae.getSource()==tile[r][c]) {
if(tileList[r[c].getPiece()!=null) {
tileList[r][c].getPiece().kretanje(tile, tileList);
}
}
}
}
The problem is when my first button is clicked I do not know how to refresh that button or the panel it is in
There is no need for all the looping code in the ActionListener.
The ActionEvent will contain the reference to the button that was clicked.
So in the ActionListener you add to the button your basic code would be:
JButton button = (JButton)ae.getSource();
button.setIcon(...); // do whatever you want with the button

How to add moving sprites to JFrame

I'm trying to add sprites to a JFrame that move or 'fidget' in place(meaning they just move up a pixel and then down a pixel), almost like the Pokemon sprites in your party menu move, but just with a single sprite. I got the code to work when I was just running it as a JApplet, but my larger game is built in a JFrame with multiple JPanels. When I tried to incorporate the working code into my larger game, it stopped working. Any help would be greatly appreciated. This is not for school, just my own personal game.
This begins the JApplet that works.
public class SpriteAnimation extends JApplet{
private static final long serialVersionUID = 1L;
public static final int WIDTH = 150;
public static final int HEIGHT = 50;
private PaintSurface canvas;
public void init(){
this.setSize(WIDTH, HEIGHT);
canvas = new PaintSurface();
this.add(canvas, BorderLayout.CENTER);
Timer t = new Timer(250, e -> {canvas.repaint();});
t.start();
}
}
public class PaintSurface extends JComponent{
private static final long serialVersionUID = 1L;
ArrayList<Sprite> sprites = new ArrayList<Sprite>();
public PaintSurface(){
sprites.add(new Hero(0));
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
doDrawing(g);
Toolkit.getDefaultToolkit().sync();
}
public void doDrawing(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for(Sprite h : sprites){
g2.drawImage(h.getImage(), h.getX(), h.getY(), null);
h.move();
}
}
}
public class Sprite {
private int x, y, fidget;
private Image image;
boolean flip = true;
public Sprite(String s, int fidget, int startingX) {
this.fidget = fidget;
ImageIcon icon = new ImageIcon(s);
image = icon.getImage();
x = startingX; y = 15;
}
public void move() {
y = 10;
if(!flip){
y += fidget;
flip = !flip;
}
else{
y -= fidget;
flip = !flip;
}
}
public Image getImage(){
return image;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
public class Hero extends Sprite {
private int startingX;
public Hero(int x){
super("Hero.png", 1, x);
this.startingX = x;
}
public int getStartingX() {
return startingX;
}
public void setStartingX(int startingX) {
this.startingX = startingX;
}
}
This is where I'd like to add the working Sprites to(Specifically the battlefield JPanel).
public class BattleFrame extends JFrame {
private static final long serialVersionUID = 1L;
static ArrayList<JButton> buttonsActions = new ArrayList<JButton>();
static ArrayList<JButton> buttonsConfirmation = new ArrayList<JButton>();
static ArrayList<JButton> buttonsAlly = new ArrayList<JButton>();
static ArrayList<JButton> buttonsEnemy = new ArrayList<JButton>();
static ArrayList<ArrayList<JButton>> buttons = new ArrayList<ArrayList<JButton>>();
static Box boxAllies = Box.createVerticalBox();
static int movesLeft = 3;
static JScrollPane logs;
static JTextArea log;
public BattleFrame(){
this.setSize(1200, 700);
this.setTitle("The Last Battle");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
JPanel battleField = new JPanel();
battleField.setBorder(BorderFactory.createTitledBorder("Battle Field"));
battleField.setLayout(new BorderLayout());
JPanel allies = new JPanel();
allies.setBorder(BorderFactory.createTitledBorder("Armies of Light"));
boxAllies.add(new JLabel("Moves left: " + movesLeft));
JButton channellers = new JButton("Channellers");
channellers.setName("Channellers"); buttonsAlly.add(channellers);
channellers.addActionListener(e -> ButtonClick.clicked(channellers));
JButton archers = new JButton("Archers");
archers.setName("Archers"); buttonsAlly.add(archers);
archers.addActionListener(e -> ButtonClick.clicked(archers));
JButton infantry = new JButton("Infantry");
infantry.setName("Infantry"); buttonsAlly.add(infantry);
infantry.addActionListener(e -> ButtonClick.clicked(infantry));
boxAllies.add(Box.createVerticalStrut(150)); boxAllies.add(channellers);
boxAllies.add(Box.createVerticalStrut(40)); boxAllies.add(infantry);
boxAllies.add(Box.createVerticalStrut(40)); boxAllies.add(archers);
boxAllies.add(Box.createVerticalStrut(40));
allies.add(boxAllies);
JPanel enemies = new JPanel();
enemies.setBorder(BorderFactory.createTitledBorder("The Shadow"));
Box boxEnemies = Box.createVerticalBox();
JButton enemyChannellers = new JButton("Dreadlords");
enemyChannellers.setName("Dreadlords"); buttonsEnemy.add(enemyChannellers);
enemyChannellers.addActionListener(e -> ButtonClick.clicked(enemyChannellers));
JButton enemyArchers = new JButton("Enemy Archers");
enemyArchers.setName("Enemy Archers"); buttonsEnemy.add(enemyArchers);
enemyArchers.addActionListener(e -> ButtonClick.clicked(enemyArchers));
JButton enemyInfantry = new JButton("Enemy Infantry");
enemyInfantry.setName("Enemy Infantry"); buttonsEnemy.add(enemyInfantry);
enemyInfantry.addActionListener(e -> ButtonClick.clicked(enemyInfantry));
boxEnemies.add(Box.createVerticalStrut(150)); boxEnemies.add(enemyChannellers);
boxEnemies.add(Box.createVerticalStrut(40)); boxEnemies.add(enemyInfantry);
boxEnemies.add(Box.createVerticalStrut(40)); boxEnemies.add(enemyArchers);
boxEnemies.add(Box.createVerticalStrut(40));
enemies.add(boxEnemies);
JPanel messagePanel = new JPanel();
Box boxMessage = Box.createHorizontalBox();
log = new JTextArea("This is where battle updates will appear.", 36, 32);
logs = new JScrollPane(log, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
log.setWrapStyleWord(true);
log.setAlignmentY(20); log.setEditable(false);
logs.setSize(log.getWidth(), log.getHeight());
boxMessage.add(logs); boxMessage.add(Box.createVerticalStrut(100));
messagePanel.add(boxMessage);
JPanel actionPanel = new JPanel();
actionPanel.setBorder(BorderFactory.createTitledBorder("Available Actions"));
Box boxActions = Box.createHorizontalBox();
JButton newUnit = new JButton("New Unit");
newUnit.setName("new"); buttonsActions.add(newUnit);
newUnit.addActionListener(e -> ButtonClick.clicked(newUnit));
JButton attack = new JButton("Attack");
attack.setName("attack"); buttonsActions.add(attack);
attack.addActionListener(e -> ButtonClick.clicked(attack));
JButton train = new JButton("Train");
train.setName("train"); buttonsActions.add(train);
train.addActionListener(e -> ButtonClick.clicked(train));
JButton heal = new JButton("Heal");
heal.setName("heal"); buttonsActions.add(heal);
heal.addActionListener(e -> ButtonClick.clicked(heal));
JButton rest = new JButton("Rest");
rest.setName("rest"); buttonsActions.add(rest);
rest.addActionListener(e -> ButtonClick.clicked(rest));
JButton status = new JButton("Status Report");
status.setName("status"); buttonsActions.add(status);
status.addActionListener(e -> ButtonClick.clicked(status));
JButton cancel = new JButton("Cancel");
cancel.setName("cancel"); buttonsActions.add(cancel);
cancel.addActionListener(e -> ButtonClick.clicked(cancel));
boxActions.add(newUnit); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(attack); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(train); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(rest); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(heal); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(status); boxActions.add(Box.createHorizontalStrut(40));
boxActions.add(cancel);
actionPanel.add(boxActions);
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, enemies, messagePanel);
buttons.add(buttonsAlly);
buttons.add(buttonsActions);
buttons.add(buttonsEnemy);
this.add(actionPanel, BorderLayout.SOUTH);
this.add(allies, BorderLayout.WEST);
this.add(pane, BorderLayout.EAST);
this.add(battleField, BorderLayout.CENTER);
this.setVisible(true);
}
}

JComponent with JButton togather

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 :(

Java - Dynamic GridLayout

I am trying to create a dynamic GridLayout using the following code:
package resizablegui;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
class GUIHandler extends JFrame {
JSpinner widthSpinner;
JSpinner heightSpinner;
JPanel board;
private JPanel resizer() {
final JPanel resizer = new JPanel(new GridLayout(2,2));
final JPanel resizer_wrapper = new JPanel();
JLabel widthLabel;
JLabel heightLabel;
SpinnerModel widthModel;
SpinnerModel heightModel;
resizer_wrapper.setLayout(new BoxLayout(resizer_wrapper, BoxLayout.X_AXIS));
widthModel = new SpinnerNumberModel(8, 4, 32, 1);
heightModel = new SpinnerNumberModel(8, 4, 32, 1);
ResizeWindow onResize = new ResizeWindow();
widthLabel = new JLabel("Width: ");
resizer.add(widthLabel);
widthSpinner = new JSpinner(widthModel);
resizer.add(widthSpinner);
widthSpinner.addChangeListener(onResize);
heightLabel = new JLabel("Height: ");
resizer.add(heightLabel);
heightSpinner = new JSpinner(heightModel);
resizer.add(heightSpinner);
heightSpinner.addChangeListener(onResize);
resizer.setMaximumSize(new Dimension(100,100));
resizer_wrapper.add(resizer);
return resizer_wrapper;
}
private JPanel board(int width, int height) {
final JPanel board = new JPanel(new GridLayout(width, height));
for(int x = 0; x < width; x++) {
for(int y = 0; y < width; y++) {
JButton button = new JButton(x+", "+y);
board.add(button);
}
}
return board;
}
public GUIHandler() {
super("Board");
setLayout(new BorderLayout());
board = board(8,8);
add(resizer(), BorderLayout.NORTH);
add(board, BorderLayout.CENTER);
}
private class ResizeWindow implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
int width = (Integer)widthSpinner.getValue() * 45;
int height = (Integer)heightSpinner.getValue() * 45;
setSize(width,height);
}
}
}
public class ResizableGUI {
public static void main(String[] args) {
GUIHandler gui = new GUIHandler();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(350,350);
gui.setVisible(true);
}
}
The goal, as you can probably tell, is to have an 8x8 grid of buttons, that can be made larger (ex 9x10, 10x10...) or smaller (ex 6x8, 4x4) based on the values of the spinners. The code compiles well, but upon trying to resize the dialog, the program freezes and crashes.
Not sure why your code freezes and crashes, it didn't do that for me.
Anyway, I still see problems with your code.
Since you want a dynamic grid you need the ability to remove/add buttons to the grid as the spinner is used. So, I would create and empty "board" panel and add it to the GUI. Then I would rename your "boar(...)" method to "resetBoard(...)" as this method should be used to just remove/add buttons, not create a new panel.
The next problem is your looping code in this new "resetBoard(...)" method. The outer loop should be for the height and the inner loop for the width, since you will be adding rows of buttons to the grid, one at a time.
So the restructuring of this method might look like:
private void resetBoard(int width, int height) {
board.removeAll();
board.setLayout( new GridLayout(0, width) );
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
JButton button = new JButton(x+", "+y);
board.add(button);
}
}
}
So now you need to create the board and add buttons to it:
//board = board(8,8);
board = new JPanel();
resetBoard(8, 8);
Finally, in the ChangeListener you need to reset the button on the board, not change the size of the frame:
int width = (Integer)widthSpinner.getValue();
int height = (Integer)heightSpinner.getValue();
resetBoard(width,height);
board.revalidate();
//pack(); pack the frame is you wish
Also, when you first create the frame, don't set the size manually let the pack() method do the work for you:
//gui.setSize(350,350);
gui.pack();

drawing in swing Java

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
}
}

Categories