我有一个JButton的JDialog(截图中的右边框)。当我单击JButton时,我想更改另一个JFrame中的JPanel大小(截图中的左边框)。通过JButton更改JPanel大小
我的问题是,目前我的应用程序不会将JPanel的大小更改为新大小(20,20),当我单击按钮“单击我”时。当我点击按钮时,我的测试文本“Hello world”出现在控制台中。
实施例的屏幕截图:如果没有显示截图
备选链路:http://www.dachaufsetzer.net/files/images/other/java-question-1.jpg
这是我的代码:
Dialog.java(所述的JDialog)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Dialog extends JDialog implements ActionListener{
public Dialog(){
JDialog d = new JDialog();
d.setSize(300, 300);
JButton b = new JButton("click me");
b.addActionListener(new Generator());
d.add(b);
d.setVisible(true);
}
}
Gener ator.java(在Frame.java使用的JPanel)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Generator extends JPanel implements ActionListener{
int width;
int height;
public Generator(){
}
public Generator(int w, int h){
this.width = w;
this.height = h;
super.setBackground(Color.red);
super.setPreferredSize(new Dimension(this.width, this.height));
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(0, 0, 50, 50);
}
@Override
public void actionPerformed(ActionEvent e) {
super.setPreferredSize(new Dimension(20, 20));
System.out.println("Hello world");
}
}
Frame.java(JFrame中其使用Generator.java)
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Frame extends JFrame {
public Frame(){
JFrame f = new JFrame();
f.setSize(400, 400);
Generator g = new Generator(2000, 2000);
JScrollPane scrollPane = new JScrollPane(g);
scrollPane.setPreferredSize(new Dimension(300,300));
f.add(scrollPane);
f.setVisible(true);
}
}
主.java(主类)
public class Main {
public static void main(String[] args) {
Frame window = new Frame();
Dialog d = new Dialog();
}
}
感谢您的支持。
非常感谢您为Flood2d提供的巨大帮助。现在很清楚! – spiceflo