I am stuck on getting this swing UI to act the way I was hoping. I wrote this demo code to showcase what it is doing and I will now explain what I was hoping to make it do.
I have a JFrame and 3 JPanels
https://i.stack.imgur.com/B82tF.png
I want the JFrame to have an image in the background on the JFrame, like a world map, then on top of that I was trying to have: a top nav bar with buttons, then on top of the map, I want buttons that a player can click on for different areas of the map on the layer below, then I want to have a drawer that opens and closes if the user clicks on the show/hide drawer button that gives info about the action they performed by clicking the buttons.
What I have so far is three panels all aligned side by side and that is not what I want.
How can i get this UI to act like I described above?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class TestFrame extends JFrame {
static JFrame frame;
static JButton btnExit, btnShowHide;
static JPanel gridPanel, drawerPanel;
public static void main(String[] args)
{
GridLayout layout = new GridLayout(1,1,0,0);
frame = new JFrame("Main Frame");
frame.setLayout(layout);
// 1: Creating grid panel
gridPanel = new JPanel();
gridPanel.setBackground(Color.yellow);
gridPanel.setLayout(new GridLayout(5, 5, 0, 0));
gridPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY));
gridPanel.setOpaque(false);
gridPanel.setBorder(BorderFactory.createLineBorder(Color.gray));
placeButtons();
// 2: Creating button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.red);
// add buttons
btnExit = new JButton("Exit");
buttonPanel.add(btnExit);
btnExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
System.exit(0);
} catch (Exception err) {
System.out.println("doh");
}
}
});
// 3: Creating button panel
drawerPanel = new JPanel();
drawerPanel.setBackground(Color.blue);
btnShowHide = new JButton("show drawer");
buttonPanel.add(btnShowHide);
btnShowHide.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
System.out.println("show drawer");
drawerPanel.setVisible(true);
} catch (Exception err) {
System.out.println("Could not close the DB: " + err);
}
if(btnShowHide.getText().equals("show drawer")){
btnShowHide.setText("hide drawer");
} else{
btnShowHide.setText("show drawer");
drawerPanel.setVisible(false);
}
}
});
// Adding panels to frame
frame.add(gridPanel);
frame.add(buttonPanel);
frame.add(drawerPanel);
frame.setSize(500, 500);
frame.setVisible(true);
}
public static void placeButtons(){
System.out.println("place buttons");
int dbx = 0;
int dby = 0;
for(int xCnt = 0; xCnt < 5; xCnt++){
dby = 0;
for(int yCnt = 0; yCnt < 5; yCnt++) {
JButton click = new JButton("x:"+xCnt+" y:"+yCnt);
gridPanel.add(click);
dby++;
}
dbx++;
}
}
}```