Java Swing - the best control for specific task - java

I need to divide java swing window into many fields, something similar to the table or chess board. Color of each cell should be dependent on the object which this cell represents (each object has coordinates, which are changing during the game, so the color of each cell is not constant).
Additionally, if the user clicks on the empty field (white color), then a new random object is created and this object is assigned to these field (and field color is changing).
Which of java swing controls will be the best for these functionalities?

If I were you I would make 2 panel classes(white and black), the white one with a MouseAdapter, so that when one of the panels is clicked you can pull a random JLabel from an array. Here's an example that might help (roughly 120 lines):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class ScratchPaper extends JFrame {
private static final long serialVersionUID = 1L;
private static final int GRIDSIZE = 8;
private JPanel[][] whitePanel = new WhitePanel[GRIDSIZE][GRIDSIZE];
private JPanel[][] blackPanel = new BlackPanel[GRIDSIZE][GRIDSIZE];
private Random rand = new Random();
JButton b1 = new JButton("Btn1");
JButton b2 = new JButton("Btn2");
JButton b3 = new JButton("Btn3");
JLabel l1 = new JLabel("Lbl1");
JLabel l2 = new JLabel("Lbl2");
JLabel l3 = new JLabel("Lbl3");
JPanel panel = new JPanel();
private JComponent[][] randObjects = {{b1, b2, b3}, {l1, l2, l3}, {panel, panel, panel}};
private Color[] randColors = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE, Color.MAGENTA};
public ScratchPaper() {
initGUI();
setTitle("EXAMPLE");
pack();
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void initGUI() {
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(GRIDSIZE, GRIDSIZE)); // makes 8*8 grid
add(centerPanel, BorderLayout.CENTER);
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Component clickedComp = findComponentAt(e.getPoint());
JPanel target = (JPanel) clickedComp;
panel.setBackground(randColors[rand.nextInt(randColors.length)]);
if (target instanceof WhitePanel){
target.add(randObjects[rand.nextInt(randObjects.length)][rand.nextInt(randObjects[0].length)]);
target.updateUI();
}
}
};
addMouseListener(ma);
for (int row=0; row<GRIDSIZE; row++) {
for (int col=0; col<GRIDSIZE; col++) {
whitePanel[row][col] = new WhitePanel(row, col);
blackPanel[row][col] = new BlackPanel(row, col);
if ((row%2 == 0 && col%2 == 0) || ((row+1)%2 == 0 && (col+1)%2 == 0)) {
centerPanel.add(whitePanel[row][col]);
}
else {
centerPanel.add(blackPanel[row][col]);
}
}
}
}
public static void main(String args[]) {
try {
String className = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(className);
} catch (Exception ex) {
System.out.println(ex);
}
EventQueue.invokeLater(new Runnable(){
#Override
public void run(){
new ScratchPaper();
}
});
}
class WhitePanel extends JPanel {
private static final int SIZE = 50;
public WhitePanel(int row, int col) {
Dimension size = new Dimension(SIZE, SIZE);
setPreferredSize(size);
setBackground(Color.WHITE);
}
}
class BlackPanel extends JPanel {
private static final int SIZE = 50;
public BlackPanel(int row, int col) {
Dimension size = new Dimension(SIZE, SIZE);
setPreferredSize(size);
setBackground(Color.BLACK);
}
}
}
Try running it! It's actually pretty fun!

Related

How to make all images in Grid Overlay flush?

