我的问题是我的JTextField -setColumns(int)
“field1.setColumns(5);”
......不起作用。我猜它是一个布局管理器问题。但是,我正在练习练习册。我所知道的唯一布局是flowLayout,borderLayout和gridlayout。
简而言之,只要“field2”触发ActionEvent(通过按回车键),“field1”应该改变大小。
我在“actionPerformed”中放置了一个“System.out.println(”ActionEvent detect“)来证明一个actionevent正在被触发,所以这不是问题。我甚至打印过”field1.getColumn “它显示了5的正确更改值,但是......它不仅不会在运行时明显改变大小。
我希望有人可以解释这个问题,而不是解决问题。解决这个问题不会帮助我学习,这是解决这些书籍练习的全部目的。
重要的是,我正在编写netbeans。在此先感谢您的帮助。
public class Exercise13_11 extends JFrame implements ActionListener
{
private JTextField textField1, textField2;
private JLabel label1, label2;
private JRadioButton rButton1, rButton2, rButton3;
public static void main(String[] args)
{
JFrame frame = new Exercise13_11();
frame.setTitle("Exercise 13.11");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450, 200);
frame.setVisible(true);
}
public Exercise13_11()
{
// North Panel aligned and filled.
JPanel northPanel = new JPanel();
northPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
northPanel.add(label1 = new JLabel("Text Field"));
northPanel.add(textField1 = new JTextField(20));
northPanel.setToolTipText("Demonstrate JTextField");
getContentPane().add(northPanel, BorderLayout.CENTER);
// South panel now being filled...
JPanel southPanel = new JPanel();
southPanel.setLayout(new FlowLayout());
JPanel alignmentPanel = new JPanel();
alignmentPanel.setBorder(
new javax.swing.border.TitledBorder("Horizontal Alignment"));
alignmentPanel.add(rButton1 = new JRadioButton("Left"));
alignmentPanel.add(rButton2 = new JRadioButton("Center"));
alignmentPanel.add(rButton3 = new JRadioButton("Right"));
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(rButton1);
buttonGroup.add(rButton2);
buttonGroup.add(rButton3);
JPanel columnPanel = new JPanel();
columnPanel.setBorder(new javax.swing.border.EtchedBorder());
columnPanel.setLayout(new FlowLayout());
columnPanel.add(label2 = new JLabel("Column Size"));
columnPanel.add(textField2 = new JTextField(10));
southPanel.add(alignmentPanel);
southPanel.add(columnPanel);
getContentPane().add(southPanel, BorderLayout.SOUTH);
textField1.addActionListener(this);
rButton1.addActionListener(this);
rButton2.addActionListener(this);
rButton3.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == textField1)
{
textField1.setColumns(5);
}
else if (e.getSource() == rButton1)
textField1.setHorizontalAlignment(textField1.LEFT);
else if (e.getSource() == rButton2)
textField1.setHorizontalAlignment(textField1.CENTER);
else if (e.getSource() == rButton3)
textField1.setHorizontalAlignment(textField1.RIGHT);
}
}
答案 0 :(得分:5)
它正常工作,您只需要强制容器再次布局其组件。这可以通过调用revalidate
然后发出repaint
请求(删除任何可视化工件)来实现。
答案 1 :(得分:-1)
.setColumns()
方法(与JFormattedTextField
组件一起使用)无法正常工作,原因是将TitledBorder
放在其中的容器使用了JFormattedTextFields
:>
<container.setBorder(javax.swing.BorderFactory.createTitledBorder("central"));>