How to center text and a JComponent in a JTextPane vertically? - java

Currently it looks so
What to do so that it looks so?
Below is my code:
JFrame f = new JFrame();
JTextPane textPane = new JTextPane();
JTextField component = new JTextField(" ");
component.setMaximumSize(component.getPreferredSize());
textPane.setSelectionStart(textPane.getDocument().getLength());
textPane.setSelectionEnd(textPane.getDocument().getLength());
textPane.insertComponent(component);
try {
textPane.getDocument().insertString(textPane.getDocument().getLength(), "text",
new SimpleAttributeSet());
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
f.add(new JScrollPane(textPane));
f.setSize(200, 100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
The single question which is near to this topic I found: JTextPane insert component, faulty vertical alignment
But there is no answer how to change the alignment. But it must be possible according to the discussion there.

You can use this http://java-sl.com/tip_center_vertically.html
It should work with JComponents as well.
You can also override LabelView's getPreferredSpan() adding some space to the bottom.
Alternatively you can try to override RowView inner class in ParagraphView
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/javax/swing/text/ParagraphView.java#ParagraphView.Row
That points to inner class Row extends BoxView
You should replace it with own one. Try to override
public float getAlignment(int axis)
to return CENTER (0.5). If this does not help override layoutMinorAxis(0 to return proper offsets (shifted).

Define a style for your document with a JLabel and set the vertical aligment on it:
Style s = doc.addStyle("icUf", regular);
ImageIcon icUf = createImageIcon("uf.png", "Unidad Funcional");
if (icUf != null) {
JLabel jl = new JLabel(icUf);
jl.setVerticalAlignment(JLabel.CENTER);
StyleConstants.setComponent(s, jl);
}
Insert the label:
doc.insertString(doc.getLength(), " ", doc.getStyle("icUf"));
and the text:
doc.insertString(doc.getLength(), " text ", doc.getStyle("bold"));

Based on the answer above (which didn't work for me, but helped me find this), I used:
Style s = doc.addStyle("icUf", regular);
ImageIcon icUf = createImageIcon("uf.png", "Unidad Funcional");
if (icUf != null) {
// create label with icon AND text
JLabel jl = new JLabel("some text",icUf, SwingConstants.LEFT);
StyleConstants.setComponent(s, jl);
}
doc.insertString(doc.getLength(), " ", doc.getStyle("icUf"))
This properly aligned the text 'some text' and the icon.

Related

JAVA - GridLayout and JScrollPane behave unexpected

My GridLayout in Java behaving diffrently like I expected.
I want to have multiple Boxes within an JScrollPane (like in the screenshot below).
But when i have to less entries (for example 2) the height of the boxes are 100% height.
Does someone can tell me what i made wrong in my code?
ResultSet result = MysqlDataReader.ReadFromDataBase("DUMMY",connectionStrato);
innerPanel.removeAll();
innerPanel.setLayout(new GridLayout(Integer.parseInt(Math.round(result.getRow() / 3) + ""), 6, 2, 2));
while(result.next()){
URL url;
Image image;
try{
url = new URL("DUMMY" + result.getString(1) + ".jpg");
image = ImageIO.read(url.openStream());
} catch (MalformatedURLException ex) {
url = new URL("DUMMY");
image = ImageIO.read(url.openStream());
Logger.getLogger(ItemforList.class.getName()).log(Level.SEVERE, null, ex);
} catch(IOException ex){
url = new URL("DUMMY);
image = ImageIO.read(url.openStream());
Logger.getLogger(ItemforList.class.getName()).log(Level.SEVERE, null, ex);
}
ItemforList item = new ItemforList("DUMMY"+result.getString(1)+".jpg", result.getString(1)+"");
innerPanel.add(item)
}
scrollPaneL.setViewportView(innerPanel);
Component[] components = innerPanel.getComponents();
for (Component component : components){
if(component.getClass().equals(ItemforList.class)){
ItemforList item = (ItemforList) component;
System.out.printLn("TEST");
item.SetResizedIcon();
}
}
You didn't post any code so I can't comment on or directly fix that.
But to answer your question, the way to fix your problem is to fill in the extra grid boxes with dummy components - something just to take up that space

BoxLayout adding left margin

I've got a JPanel that has a BoxLayout (Page axis), and I want to lay out two components, one on top of the other.
My problem is the margin to the left of the large lipsum box, how can I get rid of this? If I don't add the top components, there is no margin.
Here's my code, the second image is created by not adding headerPanel:
JLabel commandLabel = new JLabel(command);
JLabel paramLabel = new JLabel(params);
JLabel descLabel = new JLabel("<html><body style='width: 200px;'>" + description + "</body></html>");
Font baseFont = commandLabel.getFont(), commandFont, paramFont, descFont;
commandFont = baseFont.deriveFont(Font.BOLD);
paramFont = baseFont.deriveFont(Font.ITALIC);
descFont = baseFont.deriveFont(Font.PLAIN);
commandLabel.setFont(commandFont);
paramLabel.setFont(paramFont);
descLabel.setFont(descFont);
descLabel.setAlignmentX(LEFT_ALIGNMENT);
descLabel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke()));
JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
headerPanel.add(commandLabel);
headerPanel.add(paramLabel);
this.add(headerPanel);
this.add(descLabel);
This class extends JPanel, and is added to a JFrame, which is simply pack()'d
Though I couldn't tell where the observed behaviour comes from, the expected display could be achieved by using an intermediate JPanel to contain your label, rather than adding the JLabel directly :
JLabel commandLabel = new JLabel(command);
JLabel paramLabel = new JLabel(params);
JLabel descLabel = new JLabel("<html><body style='width: 200px;'>" + description + "</body></html>");
Font baseFont = commandLabel.getFont(), commandFont, paramFont, descFont;
commandFont = baseFont.deriveFont(Font.BOLD);
paramFont = baseFont.deriveFont(Font.ITALIC);
descFont = baseFont.deriveFont(Font.PLAIN);
commandLabel.setFont(commandFont);
paramLabel.setFont(paramFont);
descLabel.setFont(descFont);
descLabel.setAlignmentX(LEFT_ALIGNMENT);
descLabel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke()));
JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
JPanel descPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));// added
headerPanel.add(commandLabel);
headerPanel.add(paramLabel);
descPanel.add(descLabel);// added
this.add(headerPanel);
this.add(descPanel);// modified
My problem is the margin to the left of the large lipsum box, how can I get rid of this?
You need to make the alignments of your components consistent. That is the alignment "X" property of all the components should be left aligned.
I'm guessing the JLabel is center aligned so you need to use:
descLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
See Fixing Alignment Problems section from the Swing tutorial on How to Use BoxLayout for more information and examples.

