gpt4 book ai didi

java - 按按钮打开一个新窗口 按下

转载 作者:行者123 更新时间:2023-11-29 07:08:37 25 4
gpt4 key购买 nike

我试图通过按 JButton 打开一个新窗口。现在我的 Jbutton 的 actionPerformed 方法只是在按下它后关闭窗口。我希望它在旧窗口关闭时打开一个新窗口。我知道,这个问题已经被问过了,但我尝试了很多东西,似乎没有一个能完美地工作。

    import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.Random;

public class secondTab extends JFrame
{
static JTabbedPane Pane = new JTabbedPane();

static JPanel Second = new JPanel();
static JPanel second = new JPanel(); // This Panel is inside the Second Panel

static JButton guess1 = new JButton();
static String words[] = new String[9];

static Random getRandomWord = new Random();

static int rr;
static JButton Labels[] = new JButton[10];

public static void main(String args[])
{
//construct frame
new secondTab().show();
}

public secondTab()
{
// code to build the form
setTitle("Shopping Cart");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridBagLayout());

// position tabbed pane
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
Pane.setForeground(Color.YELLOW);
Pane.setBackground(Color.MAGENTA);

getContentPane().add(Pane, gridConstraints);
getContentPane().setLayout(new GridBagLayout());


// Tabs Starts From Here

Second.setLayout(new GridBagLayout());

words[1] = "JAVA";
words[2] = "FLOAT";
words[3] = "VOID";
words[4] = "MAIN";
words[5] = "STATIC";
words[6] = "FINAL";
words[7] = "PRIVATE";
words[8] = "CHAR";
words[9] = "IF";


rr = getRandomWord.nextInt(10);

for(int i = 1; i <=words[rr].length(); i++)
{
Labels[i] = new JButton();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
second.add(Labels[i]);
}


gridConstraints.gridx= 0;
gridConstraints.gridx= 0;
Second.add(second, gridConstraints);


guess1.setText("New Word");
gridConstraints.gridx = 0;
gridConstraints.gridy = 2;
Second.add(guess1, gridConstraints);

这是我的按钮的 Action Performed 方法

            // Action Performed method for the JButton guess1
guess1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
}
});



Pane.addTab("Game ", Second);

pack();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 *
(screenSize.height - getHeight())), getWidth(), getHeight());
}

}

最佳答案

只需在 dispose() 之后添加新的面板语句。例如:添加

guess1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
new JFrame("New Window").show();
}
});

还有一点 - 您已经创建了包含 9 个元素的数组,并且您正试图在 10 个索引处插入,这会引发 ArrayIndexOutOfBound 异常。

关于java - 按按钮打开一个新窗口 按下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16683548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com