如何通过动态点击键来更改JFrame的内容,在本例中我想通过我创建的两个JPanel更改内容,当我点击时我想要更改为Panel2,当我点击下来时我想要更改为Panel3,但我希望JFrames内容只能更改(我希望保持在同一个JFrame中)代码没有错误,我对如何解决这个问题感到有些困惑。
class Drawing extends JFrame implements KeyListener{
int num = 1;
public Drawing() {
Panel2 jPanel2 = new Panel2();
Panel3 jPanel3 = new Panel3();
if(num == 1){
add(jPanel2);
remove(jPanel3);
pack();
}
if(num == 2){
add(jPanel3);
remove(jPanel2);
pack();
}
// be nice to testers..
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
addKeyListener(this);
}
然后我有keypressed方法将num更改为1或2,具体取决于按下了什么键(我还实现了keyReleased和keyTyped,但我没有包含它们来添加空间)
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == e.VK_UP){
num = 1;
}
if(e.getKeyCode() == e.VK_DOWN){
num = 2;
}
}
public static void main(String args[]) {
new Drawing();
}
这是改变页面图形的两个面板
class Panel2 extends JPanel {
Panel2() {
setPreferredSize(new Dimension(500,500));
}
public void paint(Graphics g) {
g.drawString("BLAH", 20, 20);
g.drawRect(200, 200, 200, 200);
repaint();
}
}
class Panel3 extends JPanel {
Panel3() {
// set a preferred size for the custom panel.
setPreferredSize(new Dimension(500,500));
}
public void paint(Graphics g) {
g.drawString("BURP", 20, 20);
g.drawRect(200, 200, 200, 200);
repaint();
}
}
答案 0 :(得分:0)
首先,在您的用例中,不要使用keyTyped事件,因为它只是被触发
当此密钥表示的unicode字符由 键盘到系统输入
。您的UI中没有系统输入。有关详细信息,请查看此处:KeyListener, keyPressed versus keyTyped
相反,请使用 keyPressed 或 keyReleased 事件。
其次,在处理事件时需要显式调用add(jPanel2);remove(jPanel3);
。设置num = 1
没有做任何事情。
第三,您需要在jPanel2.repaint();
之后致电add(jPanel2);remove(jPanel3);
,以确保该面板描绘您想要的内容。
第四,始终调用 super.paint(g);
来正确初始化绘画画布!
所以,要把它们放在一起,你有:
public class Drawing extends JFrame implements KeyListener {
int num = 1;
Panel2 jPanel2 = new Panel2();
Panel3 jPanel3 = new Panel3();
public Drawing() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
addKeyListener(this);
setSize(300, 300);
}
@Override
public void keyTyped(KeyEvent e) {
}
private void changePanel() {
if (num == 1) {
remove(jPanel3);
add(jPanel2);
jPanel2.repaint();
pack();
}
if (num == 2) {
remove(jPanel2);
add(jPanel3);
jPanel3.repaint();
pack();
}
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == e.VK_UP) {
num = 1;
}
if (e.getKeyCode() == e.VK_DOWN) {
num = 2;
}
changePanel(); // do the actual swap of the panels
}
public static void main(String args[]) {
new Drawing();
}
}
class Panel2 extends JPanel {
Panel2() {
setPreferredSize(new Dimension(500, 500));
}
public void paint(Graphics g) {
super.paint(g); //always call!
g.drawString("BLAH", 20, 20);
g.drawRect(200, 200, 200, 200);
}
}
class Panel3 extends JPanel {
Panel3() {
setPreferredSize(new Dimension(500, 500));
}
public void paint(Graphics g) {
super.paint(g); //always call!
g.drawString("BURP", 20, 20);
g.drawOval(200, 200, 200, 200);
}
}