我有一個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