I am trying to hide a JSplitPane with animation. By hide, I mean to setDividerLocation(0) so its left component is invisible (technically it is visible, but with zero width):
public class SplitPaneTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
JPanel rightPanel = new JPanel(new GridLayout(60, 60));
for (int i = 0; i < 60 * 60; i++) {
// rightPanel.add(new JLabel("s"));
}
rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
frame.add(splitPane);
JButton button = new JButton("Press me to hide");
button.addActionListener(e -> hideWithAnimation(splitPane));
leftPanel.add(button, BorderLayout.PAGE_START);
frame.setMaximumSize(new Dimension(800, 800));
frame.setSize(800, 800);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
private static void hideWithAnimation(JSplitPane splitPane) {
final Timer timer = new Timer(10, null);
timer.addActionListener(e -> {
splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
if (splitPane.getDividerLocation() == 0)
timer.stop();
});
timer.start();
}
}
If you run it, will see that everything seems good, and the animation runs smooth.
However, in the real application the right of the JSplitPane is a JPanel with CardLayout and each card has a lot of components.
If you uncomment this line in order to simulate the number of components:
// rightPanel.add(new JLabel("s"));
and re-run the above example, you will see that the animation no longer runs smoothly. So, the question is, is is possible to make it smooth(-ier)?
I have no idea how to approach a solution - if any exists.
Based on my research, I registered a global ComponentListener:
Toolkit.getDefaultToolkit()
.addAWTEventListener(System.out::println, AWTEvent.COMPONENT_EVENT_MASK);
and saw the tons of events that are being fired. So, I think the source of the problem is the tons of component events that are being fired for each component. Also, it seems that components with custom renderers (like JList - ListCellRenderer and JTable - TableCellRenderer), component events are firing for all of the renderers. For example, if a JList has 30 elements, 30 events (component) will be fired only for it. It also seems (and that's why I mentioned it) that for CardLayout, events are taking place for the "invisible" components as well.
I know that 60*60 might sound crazy to you, but in a real application (mine has ~1500) as it makes sense, the painting is heavier.
I know that 60*60 might sound crazy to you, but in a real application (mine has ~1500) as it makes sense, the painting is heavier.
The layout manager is invoked every time the divider location is changed which would add a lot of overhead.
One solution might be to stop invoking the layout manager as the divider is animating. This can be done by overriding the doLayout() method of the right panel:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SplitPaneTest2 {
public static boolean doLayout = true;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
JPanel rightPanel = new JPanel(new GridLayout(60, 60))
{
#Override
public void doLayout()
{
if (SplitPaneTest2.doLayout)
super.doLayout();
}
};
for (int i = 0; i < 60 * 60; i++) {
rightPanel.add(new JLabel("s"));
}
rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
frame.add(splitPane);
JButton button = new JButton("Press me to hide");
button.addActionListener(e -> hideWithAnimation(splitPane));
leftPanel.add(button, BorderLayout.PAGE_START);
frame.setMaximumSize(new Dimension(800, 800));
frame.setSize(800, 800);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
private static void hideWithAnimation(JSplitPane splitPane) {
SplitPaneTest2.doLayout = false;
final Timer timer = new Timer(10, null);
timer.addActionListener(e -> {
splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
if (splitPane.getDividerLocation() == 0)
{
timer.stop();
SplitPaneTest2.doLayout = true;
splitPane.getRightComponent().revalidate();
}
});
timer.start();
}
}
Edit:
I was not going to include my test on swapping out the panel full of components with a panel that uses an image of components since I fell the animation is the same, but since it was suggested by someone else here is my attempt for your evaluation:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
public class SplitPaneTest2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
JPanel rightPanel = new JPanel(new GridLayout(60, 60));
for (int i = 0; i < 60 * 60; i++) {
rightPanel.add(new JLabel("s"));
}
rightPanel.setBorder(BorderFactory.createLineBorder(Color.red));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
frame.add(splitPane);
JButton button = new JButton("Press me to hide");
button.addActionListener(e -> hideWithAnimation(splitPane));
leftPanel.add(button, BorderLayout.PAGE_START);
frame.setMaximumSize(new Dimension(800, 800));
frame.setSize(800, 800);
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
private static void hideWithAnimation(JSplitPane splitPane) {
Component right = splitPane.getRightComponent();
Dimension size = right.getSize();
BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
right.paint( g );
g.dispose();
JLabel label = new JLabel( new ImageIcon( bi ) );
label.setHorizontalAlignment(JLabel.LEFT);
splitPane.setRightComponent( label );
splitPane.setDividerLocation( splitPane.getDividerLocation() );
final Timer timer = new Timer(10, null);
timer.addActionListener(e -> {
splitPane.setDividerLocation(Math.max(0, splitPane.getDividerLocation() - 3));
if (splitPane.getDividerLocation() == 0)
{
timer.stop();
splitPane.setRightComponent( right );
}
});
timer.start();
}
}
#GeorgeZ. I think the concept presented by #camickr has to do with when you actually do the layout. As an alternative to overriding doLayout, I would suggest subclassing the GridLayout to only lay out the components at the end of the animation (without overriding doLayout). But this is the same concept as camickr's.
Although if the contents of your components in the right panel (ie the text of the labels) remain unchanged during the animation of the divider, you can also create an Image of the right panel when the user clicks the button and display that instead of the actual panel. This solution, I would imagine, involves:
A CardLayout for the right panel. One card has the actual rightPanel contents (ie the JLabels). The second card has only one JLabel which will be loaded with the Image (as an ImageIcon) of the first card.
As far as I know, by looking at the CardLayout's implementation, the bounds of all the child components of the Container are set during layoutContainer method. That would probably mean that the labels would be layed out inspite being invisible while the second card would be shown. So you should probably combine this with the subclassed GridLayout to lay out only at the end of the animation.
To draw the Image of the first card, one should first create a BufferedImage, then createGraphics on it, then call rightPanel.paint on the created Graphics2D object and finally dispose the Graphics2D object after that.
Create the second card such that the JLabel would be centered in it. To do this, you just have to provide the second card with a GridBagLayout and add only one Component in it (the JLabel) which should be the only. GridBagLayout always centers the contents.
Let me know if such a solution could be useful for you. It might not be useful because you could maybe want to actually see the labels change their lay out profile while the animation is in progress, or you may even want the user to be able to interact with the Components of the rightPanel while the animation is in progress. In both cases, taking a picture of the rightPanel and displaying it instead of the real labels while the animation takes place, should not suffice. So it really depends, in this case, on how dynamic will be the content of the rightPanel. Please let me know in the comments.
If the contents are always the same for every program run, then you could probably pre-create that Image and store it. Or even, a multitude of Images and store them and just display them one after another when the animation turns on.
Similarly, if the contents are not always the same for every program run, then you could also subclass GridLayout and precalculate the bounds of each component at startup. Then that would make GridLayout a bit faster in laying out the components (it would be like encoding a video with the location of each object), but as I am testing it, GridLayout is already fast: it just calculates about 10 variables at the start of laying out, and then imediately passes over to setting the bounds of each Component.
Edit 1:
And here is my attempt of my idea (with the Image):
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.IntBinaryOperator;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SplitPaneTest {
//Just a Timer which plays the animation of the split pane's divider going from side to side...
public static class SplitPaneAnimationTimer extends Timer {
private final JSplitPane splitPane;
private int speed, newDivLoc;
private IntBinaryOperator directionf;
private Consumer<SplitPaneAnimationTimer> onFinish;
public SplitPaneAnimationTimer(final int delay, final JSplitPane splitPane) {
super(delay, null);
this.splitPane = Objects.requireNonNull(splitPane);
super.setRepeats(true);
super.setCoalesce(false);
super.addActionListener(e -> {
splitPane.setDividerLocation(directionf.applyAsInt(newDivLoc, splitPane.getDividerLocation() + speed));
if (newDivLoc == splitPane.getDividerLocation()) {
stop();
if (onFinish != null)
onFinish.accept(this);
}
});
speed = 0;
newDivLoc = 0;
directionf = null;
onFinish = null;
}
public int getSpeed() {
return speed;
}
public JSplitPane getSplitPane() {
return splitPane;
}
public void play(final int newDividerLocation, final int speed, final IntBinaryOperator directionf, final Consumer<SplitPaneAnimationTimer> onFinish) {
if (newDividerLocation != splitPane.getDividerLocation() && Math.signum(speed) != Math.signum(newDividerLocation - splitPane.getDividerLocation()))
throw new IllegalArgumentException("Speed needs to be in the direction towards the newDividerLocation (from the current position).");
this.directionf = Objects.requireNonNull(directionf);
newDivLoc = newDividerLocation;
this.speed = speed;
this.onFinish = onFinish;
restart();
}
}
//Just a GridLayout subclassed to only allow laying out the components only if it is enabled.
public static class ToggleGridLayout extends GridLayout {
private boolean enabled;
public ToggleGridLayout(final int rows, final int cols) {
super(rows, cols);
enabled = true;
}
#Override
public void layoutContainer(final Container parent) {
if (enabled)
super.layoutContainer(parent);
}
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
}
//How to create a BufferedImage (instead of using the constructor):
private static BufferedImage createBufferedImage(final int width, final int height, final boolean transparent) {
final GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
final GraphicsDevice gdev = genv.getDefaultScreenDevice();
final GraphicsConfiguration gcnf = gdev.getDefaultConfiguration();
return transparent
? gcnf.createCompatibleImage(width, height, Transparency.TRANSLUCENT)
: gcnf.createCompatibleImage(width, height);
}
//This is the right panel... It is composed by two cards: one for the labels and one for the image.
public static class RightPanel extends JPanel {
private static final String CARD_IMAGE = "IMAGE",
CARD_LABELS = "LABELS";
private final JPanel labels, imagePanel; //The two cards.
private final JLabel imageLabel; //The label in the second card.
private final int speed; //The speed to animate the motion of the divider.
private final SplitPaneAnimationTimer spat; //The Timer which animates the motion of the divider.
private String currentCard; //Which card are we currently showing?...
public RightPanel(final JSplitPane splitPane, final int delay, final int speed, final int rows, final int cols) {
super(new CardLayout());
super.setBorder(BorderFactory.createLineBorder(Color.red));
spat = new SplitPaneAnimationTimer(delay, splitPane);
this.speed = Math.abs(speed); //We only need a positive (absolute) value.
//Label and panel of second card:
imageLabel = new JLabel();
imageLabel.setHorizontalAlignment(JLabel.CENTER);
imageLabel.setVerticalAlignment(JLabel.CENTER);
imagePanel = new JPanel(new GridBagLayout());
imagePanel.add(imageLabel);
//First card:
labels = new JPanel(new ToggleGridLayout(rows, cols));
for (int i = 0; i < rows * cols; ++i)
labels.add(new JLabel("|"));
//Adding cards...
final CardLayout clay = (CardLayout) super.getLayout();
super.add(imagePanel, CARD_IMAGE);
super.add(labels, CARD_LABELS);
clay.show(this, currentCard = CARD_LABELS);
}
//Will flip the cards.
private void flip() {
final CardLayout clay = (CardLayout) getLayout();
final ToggleGridLayout labelsLayout = (ToggleGridLayout) labels.getLayout();
if (CARD_LABELS.equals(currentCard)) { //If we are showing the labels:
//Disable the laying out...
labelsLayout.setEnabled(false);
//Take a picture of the current panel state:
final BufferedImage pic = createBufferedImage(labels.getWidth(), labels.getHeight(), true);
final Graphics2D g2d = pic.createGraphics();
labels.paint(g2d);
g2d.dispose();
imageLabel.setIcon(new ImageIcon(pic));
imagePanel.revalidate();
imagePanel.repaint();
//Flip the cards:
clay.show(this, currentCard = CARD_IMAGE);
}
else { //Else if we are showing the image:
//Enable the laying out...
labelsLayout.setEnabled(true);
//Revalidate and repaint so as to utilize the laying out of the labels...
labels.revalidate();
labels.repaint();
//Flip the cards:
clay.show(this, currentCard = CARD_LABELS);
}
}
//Called when we need to animate fully left motion (ie until reaching left side):
public void goLeft() {
final JSplitPane splitPane = spat.getSplitPane();
final int currDivLoc = splitPane.getDividerLocation(),
minDivLoc = splitPane.getMinimumDividerLocation();
if (CARD_LABELS.equals(currentCard) && currDivLoc > minDivLoc) { //If the animation is stopped:
flip(); //Show the image label.
spat.play(minDivLoc, -speed, Math::max, ignore -> flip()); //Start the animation to the left.
}
}
//Called when we need to animate fully right motion (ie until reaching right side):
public void goRight() {
final JSplitPane splitPane = spat.getSplitPane();
final int currDivLoc = splitPane.getDividerLocation(),
maxDivLoc = splitPane.getMaximumDividerLocation();
if (CARD_LABELS.equals(currentCard) && currDivLoc < maxDivLoc) { //If the animation is stopped:
flip(); //Show the image label.
spat.play(maxDivLoc, speed, Math::min, ignore -> flip()); //Start the animation to the right.
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
leftPanel.setBorder(BorderFactory.createLineBorder(Color.green));
int rows, cols;
rows = cols = 60;
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
final RightPanel rightPanel = new RightPanel(splitPane, 10, 3, rows, cols);
splitPane.setLeftComponent(leftPanel);
splitPane.setRightComponent(rightPanel);
JButton left = new JButton("Go left"),
right = new JButton("Go right");
left.addActionListener(e -> rightPanel.goLeft());
right.addActionListener(e -> rightPanel.goRight());
final JPanel buttons = new JPanel(new GridLayout(1, 0));
buttons.add(left);
buttons.add(right);
frame.add(splitPane, BorderLayout.CENTER);
frame.add(buttons, BorderLayout.PAGE_START);
frame.setSize(1000, 800);
frame.setMaximumSize(frame.getSize());
frame.setLocationByPlatform(true);
frame.setVisible(true);
splitPane.setDividerLocation(0.5);
});
}
}
The goal is to create a create a game like rubrics cube where the user has to rearrange the buttons according to the matched color. This is what I did to place the buttons randomly, but it doesn't work when the buttons are presented. The random order is taken as the ordered order if that makes sense. Any ideas on how to fix this?
while(list1.size()!=501){
int x=rand.nextInt(8);
list1.add(x);
}
while(list2.size()!=501){
int x=rand.nextInt(8);
list2.add(x);
}
for(int b=0;b<500;b++){
int l= list1.get(b);
//System.out.println(l);
int j= list2.get(b);
panel.add(buttons[l][j]);
//System.out.println(buttons[l][j].getBackground());
}
Consider:
Giving the buttons a value of some sort that represents their true order. There are several ways to do this, including putting them in an array of specified order, or extending JButton and giving your class an int value field, or using a HashMap
Place these buttons into an ArrayList<JButton>
Shuffling the ArrayList via Collections.shuffle(...)
Then adding the buttons to your GUI
Alternatively, you could use non-shuffled JButtons and instead shuffle AbstractActions which you then set into the buttons.
The details of any solution will depend on the details of your current program, something that we don't yet know enough about. If you need more detailed help, do consider creating and posting a valid MCVE in your question.
For example, compile and run this, and then read the comments:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.*;
public class RandomButtons extends JPanel {
private static final long serialVersionUID = 1L;
private static final int ROWS = 8;
private JButton[][] buttons = new JButton[ROWS][ROWS];
private List<JButton> buttonList = new ArrayList<>();
private JPanel buttonsPanel = new JPanel(new GridLayout(ROWS, ROWS));
public RandomButtons() {
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[i].length; j++) {
// create new JBUtton
final JButton button = new JButton("Button");
// put into array
buttons[i][j] = button;
// put into ArrayList
buttonList.add(button);
// unique value 0 to 63 for each button
// order it has been created
final int value = i * ROWS + j;
// create one of 64 different color hues using value above
float hue = ((float) value) / (ROWS * ROWS);
float sat = 0.7f; // reduce sat so we can see text
float brightness = 1.0f;
Color color = Color.getHSBColor(hue, sat, brightness);
button.setBackground(color); // set button's color
button.addActionListener(e -> {
// display the button's order
System.out.println("Value: " + value);
});
}
}
randomizeButtons();
JButton randomizeButton = new JButton("Randomize");
randomizeButton.addActionListener(e -> { randomizeButtons(); });
JButton orderButton = new JButton("Put in Order");
orderButton.addActionListener(e -> { orderButtons(); });
JPanel bottomPanel = new JPanel(new GridLayout(1, 2));
bottomPanel.add(randomizeButton);
bottomPanel.add(orderButton);
setLayout(new BorderLayout());
add(buttonsPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
public void randomizeButtons() {
buttonsPanel.removeAll(); // remove all buttons
Collections.shuffle(buttonList); // shuffle the ArrayList
// re-add the buttons **using the ArrayList**
for (JButton jButton : buttonList) {
buttonsPanel.add(jButton);
}
// tell JPanel to layout its newly added components
buttonsPanel.revalidate();
// and then paint them
buttonsPanel.repaint();
}
public void orderButtons() {
buttonsPanel.removeAll(); // remove all buttons
// re-add the buttons **using the 2D array**
for (JButton[] buttonRow : buttons) {
for (JButton jButton : buttonRow) {
buttonsPanel.add(jButton);
}
}
buttonsPanel.revalidate();
buttonsPanel.repaint();
}
private static void createAndShowGui() {
RandomButtons mainPanel = new RandomButtons();
JFrame frame = new JFrame("RandomButtons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
I have another problem with my project. I have created this GameBoard made out of JButtons (it works as it's supposed to now) but I would need to add it to a JPanel. I need to display other things (in other panels) in the window. But when I tried to add the Button Array to a panel, and add that panel to the window, crazy things started happening (the buttons were very small, the grid was completely broken etc.). How could I add this Button Array to a JPanel and put that in the center of the window?
Here is my code:
package city;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameBoard extends JFrame implements ActionListener {
// The overall box count in chess board
public static final int squareCount = 64;
// The Array of buttons (the GameBoard itself)
public Button[][] button = new Button[8][8];
// Colors for all the buttons
public Color defaultColor = Color.WHITE;
public Color darkRedColor = Color.RED;
public Color darkBlueColor = Color.BLUE;
public Color lightBlueColor = Color.CYAN;
public Color lightRedColor = Color.PINK;
public GameBoard(String title) {
// Creates the buttons in the array
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
button[i][j] = new Button();
add(button[i][j]);
button[i][j].setBackground(defaultColor);
}
}
// Build the window
this.setTitle(title); // Setting the title of board
this.setLayout(new GridLayout(8, 18)); // GridLayout will arrange elements in Grid Manager 8 X 8
this.setSize(650, 650); // Size of the chess board
this.setVisible(true); // Sets the board visible
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // If you close the window, the program will terminate
this.setResizable(false); //The window is not resizable anymore ;)
// Sets some text on the buttons
button[0][3].setText("Red's");
button[0][4].setText("Gate");
button[7][3].setText("Blue's");
button[7][4].setText("Gate");
// Colors the buttons
newGame();
}
// Colors the buttons
public void newGame() {
button[0][0].setBackground(lightRedColor);
button[0][1].setBackground(lightRedColor);
button[0][2].setBackground(lightRedColor);
button[0][3].setBackground(darkRedColor);
button[0][4].setBackground(lightRedColor);
button[0][5].setBackground(lightRedColor);
button[0][6].setBackground(lightRedColor);
button[0][7].setBackground(lightRedColor);
button[1][3].setBackground(darkRedColor);
button[7][0].setBackground(lightBlueColor);
button[7][1].setBackground(lightBlueColor);
button[7][2].setBackground(lightBlueColor);
button[7][3].setBackground(lightBlueColor);
button[7][4].setBackground(darkBlueColor);
button[7][5].setBackground(lightBlueColor);
button[7][6].setBackground(lightBlueColor);
button[7][7].setBackground(lightBlueColor);
button[6][4].setBackground(darkBlueColor);
}
// The ActionListener is not yet used
public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();
}
public static void main(String[] args) {
String title = "City - A Two-Player Strategic Game";
GameBoard gameBoard = new GameBoard(title); // Creating the instance of gameBoard
}
}
And here is a screenshot of the bad GUI that generated:
Bad GUI
Thanks for any help, and good luck everyone with a similar problem!
Is this what you are looking for? I am not very sure what´s the problem.
This adds the buttons to a new JPanel and adds this panel to the frame.
JPanel panel = new JPanel(new GridLayout(8, 8));
panel.setSize(650,650);
getContentPane().add(panel, BorderLayout.CENTER);
// Creates the buttons in the array
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
button[i][j] = new JButton();
panel.add(button[i][j]);
button[i][j].setBackground(defaultColor);
}
}
// Build the window
this.setTitle(title); // Setting the title of board
getContentPane().setLayout(new BorderLayout());
this.setSize(650, 650); // Size of the chess board
this.setVisible(true); // Sets the board visible
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // If you close the window, the program will terminate
this.setResizable(false); //The window is not resizable anymore ;)
I'm trying to create a Sudoku game and I am having trouble creating the bold lines to break it into 3 x 3 blocks. My recent attempt was to impose an image on top of the table using JLabel. The problem is the label completely covers the JTable. I goofed around with setting the opacity of the label and the table with no luck. Here are some images to show what I'm aiming for:
The current look:
The goal:
If you could advise me as to a method I can use to create these lines, it would be greatly appreciated. No direct answers needed, just a point in the right direction.
Check out Table Row Rendering.
It shows how to provide a custom Border for each cell in a row.
So you would need to modify the code to provide multiple different Borders depending on the cell being rendered.
For any board game I'd tend to use buttons in a grid layout (or a group of grid layouts) like in this mine sweeper game or this chess board.
For the borders in this GUI though, I'd use a 3 x 3 group of nine grid layouts, each of which has a LineBorder. By default the border would go around all four sides of the panel it is displayed in, but where they meet the border would be double width, thereby coming close to recreating the second image.
E.G.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
public class Soduko {
private JComponent ui = null;
Soduko() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridLayout(3,3));
ui.setBorder(new EmptyBorder(4,4,4,4));
ArrayList<Integer> values = new ArrayList<>();
for (int ii=0; ii<34; ii++) {
values.add(0);
}
Random r = new Random();
for (int ii=34; ii<81; ii++) {
values.add(r.nextInt(9)+1);
}
Collections.shuffle(values);
int count=0;
for (int ii=0; ii<9; ii++) {
JPanel p = new JPanel(new GridLayout(3, 3));
p.setBorder(new LineBorder(Color.BLACK, 2));
ui.add(p);
for (int jj=0; jj<9; jj++) {
int v = values.get(count++).intValue();
String s = v>0 ? "" + v : "";
p.add(new JButton(s));
}
}
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Soduko o = new Soduko();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
So, what I want to happen is for every box to be white but when the user clicks on one of the boxes in the grid, it will change to a randomly generated color. I know how to write the code for the randomly generated color, but I'm not sure how to make it so that the program chooses the correct panel to change its color. Here is what i have so far:
Client
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class Prog3
{
public static void main(String[] args)
{
int rows=8;
int cols=8;
JFrame theGUI = new JFrame();
theGUI.setTitle("GUI Example");
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = theGUI.getContentPane();
pane.setLayout(new GridLayout(rows, cols,5,5));
for (int i = 1; i < rows * cols; i++)
{
Color backColor = Color.white;
Prog3_Server panel = new Prog3_Server(backColor,50,50);
pane.add(panel);
}
theGUI.pack();
theGUI.setVisible(true);
}
}
Server
import javax.swing.*;
import java.awt.*;
public class Prog3_Server extends JPanel
{
public static void main(String[] args)
{
JFrame theGUI = new JFrame();
theGUI.setTitle("GUI Example");
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Prog3_Server panel = new Prog3_Server(Color.white, 200, 200);
Container pane = theGUI.getContentPane();
pane.add(panel);
theGUI.pack();
theGUI.setVisible(true);
}
// Client provides color and preferred width and height
public Prog3_Server(Color backColor, int width, int height){
setBackground(backColor);
setPreferredSize(new Dimension(width, height));
}
// Client provides color
// Preferred width and height are 0, 0 by default
public Prog3_Server(Color backColor){
setBackground(backColor);
}
}
Any ideas on how i would use mouse events to make sure the right panel is changed from white to a random color?
You need a MouseListener/MouseAdapter
MouseListener detectClick = new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
me.getSource().setBackground(createRandomBackgroundColor());
}
}
If you add this MouseListener to all of your sub-panels, you should get the result you want
You should add the MouseListener where you're creating and adding the subpanels to the parent panel, here:
//create MouseListener here
for (int i = 1; i < rows * cols; i++)
{
Color backColor = Color.white;
Prog3_Server panel = new Prog3_Server(backColor,50,50);
//add mouse listener to the panel you've created here
pane.add(panel);
}