Add JTextField to JToolBar
-
12-06-2021 - |
문제
I'm trying to add JTextField
to JToolBar
and it works, but it is too long. I need it to take only 3 letters.
Here is the screenshot of it now...
I tried following methods,
JTextField field = new JextField(3); // thought this limits to three characters.
And I tried,
field.setColumns(3); // this didn't work either.
해결책
The default layout of a tool-bar respects the maximum size set for a text field.
import java.awt.*;
import javax.swing.*;
public class TextFieldInToolBar {
TextFieldInToolBar() {
JPanel p = new JPanel(new BorderLayout());
JToolBar tb = new JToolBar();
p.add(tb, BorderLayout.PAGE_START);
Icon disk = (Icon)UIManager.get("FileView.floppyDriveIcon");
Icon pc = (Icon)UIManager.get("FileView.computerIcon");
tb.add(new JButton(disk));
JTextField tf = new JTextField(3);
tf.setMaximumSize(tf.getPreferredSize());
tb.add(tf);
tb.addSeparator();
tb.add(new JButton(pc));
p.setPreferredSize(new Dimension(250,50));
JOptionPane.showMessageDialog(null, p);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TextFieldInToolBar();
}
});
}
}
다른 팁
JToolBar is container as JFrame, JDialog or JWindow, you can laying this container by using the proper LayoutManager
this issue should be the same by using JMenuBar as container for JComponents (alternative)
제휴하지 않습니다 StackOverflow