Setting a 1 or 2-character text on a JButton 32x32 - java

I want to set the text on a JButton that is size 32x32 but it only shows "...". yeah I know you could see the text if you make the button bigger, but how do you make the text be shown on a 32x32 jbutton? The text is only 1 or 2 digits(characters), it is actually a counter. Thanks

The insets are probably crowding out the text...
try
button.setMargin(new Insets(1, 1, 1, 1));
edit: Also, use a smaller font.
edit2: you can also control the insets for all buttons:
UIManager.put("Button.margin", new Insets(1, 1, 1, 1));

I don't think you can, this is managed directly by the look'n'feel' that is used by Java. You could try by changing it to another one to see if there is one with different insets. You could try changing them by setting smaller insects programatically.
A more complex way would be to subclass the JButton class and provide a custom drawing implementation but I think you will lose all the other cool effect.

As per my idea , its quite simple to making GUI application easier.I am writing some code below it may help you .
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frm=new JFrame("Manoj Button Test");
frm.setVisible(true);
frm.setSize(500,500);
Container cnt=frm.getContentPane();
//You can add any text to the JButton
JButton btn=new JButton("Hello Button");
cnt.add(btn);
//2nd type of example
JButton btn2=new JButton();
int number_btntext=4;
btn2.setText(String.valueOf(number_btntext));
cnt.add(btn2);
}
In the above code I have set text to GUI JButton.

Related

How can i refresh a JDialog Image Correctly?

i am coding a program using SWing in java, but this is my problem, when i press a button, I want that every time I press a button, I update a new image in the same position as the previous one, I try to do it in the action listener of the code, but the image is not updated and the one that was At the beginning, can someone help me in this? Thank you very much.
public MainWindow() {
initComponents();
setIconImage(Icono);
this.setLocationRelativeTo(null);
this.setResizable(false);
Imagen fondo=new Imagen();
this.add(fondo, BorderLayout.CENTER);
this.pack();
PracticeMode = new javax.swing.JDialog();
}
private void StartPracticeActionPerformed(java.awt.event.ActionEvent evt) {
ButtonsSelected(1);
StartGame Practice=new StartGame(OpcComboBox, numUnity, numTrys,
opcNotas, false);
PracticeBF.dispose();
PracticeMode.setIconImage(Icono);
PracticeMode.setBounds(460, 600, 460, 538);
PracticeMode.setVisible(true);
CirculodeQuintasBW BW=new CirculodeQuintasBW();
PracticeMode.add(BW, BorderLayout.CENTER);
PracticeMode.pack();
PracticeMode.setLocationRelativeTo(null);
PracticeMode.setResizable(false);
}
This is the Image that i want to refresh, it supossed to be another Image before of that, but each time i tried to refresh it doesnt work...
PracticeMode it supossed to be a JDialog, anybody can help me?.
private void D2ActionPerformed(java.awt.event.ActionEvent evt) {
CirculodeQuintasD D=new CirculodeQuintasD();
PracticeMode.add(D, BorderLayout.CENTER);
PracticeMode.validate();
PracticeMode.repaint();
PracticeMode.pack();
}
First of all variable names and method names should NOT start with an upper case character. Learn by example from reading your text book or tutorial and then follow the Java conventions and don't make up your own!
when i press a button, I want that every time I press a button, I update a new image in the same position as the previous one,
Add an JLabel containing an ImageIcon to your panel.
When you want to change the image you just use:
label.setIcon( new ImageIcon(...) );
For example read the section from the Swing tutorial on How to Use Combo Boxes. It does exactly what your want. It uses an ActionListener to change the image of a label. The only different is that the ActionEvent is generated by clicking on an item in the combobox instead of clicking on a button.

How to align text position for two different components?

