我有两个类,一个是MyDrawPanel
,第二个是TwoButtons
,我使用Eclipse来运行我的代码。
但我不知道我的代码有什么问题? Eclipse没有回复@@?
头等:
import java.awt.*;
import javax.swing.*;
class MyDrawPanel extends JPanel {
public MyDrawPanel() {
this.setForeground(Color.white);
}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
super.paintComponent(g2d);
g.fillRect(0,0,this.getWidth(),this.getHeight());
GradientPaint gradient = new GradientPaint(70,70,Color.LIGHT_GRAY,200,200,Color.CYAN);
g2d.setPaint(gradient);
g.fillOval(70, 70, 100, 100);
}
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(300, 300);
jFrame.add(new MyDrawPanel());
jFrame.setVisible(true);
}
}
第二课:
public class TwoButtons {
JFrame frame;
JLabel label;
public static void main(String[] args) {
TwoButtons gui = new TwoButtons();
gui.go();
}
private void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
JButton labelButton = new JButton("change Label");
labelButton.addActionListener(new LabelListener());
JButton colorButton = new JButton("change Circle");
colorButton.addActionListener(new ColorListener());
label = new JLabel("I'm a label");
MyDrawPanel draw = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH,colorButton);
frame.getContentPane().add(BorderLayout.CENTER,draw);
frame.getContentPane().add(BorderLayout.WEST,label);
frame.getContentPane().add(BorderLayout.EAST,labelButton);
}
class LabelListener implements ActionListener{
public void actionPerformed(ActionEvent event){
label.setText("Ouch!");
}
}
class ColorListener implements ActionListener{
public void actionPerformed(ActionEvent event){
frame.repaint();
}
}
}
有谁能告诉我如何更改我的代码?
答案 0 :(得分:1)
在go方法的底部添加这两行 -
frame.setVisible(true);
frame.setSize(500,500);