Как сделать окно динамически изменяемым по размеру и заставить графический интерфейс реагировать на окно изменяемого разJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Как сделать окно динамически изменяемым по размеру и заставить графический интерфейс реагировать на окно изменяемого раз

Сообщение Anonymous »

Я хочу, чтобы размер окна изменялся динамически, а графический интерфейс реагировал на изменение размера окна без изменения исходного выравнивания и функций каждой кнопки и без изменения исходной логики графического интерфейса. это весь код, я надеюсь, что смогу получить ответы здесь

Код: Выделить всё

public HardMode_GUI(ElementalGame game) {
this.game = game;
this.elementManager = new ElementManager();

setTitle("ELEMENTALS: Hard Mode");
ImageIcon icon = new ImageIcon(getClass().getResource("icon.png"));
setIconImage(icon.getImage());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 500);
setLocationRelativeTo(null);
setResizable(false);

JPanel mainPanel = new JPanel() {
ImageIcon backgroundImage = new ImageIcon(getClass().getResource("hardbg.png"));

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
};
mainPanel.setLayout(null);
add(mainPanel);

roundLabel = new JLabel("Round 1", SwingConstants.CENTER);
roundLabel.setFont(new Font("Serif", Font.BOLD, 28));
roundLabel.setForeground(Color.YELLOW);
roundLabel.setBounds(200, 10, 400, 40);
mainPanel.add(roundLabel);

timerLabel = new JLabel("Time left: 10 seconds", SwingConstants.CENTER);
timerLabel.setFont(new Font("Serif", Font.BOLD, 18));
timerLabel.setForeground(new Color(255, 215, 0));
timerLabel.setBounds(200, 50, 400, 40);
timerLabel.setVisible(false);
mainPanel.add(timerLabel);

resultLabel = new JLabel("", SwingConstants.CENTER);
resultLabel.setFont(new Font("Serif", Font.BOLD, 18));
resultLabel.setForeground(Color.WHITE);
resultLabel.setBounds(200, 100, 400, 80);
mainPanel.add(resultLabel);

balanceLabel = new JLabel("Your Balance: " + game.getPlayer().getMoney(), SwingConstants.LEFT);
balanceLabel.setFont(new Font("Serif", Font.BOLD, 18));
balanceLabel.setForeground(Color.WHITE);
balanceLabel.setBounds(10, 10, 200, 40);
mainPanel.add(balanceLabel);

systemBalanceLabel = new JLabel("System Balance: " + game.getSystem().getMoney(), SwingConstants.LEFT);
systemBalanceLabel.setFont(new Font("Serif", Font.BOLD, 18));
systemBalanceLabel.setForeground(Color.WHITE);
systemBalanceLabel.setBounds(10, 400, 200, 40);
mainPanel.add(systemBalanceLabel);
setupElementButtons(mainPanel);

nextRoundButton = new JButton("Next Round");
nextRoundButton.setFont(new Font("Serif", Font.BOLD, 20));
nextRoundButton.setBounds((getWidth() - 200) / 2, 390, 200, 40);
nextRoundButton.setVisible(false);
nextRoundButton.addActionListener(e -> startNextRound());
mainPanel.add(nextRoundButton);
startNextRound();
setVisible(true);
}

private void showPowerUpSelection() {
JDialog powerUpDialog = new JDialog(this, "Power-Ups", true);
powerUpDialog.setSize(800, 500);
powerUpDialog.setLocationRelativeTo(this);
powerUpDialog.setLayout(new BorderLayout());

JPanel backgroundPanel = new JPanel() {
ImageIcon backgroundImage = new ImageIcon(getClass().getResource("bg7.png"));

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
};
backgroundPanel.setLayout(new BorderLayout());
powerUpDialog.add(backgroundPanel);

JLabel choosePowerUpLabel = new JLabel("Choose Your Power-Up");
choosePowerUpLabel.setFont(new Font("Serif", Font.BOLD, 30));
choosePowerUpLabel.setForeground(Color.WHITE);
choosePowerUpLabel.setHorizontalAlignment(SwingConstants.CENTER);
choosePowerUpLabel.setBounds(0, 50, 800, 40);
backgroundPanel.add(choosePowerUpLabel);

JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(false);
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 30, 100));
String[] powerUps = {"Double Bet", "Steal Money", "Block Element"};
String[] powerUpIcons = {"doublebet.png", "stealmoney.png", "blockelement.png"};
int buttonWidth = 200, buttonHeight = 300;

