Adding jlabel to a jframe using components - java

I have 2 classes,
My main class creates a frame and I want another class to add content to it. A bit of reading arroudn told me I should use components to do this however when I run my code the frame is empty.
public static void main(String[] args)
{
// create frame
JFrame frame = new JFrame();
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 600;
// set frame attributes
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("My Frame");
frame.setVisible(true);
Component1 Com = new Component1();
Component add = frame.add(Com);
}
My Component class creates a JLabel
public class Component1 extends JComponent {
public void paintComponent()
{
JLabel label = new JLabel("<html>Some Text</html>");
}
}
I don't get any compile errors, however I dont get any text in my JFrame.
Can anyone explain what I'm doing wrong?
Chris

You need to add the JLabel. Also better to extend JPanel instead of JComponent as it has a default layout manager and will make any added components appear without the need to set component sizes. paintComponent is used for custom painting BTW.
public class Component1 extends JPanel {
Component1() {
JLabel label = new JLabel("<html>Some Text</html>");
add(label);
}
}

No need to create a new Component. Just call frame.getContentPane().add(label). And initialize your label before this.

Related

How i can disable JPanel when JFrame Start

I want to disable a JPanel at the start of JFrame
I know the code that I have to use but I do not know where I should put it
public class Fenetre1 extends JFrame {
//code JFrame
private class Affichage implements ActionListener {
//action
}
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Fenetre1 f = new Fenetre1 ();
f.panel.setEnabled(false);
}
You can setEnabled(false) when you create the JPanel. If you want to toggle enabling the JPanel, you should probably use a listener.
Notes from Java documentation (https://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html)
Note: Disabling a component does not disable its children.
Note: Disabling a lightweight component does not prevent it from receiving MouseEvents.
JFrame jframe = new JFrame();
JPanel jpanel = new JPanel();
jpanel.setEnabled(false);
jframe.add(jpanel);
Maybe JPanel can't be focused but Objects like JTextField or JTextArea are focus-able.
If you have some objects like those in the JPanel , then use textArea.setFocusable(false).
And you can try jPanel.setEnabled(false).
Your answer inspired me a bit, I use a component table in the JPanel
so,I went through the entire table and disabled each component
I put the code in the class inheriting the JFrame:
for(int j= 0;j<tab_component.length;j++)
{
tab_buttonsOperateur[j].setEnabled(false);
}
thanks anyway

Setting Location of JButton never works?

I'm trying to create a button and place it in a certain location, but for some reason it never goes in that specific location. I tried putting it a panel, using setBounds, using setLocation... but It doesn't seem to work...
I'm running this file in another file.
public class Inventory extends JPanel
{
private final static int frameWidth = 200;
private final static int frameHeight = 500;
private final static int screenLocationX = 100;
private final static int screenLocationY = 50;
private Panel panel;
private JFrame frame;
private JPanel jpanel;
public Inventory()
{
panel = new Panel();
frame = new JFrame();
JButton button = new JButton("Add Gem");
button.addActionListener(new Listener());
button.setPreferredSize(new Dimension(frameWidth,50));
// button.setLocation(0,400);
// button.setBounds(0,400,frameWidth,50);
panel.setVisible(true);
frame.setContentPane(panel);
frame.add(button);
frame.setVisible(true);
frame.setSize(frameWidth, frameHeight);
frame.setLocation(screenLocationX, screenLocationY);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
panel.addImage(new Gems());
}
}
}
Before adding panel to the frame use:
panel.setLayout(null); //setting the default settings of panel to null
and then use:
button.setBounds(300, 300, 300, 300); //bounding the button at specific location
this would work..
You need to turn the LayoutManager off
panel.setLayout(null);
JFrame by default uses a BorderLayout and, by default, components are added to the BorderLayout.CENTER position, unless otherwise specified
In this setup, the component will be placed on the centre of the frame and sized to fill it
Remember, each platform/OS renders content differently and these differences will change the amount of space required to display your components and all of this will effective the relationships between all the other components...
You consider changing the layout manager and using a combination of EmptyBorders and insets/padding to influence the location/size of your components. Try something like GridBagLayout or if your adventurous, checking out MigLayout
One of the first lessons you need to learn with GUI program (on just about any platform) is pixel perfect layouts are an illusion, there are too many variables which effect how content is rendered and how these can change the amount of space individual components will need in order to be displayed correctly...