I am trying to align the position of text within a JTextArea and a JButton, but with everything I tried, either nothing happens, or the alignment is still slightly off.
Here is what is looks like:
(You can see with the highlighted option that the JButton (center) is slightly lower than the two JTextAreas on either side.)
Here is some code:
categoryFile[i][j] = tempButton;
categoryFile[i][j].setBackground(Color.white);
categoryFile[i][j].setForeground(Color.black);
categoryFile[i][j].setOpaque(true);
categoryFile[i][j].setFocusable(false);
categoryFile[i][j].setBorderPainted(false);;
categoryFile[i][j].setVerticalAlignment(SwingConstants.TOP);
categoryFile[i][j].setPreferredSize(new Dimension(500,10));
categoryFile[i][j].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
openPDFWithOptions(filePath,fileName);
}
});
JPanel listRow = new JPanel();
listRow.setBackground(Color.white);
listRow.setLayout(new BorderLayout());
listRow.setPreferredSize(new Dimension(800, 40));
JTextArea category = new JTextArea(fileElements[0]);
category.setEditable(false);
JTextArea parent = new JTextArea(fileElements[1]);
parent.setEditable(false);
listRow.add(parent,BorderLayout.WEST);
listRow.add(categoryFile[i][j],BorderLayout.CENTER);
listRow.add(category,BorderLayout.EAST);
categoryLists[i].add(listRow,c);
Right now I am using categoryFile[i][j].setVerticalAlignment(SwingConstants.TOP) to change the position of the JButton, which ALMOST works. I've also tried changing the vertical alignment of the JTextAreas, but nothing changed.
How can I align the text within these components?
Quickest way to fix this would probably be to just add some padding on the 1st and third columns to set all the text to the same height. See Jpanel Padding

Why does my JButton appear the full size of the JFrame?

I am a newbie, I have a question. I am trying to use Eclipse to write a Java windows application, in which I will have a main window, which will contain several things, like a dashboard sort of thing, and it will have buttons, for example to add a record to a database, and this button when pressed, will open a new relevant window on top.
I tried to start, I wrote this code in Java, and for some reason, the button is in the size of the frame...full screen ! How do I fix it ?
Can you suggest me better ideas for a design than what I specified ?
Thank you
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame jfrm = new JFrame("Frame1");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
jfrm.setSize(screenSize.width, screenSize.height);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel("Hello");
jfrm.add(jlab);
JButton button = new JButton("Button");
button.setSize(new Dimension(50, 50));
button.setLocation(500, 350);
jfrm.getContentPane().add(button);
jfrm.setVisible(true);
}
Add a layout to the JFrame first. For example FlowLayout:
jfrm.setLayout(new FlowLayout());
"I tried to start, I wrote this code in Java, and for some reason, the button is in the size of the frame...full screen ! How do I fix it ?"
The reason the button stretches is because JFrame has a default BorderLayout that does not respect the preferred sizes of child components.
The solution is to set the Layout Manager to layout that does respect preferred sizes. The image blow from this example shows the most common Layout Managers and show visually which one respect the preferred size of child components.
Also, the BorderLayout is also the reason your JLabel does not show. By default, every component that is added to a BorderLayout without a position specified e.g. BorderLayout.SOUTH, will automatically be placed in the BorderLayout.CENTER position. Each position may only have one component. So when you add the JLabel it goes to the CENTER, but when you add the JButton, it also goes the CENTER, kicking out the JLabel.
If you've never encountered Layout Managers, this is probably all confusing to you. You should take the time to go over How to Layout Components Within a Container
You need to use some form of layoutmanager, you can use this information: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
You must use Layout manager.
Use this code..
public static void main(String[] args)
{
JFrame jfrm = new JFrame("Frame1");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
jfrm.setSize(screenSize.width, screenSize.height);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel jlab = new JLabel("Hello");
jfrm.add(jlab);
JButton button = new JButton("Button");
button.setSize(new Dimension(50, 50));
button.setLocation(500, 350);
jfrm.add(button);
jfrm.setVisible(true);
jfrm.setLayout(new FlowLayout());
jfrm.pack();
you forgot to add pack(). so use this code to get Jlabel and JButtion side by side.
Thanks...

JLabel text Y paint coordinate

The default JLabel draws its text at the middle of its bounds. For example, if height of the label is 20, font height is 14, the Y coordinate would be (20 - 14)/2 = 3. Like this:
What should I do if want to align the text to the TOP of the JLabel bounds? Like this:
UPD:
public class LabelTest extends JFrame {
public LabelTest() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.X_AXIS));
contentPanel.add(Box.createHorizontalStrut(10));
final JLabel label1 = new JLabel("JLabel");
label1.setVerticalAlignment(SwingConstants.TOP); // by the answer of Kevin Workman, doesn't help
label1.setBorder(BorderFactory.createLineBorder(Color.RED));
label1.setFont(new Font("Arial", Font.PLAIN, 14));
contentPanel.add(label1);
setContentPane(contentPanel);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new LabelTest();
}
});
}
}
You should be packing the frame. If you so this, there should be no unused space in the label. If you want empty space, use an empty border
label.setBorder(new EmptyBorder(0, 0, 5, 0));
top, left, bottom, right
Also, don't set sizes, Use Layout Mangers and let them do the sizing for you. Setting sizes will give you. Setting sizes will give you a rigid look that may look and perform differently on different platforms. Layout Managers will allow your GUI to be more fluid and adaptable to different environments.
See Laying out Components Within a Container for more information on working with layouts
Also see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
As always, the API is your best friend: http://docs.oracle.com/javase/7/docs/api/javax/swing/JLabel.html#setVerticalAlignment(int)
Edit- Based on your updated SSCCE, the problem is that your BoxLayout is shrinking the JLabel as small as it will go, so the vertical text position doesn't really matter. Try using a BorderLayout to check that.
The problem is that the insets of the JLabel are adding a small space to the top and bottom of the JLabel, so your text looks centered even though it's at the top. Here's a fix for the insets problem: How to change gap in swing label