I am trying to implement a GUI for a maze-based game I created that meets the following specific conditions:
The GUI itself has a set size and is not resizable (line 41) .
The master panel (line 57) that contains all the maze images is scrollable. All maze image components are flush with each other.
If maze is small enough, then entire maze will be visible in master panel.
If maze is very large, then user would need to scroll.
The master panel needs to be accessed by a mouse listener (line 130) that returns the component that is being clicked.
The following code seems to meet criteria 1 and 3, but fails criteria 2:
public class MazeGui extends JFrame implements DungeonView {
private final Board board;
public MazeGui(ReadOnlyModel m) {
//this.setSize(m.getNumRows()*100, m.getNumCols()*100);
this.setSize(600, 600);
this.setLocation(200, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.board = new Board(m);
JScrollPane scroller = new JScrollPane(board);
this.add(scroller, BorderLayout.CENTER);
setTitle("Dungeon Escape");
}
private class Board extends JPanel {
private ReadOnlyModel m;
public Board(ReadOnlyModel m) {
this.m = m;
GridLayout layout = new GridLayout(m.getNumRows(),m.getNumCols(), 0, 0);
// layout.setHgap(-100);
// layout.setVgap(-100);
this.setLayout(layout);
this.setSize(m.getNumRows()*64,m.getNumCols()*64);
for (int i = 0; i < m.getNumRows() * m.getNumCols(); i++) {
try {
// load resource from the classpath instead of a specific file location
InputStream imageStream = getClass().getResourceAsStream(String.format("/images/%s.png", m.getRoomDirections(i + 1)));
// convert the input stream into an image
Image image = ImageIO.read(imageStream);
// add the image to a label
JLabel label = new JLabel(new ImageIcon(image));
label.setPreferredSize(new Dimension(64, 64));
JPanel panel = new JPanel();
panel.setSize(64, 64);
String name = String.format("%d", i);
panel.setName(name);
panel.add(label);
// add the label to the JFrame
//this.layout.addLayoutComponent(TOOL_TIP_TEXT_KEY, label);
this.add(panel);
} catch (IOException e) {
JOptionPane.showMessageDialog(this, e.getMessage());
e.printStackTrace();
}
}
}
}
#Override
public void addClickListener(DungeonController listener) {
Board board = this.board;
MouseListener mouseListener = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(String.format("(%d,%d)", e.getX(), e.getY()));
JPanel panel = (JPanel) board.getComponentAt(e.getPoint());
System.out.println(panel.getName());
}
};
board.addMouseListener(mouseListener);
}
#Override
public void refresh() {
this.repaint();
}
#Override
public void makeVisible() {
this.setVisible(true);
}
}
Here is an image of what it produces:
First, I'd make use of a different layout manager, one which would try and expand to fit the size of the underlying container.
Then, I would let the components do their jobs. I don't know why you're adding the label to another panel, the panel doesn't seem to be adding additional functionality/features and is just adding to the complexity.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
List<Maze.Direction> directions = new ArrayList<>(32);
directions.add(Maze.Direction.EAST_SOUTH);
directions.add(Maze.Direction.EAST_SOUTH_WEST);
directions.add(Maze.Direction.EAST_SOUTH_WEST);
directions.add(Maze.Direction.EAST_SOUTH_WEST);
directions.add(Maze.Direction.EAST_SOUTH_WEST);
directions.add(Maze.Direction.SOUTH_WEST);
directions.add(Maze.Direction.NORTH_EAST_SOUTH);
directions.add(Maze.Direction.NORTH_EAST_SOUTH_WEST);
directions.add(Maze.Direction.NORTH_EAST_SOUTH_WEST);
directions.add(Maze.Direction.NORTH_EAST_SOUTH_WEST);
directions.add(Maze.Direction.NORTH_EAST_SOUTH_WEST);
directions.add(Maze.Direction.NORTH_SOUTH_WEST);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH_SOUTH);
directions.add(Maze.Direction.NORTH);
directions.add(Maze.Direction.NORTH);
directions.add(Maze.Direction.NORTH);
directions.add(Maze.Direction.NORTH);
directions.add(Maze.Direction.NORTH);
directions.add(Maze.Direction.NORTH);
System.out.println(directions.size());
Maze maze = new DefaultMaze(5, 6, directions);
MazeGui frame = new MazeGui(maze);
frame.addClickListener(null);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface Maze {
enum Direction {
EAST_SOUTH("EastSouth.png"), EAST_SOUTH_WEST("EastSouthWest.png"), SOUTH_WEST("SouthWest.png"),
NORTH_EAST_SOUTH("NorthEastSouth.png"), NORTH_EAST_SOUTH_WEST("NorthEastSouthWest.png"),
NORTH_SOUTH_WEST("NorthSouthWest.png"), NORTH_SOUTH("NorthSouth.png"), NORTH("North.png");
private BufferedImage image;
private Direction(String name) {
try {
image = ImageIO.read(getClass().getResource("/images/" + name));
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
public BufferedImage getImage() {
return image;
}
}
public int getRows();
public int getColumns();
public Direction getRoomDirections(int index);
}
public class DefaultMaze implements Maze {
int rows;
int columns;
private List<Direction> directions;
public DefaultMaze(int rows, int columns, List<Direction> directions) {
this.rows = rows;
this.columns = columns;
this.directions = directions;
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
#Override
public Direction getRoomDirections(int index) {
return directions.get(index);
}
}
public class MazeGui extends JFrame {
// Missing code
public interface DungeonController {
}
private final Board board;
public MazeGui(Maze m) {
this.setSize(600, 600);
this.setResizable(false);
this.board = new Board(m);
JScrollPane scroller = new JScrollPane(board);
this.add(scroller, BorderLayout.CENTER);
setTitle("Dungeon Escape");
}
public Board getBoard() {
return board;
}
public void addClickListener(DungeonController listener) {
Board board = getBoard();
board.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Component cell = board.getComponentAt(e.getPoint());
System.out.println(cell.getName());
board.highlight(cell.getBounds());
}
});
}
private class Board extends JPanel {
private Rectangle selectedCell;
private Maze maze;
public Board(Maze maze) {
this.maze = maze;
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < maze.getRows() * maze.getColumns(); index++) {
Maze.Direction direction = maze.getRoomDirections(index);
JLabel label = new JLabel(new ImageIcon(direction.getImage()));
label.setName(direction.name());
add(label, gbc);
gbc.gridx++;
if (gbc.gridx >= maze.getColumns()) {
gbc.gridx = 0;
gbc.gridy++;
}
}
// addMouseListener(new MouseAdapter() {
// #Override
// public void mouseClicked(MouseEvent e) {
// Component component = getComponentAt(e.getPoint());
// selectedCell = null;
// if (component != null) {
// selectedCell = component.getBounds();
// }
// repaint();
// }
// });
}
public void highlight(Rectangle bounds) {
selectedCell = bounds;
repaint();
}
#Override
public void paint(Graphics g) {
super.paint(g);
if (selectedCell != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(0, 0, 255, 128));
g2d.fill(selectedCell);
g2d.dispose();
}
}
}
}
}
The GUI itself has a set size and is not resizable
So the issue here is that you are forcing the "board" panel to have an arbitrary size.
this.setSize(600, 600);
The actual size of the panel should be 8 * 64 = 512. So extra space is being added to each grid.
Don't hardcode size values.
It is the job of the layout manager to determine the preferred size of each component.
So instead of using setSize(...) you should pack() the frame before making it visible:
this.pack();
this.setVisible(true);
When you do this you will see that the maze fits completely in the frame.
If you want extra space around the maze then you need to add a "border" to your board:
setBorder( new EmptyBorder(88, 88, 88, 88) );
GridLayout layout = new GridLayout(m.getNumRows(),m.getNumCols(), 0, 0);
Turns out I should have been using GridBagLayout!
There is no need to change layout managers, only use the layout managers more effectively.
If you really for some reason need to specify a fixed frame size then you can make the following change:
//this.add(scroller, BorderLayout.CENTER);
JPanel wrapper = new JPanel( new GridBagLayout() );
wrapper.add(scroller, new GridBagConstraints());
this.add(wrapper, BorderLayout.CENTER);
This will allow the "board" panel to be displayed at its preferred size and the "board" panel will be centered in its parent container.
Using these tips will help you effectively create more complicated layouts.

