jf.setVisible(true)
jf.setSize(1000, 500)
这两句对调下位置,先设置大小,然后再可见。。
import java.awt.Color
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.JButton
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.SwingUtilities
public class TestWin extends JFrame implements ActionListener {
private JButton blackBtn=new JButton("Black")
private JButton whiteBtn=new JButton("White")
private JPanel pane=new JPanel()
public TestWin() {
this.blackBtn.addActionListener(this)
this.whiteBtn.addActionListener(this)
JPanel btnPane=new JPanel()
btnPane.add(this.blackBtn)
btnPane.add(this.whiteBtn)
this.add(btnPane,"North")
this.add(pane,"Center")
this.setSize(800, 600)
this.setLocationRelativeTo(null)
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
this.setVisible(true)
}
@Override
public void actionPerformed(ActionEvent e) {
Object source=e.getSource()
if(source==this.blackBtn) {
this.pane.setBackground(Color.BLACK)
}else if(source==this.whiteBtn) {
this.pane.setBackground(Color.WHITE)
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TestWin())
}
}