Overriding the paint method in JTextField to draw text - java

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

Related

Having trouble giving my JPanel functionality

*This is my first time using GUI, I seem to miss something my eye can't catch. The code looks fine to me however when i submit it to autoLab I get this error, which I cannot figure out where I went wrong.
{"correct":false,"feedback":"(class java.lang.NumberFormatException)
Error while attempting to call static method q2() on input [1]}
The problem question is q5:
Write a public static method named q5 that takes no parameters and returns a JPanel.
The panel will contain 1 JTextField with any number of columns, 1 JButton with any label,
and 1 JLabel. The panel will have functionality such that when a user enters a number into
the text field (we'll call this value x) and presses the button the label will display the
y-value of a parabola in standard form (https://www.desmos.com/calculator/zukjgk9iry)
where a=5.37, b=-6.07, and c=2.0 at the x-value from the text field
Hint: If you store y in the wrapper class Double instead of the primitive double you can
call toString on it to convert it to a string that can be used as the text for the label
Tip: After clicking the button you may have to resize your window to see the result since
the frame will not automatically resize to fit the new text
Do not create any JFrames in your problem set questions. Doing so will crash the
auto-grader since the grading server does not have a screen to display the JFrame.
Instead, only return the required JPanel in the problem set methods and test with a JFrame
in your main method, or other helper methods that are not graded
This is the code I wrote
public static JPanel q5() {
JPanel panel = new JPanel();
JTextField textField = new JTextField(5);
panel.add(textField);
JLabel label = new JLabel("hello!");
panel.add(label);
JButton button = new JButton("Click Me!");
panel.add(button);
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int x = Integer.parseInt(textField.getText());
double a=5.37*Math.pow(x, 2);
double b=-6.07*x;
double c=2.0;
String answer= ("y = " + a+ b +c);
label.setText(answer);
}
});
return panel;
}
can you explain where I went wrong , thank you.
So, a NumberFormatException can occur when trying to parse a String, when the String does not contain a number. You did not give enough information to be sure, but I am going to presume that it is this line that causes the problem:
int x = Integer.parseInt(textField.getText());
One thing that strikes me as odd, is that you initialize the JTextField with 5 columns:
JTextField textField = new JTextField(5);
Is that what you want? If you wanted to pre-initialize the text field with a value of 5, you would have to do it like this:
JTextField textField = new JTextField("5");

Swing JScrollPane resizing to fit the viewport panel

I tried a lot of layout managers but none could solve my problem:
I want the items in a scrollPane to keep their size (preferred or minimum) and not being resized (reduced) to fit the viewport Panel. Since if it is a JTextArea, and if the text area has blank space and it is bigger then the viewport, it would reduce it so the blank text area won't be shown. I want the blank text area to be shown for appearance issues.
Im stacking one item after another using BoxLayout, and it seems to me that for text areas the setMinimum method fails.
If the text area has blank space, then the scrollbar of the ScrollPane won't appear, instead it only appears it there are no blank space left.
Any solution?
JScrollPane materialPane = new FScrollPane();
this.materialPaneView = new TPanel();
this.materialPaneView.setMinimumSize(new Dimension((int)(WIDTH*0.95), (int)(HEIGHT/2)));
this.materialPaneView.setLayout(new BoxLayout(this.materialPaneView, BoxLayout.Y_AXIS));
materialPane.setViewportView(materialPaneView);
materialPane.setMinimumSize(new Dimension((int)(WIDTH*0.95), (int)(HEIGHT/2)));
for(Material mat: this.unit.getMaterial()){
this.addMaterial(mat);
}
centerPanel.add(sectionPane);
centerPanel.add(exercisePane);
centerPanel.add(materialPane);
this.add(upperPanel, BorderLayout.NORTH);
this.add(centerPanel, BorderLayout.CENTER);
public void addMaterial(Material mat){
JTextField matName = new JTextField(30);
JPanel fieldButtonPanel = new TPanel();
fieldButtonPanel.setLayout(new GridLayout(1,2));
JPanel fieldPanel = new TPanel(new FlowLayout(FlowLayout.LEFT));
JPanel deleteMatButtonPanel = new TPanel(new FlowLayout(FlowLayout.RIGHT));
matName.setText(mat.getName());
matName.setMaximumSize(new Dimension(FFont.def.getSize()*20, 30));
fieldPanel.add(matName);
JButton deleteMat = new JButton("Delete Material");
deleteMatButtonPanel.add(deleteMat);
fieldButtonPanel.add(fieldPanel);
fieldButtonPanel.add(deleteMatButtonPanel);
fieldButtonPanel.setAlignmentX(LEFT_ALIGNMENT);
JTextArea matText = new FTextArea(mat.getDesc(), (int)(WIDTH*0.95), (int)(HEIGHT/3.4));
matText.setMinimumSize(new Dimension((int)(WIDTH*0.95), (int)(HEIGHT/3.5)));
/*matText.setMaximumSize(new Dimension((int)(WIDTH*0.95), (int)(HEIGHT/3.4)));*/
matText.setText(mat.getDesc());
matText.setAlignmentX(LEFT_ALIGNMENT);
this.materialPaneView.add(fieldButtonPanel);
this.materialPaneView.add(matText);
matName.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
mat.setName(matName.getText());
}
});
HEIGHT and WIDTH are constants, and TPanel FScrollPane are my predefined transparent panels. The BoxLayout panel is the viewport of a scrollPane, and still, it would resize the text areas.
I am not sure i get what you are asking for so please tell me if i totally missed the point...
As far as i know the Viewport size is controlled by the component inside the JScrollPane and the JScrollPane size wont change no matter what happens to the viewport.
You either want to:
A) Resize the JScrollPane to the same size as it's content.
I would implement listeners to look for the content size change and resize the ScrollPane accordingly but you need to pay attention to resize the whole Hierarchy too.
B) You want to resize the viewport so that it fits in the JScrollPane? Y'know without scrollbars.
I had this problem and fixed it by using a ScrollablePanel component. Check this answer, follow the link to download the .class and use it to use a JPanel that resizes to fit the ScrollPane.
Those arent very detailed answers but i will need more information about what you are trying to do before expanding on it. And your code isnt complete, always share a code that we can CTRL+C/V and readily verify the problem in our end.

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