Java: JTextField won't appear

public class HandleUI {
public static void setUpUI(){
JPanel jPan = new JPanel();
FlowLayout flow = new FlowLayout();
jPan.setLayout(flow);
txtFld = new JTextField();
txtFld.setSize(550,5);
jPan.add(txtFld);
jPan.setSize(10,200);
MainClass.mainFrame.add(jPan);
int gapX = MainClass.mainFrame.getX()-(txtFld.getX()/2);
}
//Instance variables.
public static JTextField txtFld;
public JButton [] buttons;
}
public class MainClass {
public static void main (String [] args){
int frameX = Constants.FRAME_WIDTH;
int frameY = Constants.FRAME_HEIGHT;
mainFrame = new JFrame();
mainFrame.setSize(frameX,frameY);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
HandleUI.setUpUI();
}
//Instance variables
public static JFrame mainFrame;
}
It's supposed to show JTextField, but as you might have guessed - JFrame shows nothing. I didn't type in imports on purpose, but they are all there. I can't find the problem. Can anyone help?
1.) Simply write:
JTextField tField = new JTextField(10);
Here In the constructor you are passing the number of columns, which is sufficient for a layout like FlowLayout to set the size of the JTextField
2.) The line mainFrame.setVisible(true); must be the last line of the main method. You need to put the code at main() method, inside SwingUtilities.invokeLater(...) thingy.
3.) Instead of setting size on the JFrame use JFrame.pack(), to set the window to the preferred size.
4.) Creation of unnecessary static members is a design flaw. Try to keep yourself away from such thingies.
5.) Read a bit about Concurrency in Swing
One Example Program for help(Use the order of lines as specified in this answer):
import java.awt.*;
import javax.swing.*;
public class Example {
private void displayGUI() {
JFrame frame = new JFrame("Example Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
JTextField tField = new JTextField(10);
contentPane.add(tField);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new Example().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
You have to call setVisible(true) on your JFrame AFTER having initialised your UI.
Simply pulling the following line:
HandleUI.setUpUI();
... right before:
mainFrame.setVisible(true);
... will do the trick.
As a side note, I'd like to point out that setting the size of your text field won't really work like you did. You probably would use setPreferredSize(Dimension) instead. Or, even better, organise your UI only using Layouts and not manually setting any component's size.

Swing - scroll JFrame content without using scrollbars

I have following problem. Is there a way to scroll Jframe content without using scrollbars, just to do it programatically in code. I have Japplet inside and I can't find a way to scroll its content without showing scrolls. Whole scrolling action should be performed not on user action, but when my thread wants to do so. Waiting for help, thanks.
I can't find any way to do that. I was trying to add my component (Applet) to Jscrollpane and that to jframe, but it causes situation, when only white screen is displayed.
JFrame class:
public class SimulationFrame extends JFrame {
private SimulationWindow simulationWindow;
public SimulationFrame() throws HeadlessException {
super(PropertiesHelper.getWindowTitle());
simulationWindow = new SimulationWindow();
JScrollPane scrollPane = new JScrollPane(simulationWindow);
this.getContentPane().add(scrollPane);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
}
JComponent:
public SimulationWindow() {
setLayout(new BorderLayout());
graph = GraphHelper.provideGraphInstance();
Dimension layoutSize = new Dimension(PropertiesHelper.getGraphHolderWidth(),
PropertiesHelper.getGraphHolderHeight());
graphLayout = new StaticLayout<Checkpoint, Route>(graph, new CheckpointPositionTransformer());
graphLayout.setSize(layoutSize);
visualizationViewer = new VisualizationViewer<Checkpoint, Route>(graphLayout, new Dimension(
PropertiesHelper.getWindowWidth(), PropertiesHelper.getWindowHeight()));
visualizationViewer.getRenderContext().setVertexLabelTransformer(new CheckpointLabelTransformer());
visualizationViewer.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
visualizationViewer.getRenderContext().setVertexFillPaintTransformer(new CheckpointColorTransformer());
visualizationViewer.getRenderContext().setEdgeDrawPaintTransformer(new RouteColorTransformer());
visualizationViewer.getRenderContext().setEdgeLabelTransformer(new RouteLabelTransformer());
final ImageIcon mapBackground = createMapBackground();
if (mapBackground != null) {
mapBackgroundImagePaintable = new BackgroundImagePaintable(visualizationViewer, mapBackground);
visualizationViewer.addPreRenderPaintable(mapBackgroundImagePaintable);
}
add(visualizationViewer);
scrollRectToVisible(new Rectangle(1000,100));
}
VisualizationViewer is a class that extends JPanel. Placing scrollRectToVisible in this constructor didn't works.
Any tips? Perhaps this implementation is wrong, where Jcomponent contains Jpanel itself?
Use method
public void scrollRectToVisible(Rectangle aRect)
of the JComponent added in JScrollPane

Java (Swing): JScrollPane.setBounds() does not apply?

I'm trying to create a simple JList with a scrollbar, and therefore i need to have the JList within a JScrollPane. So far, so good. However, for some reason i can't resize/position the JScrollPane!? It sounds logic that everything inside it should stretch to 100%, so if i set the JScrollPane to be 300px wide, the elements inside will be as well. Is that correct?
While you're at it, please critisize and give me hints if i should change something or optimize it.
Anyhow, here's the code:
package train;
import java.awt.*;
import javax.swing.*;
public class GUI {
private DefaultListModel loggerContent = new DefaultListModel();
private JList logger = new JList(loggerContent);
GUI() {
JFrame mainFrame = new JFrame("title");
this.addToLog("testing testing");
this.addToLog("another test");
// Create all elements
logger = new JList(loggerContent);
JScrollPane logWrapper = new JScrollPane(logger);
logWrapper.setBounds(10, 10, 20, 50);
// Add all elements
mainFrame.add(logWrapper);
// Show everything
mainFrame.setSize(new Dimension(600, 500));
mainFrame.setVisible(true);
}
public void addToLog(String inputString) {
int size = logger.getModel().getSize();
loggerContent.add(size, inputString);
}
}
Thanks in advance,
qwerty
EDIT: Here's a screenshot of it running: http://i.stack.imgur.com/sLGgQ.png
The setVisibleRowCount() method of JList is particularly convenient for this, as suggested in the relevant tutorial. ListDemo is a good example.
Addendum:
please critisize and give me hints…
Well, since you ask: Don't invoke public methods in the constructor; make them private or invoke them after the constructor finishes. There's no need to find the last index for add(), when addElement() is available. Also, be sure to construct your GUI on the event dispatch thread .
import java.awt.*;
import javax.swing.*;
/** #see http://stackoverflow.com/questions/5422160 */
public class ListPanel extends JPanel {
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
ListPanel() {
list.setVisibleRowCount(5);
}
public void append(String inputString) {
model.addElement(inputString);
}
private void init() {
for (int i = 0; i < 10; i++) {
this.append("String " + String.valueOf(i));
}
JFrame mainFrame = new JFrame("GUI");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane jsp = new JScrollPane(list);
mainFrame.add(jsp);
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ListPanel().init();
}
});
}
}
The bounds & size of a component are generally ignored over that of it's preferred size and the constraints of the layout being used by the container.
To solve this problem, learn how to use layouts & apply them appropriately.
Try to put your JScrollPane inside a JPanel and add the panel to the frame.
JPanel panel = new JPanel();
panel.add (logWrapper);
mainFrame.add(panel);
Then set the bounds of the panel instead of the JScrollpane
panel.setBounds(10, 10, 20, 50);
The probles is that Swing uses layout managers to control child bounds property. Adding a JScrollpane directly to the main frame, doesn't allow you to choose right bounds properly.

Categories

Resources