JMenuItems not responding

I have created a 3x3 memory game with colors. The program runs and displays the colors, but the JMenuBar is not working correctly. The button new board, play and end game are not working. Is there something wrong with my Actionlistener?
This is how the code should be working : https://gyazo.com/9bf3e073a9c455e56d9b4403586bfaf5?fbclid=IwAR3Zk1BZvRj49CtAz01h95zic8tk74UmyUcU2HrY3VY8XcARoD14Ke6tcoQ
This is StartPlayer
import gui.MemoryGameWindow;
import gui.ColoredPanel;
import gui.GamePanel;
public class StartPlayer {
public static void main(String[] args) {
new MemoryGameWindow();
}
}
This is ColoredPanel
package gui;
import java.awt.Color;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class ColoredPanel extends JPanel {
private Color thisColor = null;
private Color challenge = null;
public ColoredPanel(Color color) {
this.thisColor = color;
setBackground(color);
}
public void setGameMode(Color c, MouseListener ml) {
setBackground(Color.LIGHT_GRAY);
this.challenge = c;
System.out.println("Coloredpanel says challenge is " + this.challenge);
addMouseListener(ml);
}
public void restoreBackground() {
setBackground(this.thisColor);
}
}
This is GamePanel
package gui;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GamePanel extends JPanel {
private Color[] colors = new Color[] { Color.GREEN, Color.YELLOW, Color.MAGENTA };
private Random r = new Random();
private int square = 9;
private Color challenge;
private int countOfPossibleHits = 0;
private int countOfWinnerHits = 0;
private JPanel challengeDisplay;
public GamePanel(JPanel cd) {
this.challengeDisplay = cd;
setLayout(new GridLayout(3, 0, 2, 2));
for (int i = 0; i < this.square; i++)
add(new ColoredPanel(this.colors[this.r.nextInt(this.colors.length)]));
}
public Color startGame() {
Color[] existingColors = new Color[getComponentCount()];
int i;
for (i = 0; i < getComponentCount(); i++)
existingColors[i] = ((ColoredPanel)getComponent(i)).getBackground();
this.challenge = existingColors[this.r.nextInt(existingColors.length)];
this.countOfPossibleHits = 0;
for (i = 0; i < getComponentCount(); i++) {
if (((ColoredPanel)getComponent(i)).getBackground() == this.challenge)
this.countOfPossibleHits++;
}
for (i = 0; i < getComponentCount(); i++)
((ColoredPanel)getComponent(i)).setGameMode(this.challenge, new TheMouselistener());
return this.challenge;
}
class TheMouselistener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
ColoredPanel clickedObject = (ColoredPanel)e.getSource();
clickedObject.restoreBackground();
if (clickedObject.getBackground() != GamePanel.this.challenge) {
clickedObject.add(new JLabel("Game Over!"));
GamePanel.this.challengeDisplay.add(new JLabel("Game Over!"));
System.out.println("Game Over");
GamePanel.this.updateUI();
} else {
GamePanel.this.countOfWinnerHits = GamePanel.this.countOfWinnerHits + 1;
if (GamePanel.this.countOfWinnerHits == GamePanel.this.countOfPossibleHits) {
clickedObject.add(new JLabel("You won!"));
GamePanel.this.challengeDisplay.add(new JLabel("You Won!"));
GamePanel.this.updateUI();
}
}
}
}
}
This is MemoryGameWindow
package gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class MemoryGameWindow extends JFrame implements ActionListener {
private JMenuItem newgame = null;
private JMenuItem playgame = null;
private JMenuItem exit = null;
private GamePanel gamepanel = null;
private JPanel challengeDisplay;
public MemoryGameWindow() {
setTitle("memory game");
setLayout(new BorderLayout(5, 5));
add(this.challengeDisplay = new JPanel() {
}, "North");
add(this.gamepanel = new GamePanel(this.challengeDisplay));
setJMenuBar(new GameMenubar(this));
setSize(600, 600);
setLocationRelativeTo((Component)null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object s = e.getSource();
if (s == this.newgame) {
remove(this.gamepanel);
remove(this.challengeDisplay);
add(this.challengeDisplay = new JPanel() {
}, "North");
add(this.gamepanel = new GamePanel(this.challengeDisplay));
this.playgame.setEnabled(true);
this.gamepanel.updateUI();
}
if (s == this.playgame) {
Color challenge = this.gamepanel.startGame();
this.challengeDisplay.setBackground(challenge);
this.playgame.setEnabled(false);
this.gamepanel.updateUI();
}
if (s == this.exit)
System.exit(0);
}
class GameMenubar extends JMenuBar {
public GameMenubar(MemoryGameWindow memoryGameWindow) {
JMenu file;
add(file = new JMenu("File"));
MemoryGameWindow.this.newgame = new JMenuItem("new board");
file.add(new JMenuItem("new board"));
MemoryGameWindow.this.playgame = new JMenuItem("play");
file.add(new JMenuItem("play"));
MemoryGameWindow.this.exit = new JMenuItem("end program");
file.add(new JMenuItem("end program"));
MemoryGameWindow.this.newgame.addActionListener(memoryGameWindow);
MemoryGameWindow.this.playgame.addActionListener(memoryGameWindow);
MemoryGameWindow.this.exit.addActionListener(memoryGameWindow);
}
}
}
Have a look at these two lines:
MemoryGameWindow.this.playgame = new JMenuItem("play");
file.add(new JMenuItem("play"));
First, you set the value of playgame to new JMenuItem. Later in the code, you add an ActionListener to it. That is all correct.
The problem is, the JMenuItem with the ActionListener added to it is not what you’re adding to the menu bar. Instead, you’re adding a brand new JMenuItem, which has no ActionListeners added to it.
The fix is as simple as:
file.add(MemoryGameWindow.this.playgame);
Obviously, you will need to do this for your other menu items too.

JLabel Update from another class

I am currently having an issue incrementing a points counter in combination with a MouseListener event. Here is my current Progress so far (with some irrelevant code removed)
import java.awt.*;
import javax.swing.*;
import java.awt.Color.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.util.Random;
public class Checkers extends JFrame
{
Random random = new Random();
private final int ROWS = 2;
private final int COLS = 5;
private final int GAP = 2;
private final int NUM = ROWS * COLS;
private int x;
public static int score;
private JPanel pane = new JPanel(new GridLayout(ROWS,COLS, GAP,GAP));
public JLabel lbl1 = new JLabel ("score: " + score);
private MyPanel [] panel = new MyPanel[NUM];
private Color col1 = Color.RED;
private Color col2 = Color.WHITE;
private Color tempColor;
public Checkers()
{
super("Checkers");
setSize(600,600);
setVisible(true);
setBackground(Color.BLACK);
setBoard();
}
//pane background colour and the size of this pane.
pane.setBackground(Color.BLACK);
pane.setPreferredSize(new Dimension(300,300));
//pane background colour and size of this pane.
pane2.setBackground(Color.white);
pane2.setPreferredSize(new Dimension(300,300));
//directions on the board where these panes appear.
add(pane, BorderLayout.WEST);
add(pane2, BorderLayout.EAST);
pane2.add(lbl1);
pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS));
And the MyPanel class
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class MyPanel extends JPanel implements MouseListener {
public MyPanel() {
addMouseListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {
setBackground(Color.BLACK);
Checkers.score++;
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
Expected Result - Once one of the smaller panels within the first pane are clicked, the score counter in pane2 is increased by 1, and this keeps going until they have all been clicked and score can't further be increased.
Current Result - The score does increment, but not in the way it should, instead, the points carry over to the next instance of the GUI (eg, if 3 panels are clicked in the first instance, the points will still stay 0 in this first instance, but once a new GUI is created, the points counter will be 3) which is not what i'm after.
Any help/guidance welcome.

Having selected JButton from a 2d array perform an action

I have a 2 dimensional array of JButtons, and I would like to be able to have the button that my mouse is over to perform an action, such as change color. How can I do this? Thanks.
Here is how I am creating the buttons:
for(int r = 0;r<10;r++){
for(int c = 0;c<10;c++){
buttonArray[r][c] = new JButton();
}
}
Here is an example using a loop and a MouseAdapter (since you don't need all the methods from MouseListener ) :
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JButtonHighlighter extends JPanel {
public static void main(final String[] args) {
JFrame frame = new JFrame();
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new GridLayout(10, 10));
JButton[][] buttonArray = new JButton[10][10];
for (int r = 0; r < 10; r++) {
for (int c = 0; c < 10; c++) {
final JButton newButton = new JButton();
final Color originalColor = newButton.getBackground();
final Color highlightColor = Color.GREEN;
newButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(final MouseEvent e) {
newButton.setBackground(highlightColor);
}
#Override
public void mouseExited(final MouseEvent e) {
newButton.setBackground(originalColor);
}
});
buttonArray[r][c] = newButton;
contentPanel.add(newButton);
}
}
frame.setContentPane(contentPanel);
frame.setSize(100, 100);
frame.setVisible(true);
}
}

Alignment of button is not coming proper in right side and size of right component is too much

I wrote a program which create a Frame which will display a Control panel and Visual panel.But buttons in control panel is taking too much space. So any body has any idea how to fix it ?? Given is the code.
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
/**
* This class generates and displays a visualization of a Sierpinski
*
*/
public class tOpost
{
private JFrame window;
private JTextField depthTextField;
private Canvas visual;
// declare and initialize default values
private int canvasSize = 512;
/**
* Creates a new window and displays a visualization of a Mandelbrot set
*/
public tOpost()
{
// create new window
window = new JFrame("Sierpinski Visulaizer");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new FlowLayout(FlowLayout.LEFT));
// create main panel
JPanel mainPanel = new JPanel(new GridLayout(0,1));
// create textfields with labels
JPanel depthField = new JPanel(new FlowLayout());
depthField.add(new JLabel("Recursive Depth: "));
depthTextField = new JTextField("");
depthTextField.setPreferredSize(new Dimension(80,25));
depthField.add(depthTextField);
// create comboBoxes
JPanel panel2 = new JPanel();
String[] colorText= {"Blue", "Green"};
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
JPanel[] jPanels = new JPanel[5];
for (int i = 0; i<5; i++) {
JPanel depthColorPanel = new JPanel();
depthColorPanel.add(new JLabel("Color " + (i + 1) + ": "));
JComboBox comboBox = new JComboBox(colorText);
comboBox.setSelectedItem("Blue");
depthColorPanel.add(comboBox);
jPanels[i] = depthColorPanel;
}
JPanel randomColorPanel = new JPanel();
JCheckBox randomColorButton = new JCheckBox("Randomize color at each level");
randomColorButton.setMnemonic(KeyEvent.VK_G);
randomColorButton.setSelected(false);
randomColorPanel.add(randomColorButton);
// create panel for controls
panel2.add(depthField);
for (JPanel panel : jPanels) {
panel2.add(panel);
}
panel2.add(randomColorPanel);
// create button
JPanel germinatePanel = new JPanel(new FlowLayout());
JButton germinateButton = new JButton("Draw");
germinatePanel.add(germinateButton);
mainPanel.add(panel2);
mainPanel.add(germinatePanel);
// create canvas for visualization
visual = new Canvas();
visual.setBackground(Color.BLACK);
visual.setPreferredSize(new Dimension(canvasSize, canvasSize));
mainPanel.setMinimumSize(new Dimension(100, 100));
mainPanel.setPreferredSize(new Dimension(250,canvasSize));
mainPanel.setLocation(750, 250);
// pack widgets and display window
window.add(visual);
window.add(mainPanel);
window.pack();
window.setVisible(true);
System.out.println(mainPanel.getSize().getHeight()+","+ mainPanel.getSize().getWidth());
}
/**
* Draws Triangle.
*
* #param x
* #param y
* #param s
* #param color
*/
/**
* Starts the program by creating a new instance of the Triangle class.
*/
public static void main(String[] args)
{
new tOpost();
}
}
don't mixing AWT Components with Swing JComponents, since is possible, but still caused with a few issues
don't declare for mainPanel.setSize(100,100);, let this is job for proper LayoutManager
JPanel depthField = new JPanel(new FlowLayout());, FlowLayout accepting PreferredSize that came from JComponents
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS)); BoxLayout accepting PreferredSize that returns JComponents
JPanel has implemented FlowLayout by default (without any definitions of LayoutManager)
you have to override proper method for Painting in the standard Java GUI
for AWT Components use method paint()
for Swing JComponents use method paintComponent()
.
.
EDIT
.
.
this code will help you with workaround for JComboBox
code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.border.LineBorder;
import javax.swing.event.EventListenerList;
class ColorComboBoxEditor implements ComboBoxEditor {
final protected JButton editor;
private EventListenerList listenerList = new EventListenerList();
ColorComboBoxEditor(Color initialColor) {
editor = new JButton("");
editor.setBackground(initialColor);
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Color currentBackground = editor.getBackground();
Color color = JColorChooser.showDialog(editor, "Color Chooser", currentBackground);
if ((color != null) && (currentBackground != color)) {
editor.setBackground(color);
fireActionEvent(color);
}
}
};
editor.addActionListener(actionListener);
}
#Override
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
#Override
public Component getEditorComponent() {
return editor;
}
#Override
public Object getItem() {
return editor.getBackground();
}
#Override
public void removeActionListener(ActionListener l) {
listenerList.remove(ActionListener.class, l);
}
#Override
public void selectAll() {
}
#Override
public void setItem(Object newValue) {
if (newValue instanceof Color) {
Color color = (Color) newValue;
editor.setBackground(color);
} else {
try {
Color color = Color.decode(newValue.toString());
editor.setBackground(color);
} catch (NumberFormatException e) {
}
}
}
protected void fireActionEvent(Color color) {
Object listeners[] = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ActionListener.class) {
ActionEvent actionEvent = new ActionEvent(editor, ActionEvent.ACTION_PERFORMED, color.toString());
((ActionListener) listeners[i + 1]).actionPerformed(actionEvent);
}
}
}
}
class ColorCellRenderer implements ListCellRenderer {
private DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
private final static Dimension preferredSize = new Dimension(0, 20);
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof Color) {
renderer.setBackground((Color) value);
}
if (cellHasFocus || isSelected) {
renderer.setBorder(new LineBorder(Color.DARK_GRAY));
} else {
renderer.setBorder(null);
}
renderer.setPreferredSize(preferredSize);
return renderer;
}
}
class ColorComboBoxEditorRendererDemo {
public ColorComboBoxEditorRendererDemo() {
Color colors[] = {Color.BLACK, Color.BLUE, Color.GREEN, Color.RED, Color.WHITE, Color.YELLOW};
JFrame frame = new JFrame("Color JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JComboBox comboBox = new JComboBox(colors);
comboBox.setEditable(true);
comboBox.setRenderer(new ColorCellRenderer());
Color color = (Color) comboBox.getSelectedItem();
ComboBoxEditor editor = new ColorComboBoxEditor(color);
comboBox.setEditor(editor);
frame.add(comboBox, BorderLayout.NORTH);
final JLabel label = new JLabel();
label.setOpaque(true);
label.setBackground((Color) comboBox.getSelectedItem());
frame.add(label, BorderLayout.CENTER);
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
Color selectedColor = (Color) comboBox.getSelectedItem();
label.setBackground(selectedColor);
}
};
comboBox.addActionListener(actionListener);
frame.setSize(300, 200);
frame.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ColorComboBoxEditorRendererDemo colorComboBoxEditorRendererDemo = new ColorComboBoxEditorRendererDemo();
}
});
}
}

Categories

Resources