Java Swing panel layered on top with centered text

I'm making a simple Jeopardy-esque game:
using Java Swing. It's obviously a JFrame with a JPanel in it and buttons in rows.
Now what I need is to add a layered panel with a centered and wrapped text in it:
Which I can remove later. I already tried using JTextPane and JTextArea and JPanel, none of those want to even display. The best effect I have achieved with AWT Panel, it does display but I can't center or wrap text in it.
Here's some code for which I appologise, I would usually try to make it short and readable but since it's not working I don't know what to do with it to make ti look better:
JLabel questionLabel = new JLabel(questionList.get(randomNumber).getQuestion(), SwingConstants.CENTER);
Font font = new Font("Arial", Font.PLAIN, 20);
//------------------JTextPane--------------------
JTextPane questionPane = new JTextPane();
questionPane.setForeground(Color.WHITE);
questionPane.setSize(gameWidth, gameHeight);
questionPane.setText(questionList.get(randomNumber).getQuestion());
questionPane.setFont(font);
questionPane.setEditable(false);
//------------------AWT panel--------------------
Panel awtPanel = new Panel();
awtPanel.setBackground(Color.blue);
awtPanel.setSize(game.getWidth(),game.getHeight());
Label labelQuestion = new Label("<html>" + questionList.get(randomNumber).getQuestion() + "</html>", Label.CENTER);
labelQuestion.setFont(font);
awtPanel.setForeground(Color.white);
awtPanel.add(labelQuestion);
//------------------JPanel-----------------------
JPanel layeredPanel = new JPanel();
layeredPanel.setBackground(Color.blue);
layeredPanel.setSize(game.getWidth(),game.getHeight());
JLabel jLabelQuestion = new JLabel("<html>" + questionList.get(randomNumber).getQuestion() + "</html>", SwingConstants.CENTER);
jLabelQuestion.setFont(font);
layeredPanel.setForeground(Color.WHITE);
layeredPanel.add(jLabelQuestion, BorderLayout.CENTER);
game.getLayeredPane().add(layeredPanel, JLayeredPane.DEFAULT_LAYER);
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
button.setEnabled(false);
font = new Font("Arial", Font.PLAIN, 16);
button.add(jLabelQuestion, BorderLayout.CENTER);
button.setDisabledIcon(new ImageIcon(source.getScaledInstance(gameWidth/4, gameHeight/5, java.awt.Image.SCALE_SMOOTH)));
questionList.remove(randomNumber);
logger.info(questionList.size());
game.getLayeredPane().remove(layeredPanel);
UPDATE: I chnaged to SWT rather than Swing, and I use the StackLayout with a few Composites in it, and just change between them as I see fit.
You can generally solve issues like this with a JLabel.
I would recommend encapsulating the above grid in the BorderLayout.CENTER of another pane, perhaps a new content pane. Then, add the caption to BorderLayout.NORTH.
As a more tangible example,
private void createContent() {
this.getContentPane().setLayout(new BorderLayout());
//establish the panel currently set as center, here labeled "everythingElse"
this.getContentPane().add(everythingElse, BorderLayout.CENTER);
//Create a JLabel with your caption
JLabel jlbl = new JLabel("Question");
//format that caption, most details being rather obvious, but most importantly:
jlbl.setHorizontalAlignment(SwingConstants.CENTER); //keeps text centered
this.getContentPane().add(jlbl, BorderLayout.NORTH); //add it to the top of the panel
//...other cleanup operations...
}
The issue with grid panes is that they have a limited tolerance for the number of components visible in them. If you overload one, it won't show. For BorderLayout panes, you can easily swap new items into and out of them.
For efficiency's sake, I might recommend compiling this JLabel as a final somewhere else in your code, and holding onto it for when you need it. This way, you will also dodge overhead from repeatedly creating the label object.
Lastly, avoid AWT whenever you can. It's been deprecated for an excess of ten years, and if you do use it you will run into numerous critical problems involving heavyweight and lightweight component incompatibilities. If you intend to use another windowing kit, consider implementing the new standard, JavaFX, with a JFXPane-- it's much more tolerant of HTML syntax, as well.

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

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.

Categories

Resources