Overriding the paint method in JTextField to draw text

I am wishing to draw a number onto a JTextField by overwriting the paint method. So that when the user edits the text field the number doesn't disappear. However, at the moment, the number isn't appearing at all, I have tried:
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(number != 0){
g.setColor(Color.RED);
g.drawString(String.valueOf(number),0,0);
}
}
Any ideas, is this even possible?
Try to play with Y position in the g.drawString(String.valueOf(number),0,0); call. E.g. use getHeight()/2
..when the user edits the text field the number doesn't disappear.
As pointed out by #mKorbel, there is no need to override a JTextField in order to get red numbers, simply configure it using the public methods. OTOH..
g.drawString(String.valueOf(number),0,0);
If this is really all about numbers, perhaps the best approach is to use a JSpinner with a SpinnerNumberModel, and set a custom SpinnerUI.
Why don't you just add a small JLabel to the front of the JTextField? The JLabel could contain the number, and because it isn't editable it will always be there no matter what the user changes in the JTextField. You could also format the JLabel to make it red by calling setForeground(Color.RED);. This might be a much simpler solution?
For example, instead of doing this...
JPanel panel = new JPanel(new BorderLayout());
JTextField textfield = new JTextField("Hello");
panel.add(textfield,BorderLayout.CENTER);
You might do something like this...
JPanel panel = new JPanel(new BorderLayout());
JTextField textfield = new JTextField("Hello");
panel.add(textfield,BorderLayout.CENTER);
JLabel label = new JLabel("1.");
label.setForeground(Color.RED);
panel.add(label,BorderLayout.WEST);
Which adds a red JLabel to the left of the JTextField, and because you're using BorderLayout for the JPanel then it automatically makes the JLabel the smallest it can possibly be.
maybe there no reason override paintComponent() for JTextField, instead of use
JTextField.setBackground()
JTextField.setForeground()
JTextField.setFont()
JTextField.setHorizontalAlignment(javax.swing.SwingConstants.LEFT)
some hacks are possible by put there Html colored or special formatted text
EDIT
maybe this question is about
filtering KeyEvents in the Document / DocumentListener
or
JFormattedTextField with Number Formatter

Categories

Resources