for (int i = 0; i < powerUps.length;  i++) {
int index = i;

ImageIcon icon = new ImageIcon(getClass().getResource(powerUpIcons[i]));
Image scaledImage = icon.getImage().getScaledInstance(buttonWidth, buttonHeight, Image.SCALE_SMOOTH);
ImageIcon resizedIcon = new ImageIcon(scaledImage);

JButton button = new JButton(resizedIcon);
button.setPreferredSize(new Dimension(buttonWidth, buttonHeight));
button.setToolTipText(powerUps[i]);
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
button.setFocusPainted(false);

button.addActionListener(e -> {
selectedPowerUp = index;
powerUpDialog.dispose();
applyPowerUp(index);
});

buttonPanel.add(button);
}

backgroundPanel.add(buttonPanel, BorderLayout.CENTER);

powerUpDialog.setVisible(true);

Код: Выделить всё

private void showBlockElementSelection() {
JDialog blockElementDialog = new JDialog(this, "Block Element", true);
blockElementDialog.setSize(800, 500);
blockElementDialog.setLocationRelativeTo(this);
blockElementDialog.setLayout(new BorderLayout());

JLabel titleLabel = new JLabel("Select an Element to Block");
titleLabel.setFont(new Font("Serif", Font.BOLD, 28));
titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
titleLabel.setForeground(Color.WHITE);
titleLabel.setBorder(BorderFactory.createEmptyBorder(20, 0, 10, 0));

JPanel backgroundPanel = new JPanel() {
ImageIcon backgroundImage = new ImageIcon(getClass().getResource("bg7.png"));

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
};
backgroundPanel.setLayout(new BorderLayout());
backgroundPanel.add(titleLabel, BorderLayout.NORTH);

JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 20));
buttonsPanel.setOpaque(false);

String[] hybridElements = elementManager.getHybridElements();
String[] hybridIcons = {"steam.png", "mud.png", "dust.png", "lava.png"};

for (int i = 0; i < hybridElements.length; i++) {
String element = hybridElements[i];

ImageIcon icon = new ImageIcon(getClass().getResource(hybridIcons[i]));
Image scaledImage = icon.getImage().getScaledInstance(120, 175, Image.SCALE_SMOOTH);
ImageIcon resizedIcon = new ImageIcon(scaledImage);

JButton button = new JButton(resizedIcon);
button.setPreferredSize(new Dimension(120, 175));
button.setToolTipText(element);
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
button.setFocusPainted(false);

button.addActionListener(e -> {
JOptionPane.showMessageDialog(this, "Block Element Activated! " + element + " is now blocked.");
blockElementDialog.dispose();
});

buttonsPanel.add(button);
}

JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.setOpaque(false);
centerPanel.add(buttonsPanel, BorderLayout.CENTER);
centerPanel.setBorder(BorderFactory.createEmptyBorder(50, 0, 50, 0));

backgroundPanel.add(centerPanel, BorderLayout.CENTER);
blockElementDialog.add(backgroundPanel);
blockElementDialog.setVisible(true);

Код: Выделить всё

private void setupElementButtons(JPanel mainPanel) {
int buttonWidth = 120;
int buttonHeight = 175;
int numButtons = 4;
int spacing = 30;
int totalWidth = (buttonWidth * numButtons) + (spacing * (numButtons - 1));
int startX = (getWidth() - totalWidth) / 2;

elementButtons = new JButton[numButtons];
elementButtons[0] = createElementButton(mainPanel, "steam.png", "Fire+Water = Steam", startX, 200, buttonWidth, buttonHeight, spacing, 0);
elementButtons[1] = createElementButton(mainPanel, "mud.png", "Water+Earth = Mud", startX, 200, buttonWidth, buttonHeight, spacing, 1);
elementButtons[2] = createElementButton(mainPanel, "dust.png", "Earth+Air = Dust", startX, 200, buttonWidth, buttonHeight, spacing, 2);
elementButtons[3] = createElementButton(mainPanel, "lava.png", "Earth+Fire = Lava", startX, 200, buttonWidth, buttonHeight, spacing, 3);
}

