所以我试图将JButton
直接放在我的JLabel
下面而不是旁边,这是默认位置。但我似乎无法弄清楚如何重新定位事物。我已经尝试了setLocation()
方法而且没有做任何事情。这是我的代码:
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;
public class TestClass
{
public int timesPressed;
public static void main (String[] args)
{
new TestClass();
}
public TestClass()
{
JPanel jpanel = new JPanel();
JLabel jlabel = new JLabel ("You've clicked the button " + timesPressed + " times.");
JButton jbutton = new JButton ("Button");
jbutton.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent event)
{
timesPressed++;
jlabel.setText ("You've clicked the button " + timesPressed + " times.");
}
});
jpanel.add (jlabel);
jpanel.add (jbutton);
JFrame jframe = new JFrame ("Test Frame");
jframe.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
jframe.setSize (400, 100);
jframe.setResizable (false);
jframe.add (jpanel);
jframe.setVisible (true);
}
}
我错过了什么吗?感谢。
答案 0 :(得分:0)
您没有使用布局管理器,而是使用默认布局管理器(FlowLayout),这仅在极少数情况下有用。 Here是Oracle的布局管理员指南。
简而言之,布局管理器确定组件的位置(JButton,JLabel等)。 FlowLayout只是将它们放在一起,直到空间不足为止。通常,您从不使用setLocation()而是添加(组件),并让布局管理器处理其位置。
答案 1 :(得分:0)
答案 2 :(得分:0)
试试这个:
import java.awt.GridLayout;
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;
public class TestClass
{
public int timesPressed;
JLabel jlabel;
public static void main (String[] args)
{
new TestClass();
}
public TestClass()
{
JPanel jpanel = new JPanel();
jlabel = new JLabel ("You've clicked the button " + timesPressed + " times.");
JButton jbutton = new JButton ("Button");
jbutton.addActionListener (new ActionListener()
{
public void actionPerformed (ActionEvent event)
{
timesPressed++;
jlabel.setText ("You've clicked the button " + timesPressed + " times.");
}
});
JFrame jframe = new JFrame ("Test Frame");
jbutton.setSize(10,10);
jpanel.setLayout(new GridLayout(0, 1));
jpanel.add (jlabel);
jpanel.add (jbutton);
jframe.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
jframe.setSize (400, 100);
jframe.setResizable (false);
jframe.add (jpanel);
jframe.setVisible (true);
}
}