我正在做一个分配,有一些问题,当我的框架打开时,当我运行我的程序,它没有打开到它的完整尺寸,700x100。为什么呢?此外,如何使框架内的内容可调整大小?
这是我的。
package hw06;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TargetLogoUI {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
JTextField TargetMessagePanel = new JTextField();
TargetMessagePanel.setBackground(new java.awt.Color(204, 204, 204));
TargetMessagePanel.setFont(new java.awt.Font("Helvetica", 1, 72)); // NOI18N
TargetMessagePanel.setText("Welcome to Target");
frame.add(TargetMessagePanel, BorderLayout.NORTH);
final TargetLogoPanel panel = new TargetLogoPanel();
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
panel.setTarget(true);
panel.repaint();
}
});
frame.add(panel);
frame.setSize(700, 100);
frame.setVisible(true);
}
}
class TargetLogoPanel extends JPanel {
private boolean isTarget;
public void paintComponent(Graphics g) {
super.paintComponent(g); // erase back
Graphics2D g2 = (Graphics2D) g;
Color c = null;
if (isTarget) {
c = Color.BLUE;
} else {
c = Color.RED;
}
g2.setColor(c);
g2.fill(new Ellipse2D.Double(250, 50, 160, 160));
g2.setColor(Color.WHITE);
g2.fill(new Ellipse2D.Double(275, 75, 110, 110));
g2.setColor(c);
g2.fill(new Ellipse2D.Double(300, 100, 60, 60));
}
public boolean isTarget() {
return isTarget;
}
public void setTarget(boolean isTarget) {
this.isTarget = isTarget;
}
}
我正在做一个作业,有一些问题,当我的帧打开时当我运行我的程序时,它没有打开到它的完整尺寸,700x100
实际上它的尺寸是700 * 100。
我建议您不要这样做,而是重写JPanel的getPreferredSize()
方法,然后在可视化JFrame之前在JFrame上调用pack()
。比如:
class TargetLogoPanel extends JPanel {
private static final int PREF_W = 700; //!!
private static final int PREF_H = 300;
private boolean isTarget;
public void paintComponent(Graphics g) {
super.paintComponent(g); // erase back
Graphics2D g2 = (Graphics2D) g;
// rendering your circles smoothly
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color c = null;
if (isTarget) {
c = Color.BLUE;
} else {
c = Color.RED;
}
g2.setColor(c);
g2.fill(new Ellipse2D.Double(250, 50, 160, 160));
g2.setColor(Color.WHITE);
g2.fill(new Ellipse2D.Double(275, 75, 110, 110));
g2.setColor(c);
g2.fill(new Ellipse2D.Double(300, 100, 60, 60));
}
@Override //!!
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public boolean isTarget() {
return isTarget;
}
public void setTarget(boolean isTarget) {
this.isTarget = isTarget;
}
}
另外,我如何使框架内的内容可调整大小?
请详细说明您的意思。