单击按钮时如何显示文本
现在在我的APCS课堂上,我们正在学习如何对GUI进行编程.我们已经学习了制作按钮并将背景颜色更改为绿色,红色,蓝色等的方法.但是,本周剩下的时间我的老师将不在这里,我只是很好奇如何使文本出现在框架内单击一个按钮,使文本在我再次单击该按钮时消失.如果有帮助,则下面是代码.我想将背景颜色更改为绿色,以及在屏幕上显示绿色".非常感谢您的帮助!
In my APCS class right now, we are learning how to program GUIs. We have learned about making a button and changing the background color to green, red, blue etc. However, my teacher will not be here for the rest of this week and I was just curious about how I can make text appear inside of the frame with the click of a button, and make the text disappear when I click the button again. If it helps, below is the code. I want to change the background color to green as well as displaying "green" on the screen. Thank you so much for your help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class datBoi extends JFrame implements ActionListener{
JButton datBoi;
public datBoi(String title)
{
super(title);
datBoi = new JButton("dat boi");
datBoi.setActionCommand("dat boi");
datBoi.addActionListener(this);
setLayout(new FlowLayout());
add(datBoi);
}
public void actionPerformed( ActionEvent evt)
{
// check which command has been sent
if ( evt.getActionCommand().equals( "dat boi" ) )
{ getContentPane().setBackground( Color.green );
}
repaint();
}
public static void main ( String[] args )
{
datBoi demo = new datBoi( "Get ready to be memed" ) ;
demo.setSize( 420, 420 );
demo.setVisible( true );
}
}
添加JLabel将它们添加到JPanel中以供将来使用. 使用我提供的用于显示您的文本和绿色文本的功能; 您可以通过在"区域中进行更改来更改文本.
Add JLabel add them into the JPanel for futher use. Use the function that I provided for displaying Your text and Green Text; You can change the text by changing it in the "" area.
代码如下:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class datBoi extends JFrame implements ActionListener{
JButton datBoi;
JLabel jf;
JLabel label;
public datBoi(String title)
{
super(title);
datBoi = new JButton("dat boi");
datBoi.setActionCommand("dat boi");
datBoi.addActionListener(this);
jf = new JLabel();
JPanel panel = new JPanel();
panel.add(jf);
getContentPane().add(panel);
setLayout(new FlowLayout());
add(datBoi);
JPanel panel2 = new JPanel();
getContentPane().add(panel2);
label = new JLabel();
panel.add(label);
}
public void actionPerformed( ActionEvent evt)
{
// check which command has been sent
if ( evt.getActionCommand().equals( "dat boi" ) )
{ getContentPane().setBackground( Color.green );
if(jf.getText().equals("")){
jf.setText("put your text here");
}else{
jf.setText("");
}
label.setText("GREEN");
}
repaint();
}
public static void main ( String[] args )
{
datBoi demo = new datBoi( "Get ready to be memed" ) ;
demo.setSize( 420, 420 );
demo.setVisible( true );
}
}