我正在做作业并有一些问题,当我的框架打开时,当我运行我的程序时,它不会打开它的全尺寸,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;
}
}
答案 0 :(得分:2)
我正在做作业并有一些问题,当我的框架打开时,当我运行程序时,它不会打开它的全尺寸,700x100。
实际上它的尺寸为700 x 100。
我建议您不要这样做,而是覆盖JPanel的getPreferredSize()
方法,然后在可视化之前在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;
}
}
另外,如何使框架内的内容可调整大小?
请详细说明你的意思。