JScrollPane in Java

I wrote a little code to see how the scroll Pane functions but my code never worked.
here's the code,
public Fenetre(){
this.setTitle("Data Simulator");
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
String hello = "hello";
int number = 69;
JPanel content = new JPanel();
content.setBackground(Color.LIGHT_GRAY);
//Box imad = Box.createHorizontalBox();
JTextArea textArea = new JTextArea(10, 10);
JLabel imad = new JLabel();
imad.setText(hello + " your favorite number is " + number + "\nRight?");
JScrollPane scrollPane = new JScrollPane();
setPreferredSize(new Dimension(450, 110));
scrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setEnabled(true);
scrollPane.setWheelScrollingEnabled(true);
scrollPane.setViewportView(textArea);
scrollPane.setViewportView(imad);
add(scrollPane, BorderLayout.CENTER);
//---------------------------------------------
//On ajoute le conteneur
scrollPane.add(textArea);
scrollPane.add(imad);
content.add(textArea);
content.add(imad);
content.add(scrollPane);
this.setContentPane(content);
this.setVisible(true);
this.setResizable(false);
}
When I run it, I get a little window with the textArea and next to the text area a very little white square, which is the scrollpane i suppose because when I remove it from the code, this square disappears. When I write in the text area and exceed the window's dimension, I can't scroll vertically using the mouse wheel, and not horizontally at all. I saw many examples on internet and I can't understand why my code doesn't work??
Any help explaining how scrollpane works?
scrollPane.setViewportView(textArea);
scrollPane.setViewportView(imad);
Only one component can be added to the viewport of the scroll pane, so the label replaces the text area.
content.add(textArea);
content.add(imad);
A component can only have a single parent. The above code removes the label from the scrollpane, so nothing is now in the scrollpane.
Try something like:
JScrollPane = new JScrollPane( textArea );
JPanel content = new JPanel( new BorderLayout() );
content.add(scrollPane, BorderLayout.CENTER);
content.add(imad, BorderLayout.PAGE_END);
setContentPane( content );
For a better solution, start with the working example found in the Swing tutorial on How to Use Text Areas and then modify the code. This way you will start with a better structured program that follows Swing standards.

How to change font with showconfirmdialog?

I have tried many different tutorials and none have worked this is what I have. Any help?
UIManager.put("OptionPane.font", new FontUIResource(new Font("Press Start 2P", Font.PLAIN, 11)));
if (questionNumber == questions.size()) {
triviagui.questionFrame.setVisible(false);
JOptionPane.showMessageDialog(null, "Your score for this level was : " + levelScore + " out of 10. \n Your total score is " + triviagui.totalScore, "Scores", JOptionPane.INFORMATION_MESSAGE, pokeballIcon);
}
this is how I change my font in a JLabel, so maybe it is any help?
message = new JLabel(textMessage);
// create bigger text (to-times-bigger)
Font f = message.getFont();
message.setFont(new Font(f.getName(), Font.PLAIN, f.getSize()*2));
// put text in middle of vertical space
message.setVerticalTextPosition(JLabel.CENTER);
You just take the font from your label, and reset the font as you like.
Maybe you can do the same with your JDialog?
I found a working answer here: formatting text in jdialog box
this could be a method called by the actionListener of a button:
public void openPopUp(){
String t = "<html>The quick <font color=#A62A2A>brown</font> fox.";
JOptionPane.showMessageDialog(null, t);
}
Gives you this result:

Changing the location of a label and text box

Right now the label is on top of the text box. I would like to be able to set the location of the text box and label so that the label is to the left of the text box.
this.container = this.getContentPane();
this.container.setLayout(new FlowLayout());
this.searchText = new JLabel("Enter text to be searched: ");
this.charText = new JLabel("Enter a character: ");
this.target = new JTextArea(3,30);
Use a JPanel with the FlowLayout.
JPanel myPanel = new JPanel();
myPanel.add(searchText);
myPanel.add(target);
container.add(myPanel,FlowLayout.LEFT);
Note you should create two panels if you want two labels and two text areas to be displayed in the fashion that you want. For more information on FlowLayout:
Flow Layout
In any case you should use an editor for more advance positioning.
You can use a GridLayout like this :
this.container = new JPanel(new GridLayout(1, 2) );
this.searchText = new JLabel("Enter text to be searched: ");
this.charText = new JLabel("Enter a character: ");
this.target = new JTextArea(3,30);
container.add(searchText);
container.add(target);

Categories