private JButton createElementButton(JPanel mainPanel, String iconPath, String element, int startX, int y, int width, int height, int spacing, int index) {
ImageIcon icon = new ImageIcon(getClass().getResource(iconPath));
Image scaledImage = icon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);
ImageIcon resizedIcon = new ImageIcon(scaledImage);

int xPosition = startX + (index * (width + spacing));

JButton button = new JButton(resizedIcon);
button.setBounds(xPosition, y, width, height);
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
button.setFocusPainted(false);
button.setDisabledIcon(resizedIcon);
button.addActionListener(e -> handlePlayerChoice(element));
mainPanel.add(button);

return button;
}

private void showGameMechanics() {
JDialog mechanicsDialog = new JDialog(this, "GAME MECHANICS", true);
mechanicsDialog.setSize(400, 300);
mechanicsDialog.setFont(new Font("Serif", Font.BOLD, 18));
mechanicsDialog.setLocationRelativeTo(this);
mechanicsDialog.setLayout(new BorderLayout());
JTextArea mechanicsText = new JTextArea(
" ‣ Hard Mode has 4 Rounds.\n\n" +
" ‣ The balance left from the Easy and Medium Mode continues in Hard Mode.\n" +
" ‣ First, you must choose your power-up then you can proceed on placing your bet.\n\n" +
"   The power-ups are\n" +
"   1. DOUBLE BET(allows the player to double the bet and will add to the player's balance if the player wins otherwise the player's loss adds to the system's balance.)\n\n" +
"   2. STEAL MONEY(allows the player to steal balance from the system between 50 and 100 pesos.)\n\n" +
"   3. BLOCK ELEMENT (allows the player to prevent the system from selecting a specific hybrid element during the round.)\n\n" +
" ‣ After placing the bet, the power-up you chose will be activated then you can pick your card.\n\n" +
" ‣ It has a timer of 10 seconds while choosing an element (HYBRID ELEMENTS). \n" +
"If the time is up, a random element is auto-selected.\n\n" +
" ‣ The game ends when either the player(you) or the system doesn't have enough balance to continue.  \n\n"

);
mechanicsText.setFont(new Font("Serif", Font.PLAIN, 16));
mechanicsText.setEditable(false);
mechanicsText.setWrapStyleWord(true);
mechanicsText.setLineWrap(true);
mechanicsText.setBackground(Color.LIGHT_GRAY);
mechanicsText.setForeground(Color.BLACK);
mechanicsDialog.add(new JScrollPane(mechanicsText), BorderLayout.CENTER);

JButton okButton = new JButton("Ready?");
okButton.setFont(new Font("Serif", Font.BOLD, 16));
okButton.addActionListener(e -> mechanicsDialog.dispose());
mechanicsDialog.add(okButton, BorderLayout.SOUTH);
mechanicsDialog.setVisible(true);
}

private void updateBalances() {
balanceLabel.setText("Your Balance: " + game.getPlayer().getMoney());
systemBalanceLabel.setText("System Balance: " + game.getSystem().getMoney());
}
private void startNextRound() {
roundsPlayed++;
if (roundsPlayed > 4) {
JOptionPane.showMessageDialog(this, "Hard Mode Complete! Congratulations! You have finished the game.");
System.exit(0);
}

if (isFirstRound) {
showGameMechanics();
isFirstRound = false;
}

roundLabel.setText("Round " + roundsPlayed);
resultLabel.setText("");
nextRoundButton.setVisible(false);

enableElementButtons();
showPowerUpSelection();
startCountdown();
}

private void enableElementButtons() {
for (JButton button : elementButtons) {
button.setEnabled(true);
}
}

private void disableElementButtons() {
for (JButton button : elementButtons) {
button.setEnabled(false);
button.setDisabledIcon(button.getIcon());
}
}

private void startCountdown() {
timeLeft = 10;
timerLabel.setText("Time left: " + timeLeft + " seconds");
timerLabel.setVisible(true);

countdownTimer = new Timer(1000, e -> {
timeLeft--;
timerLabel.setText("Time left: " + timeLeft + " seconds");

if (timeLeft 

Подробнее здесь: [url]https://stackoverflow.com/questions/79288632/how-to-make-the-window-dynamically-resizable-and-make-the-gui-responsive-to-the[/url]
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»