I would like to know how to draw a line inside a JPanel
that is within a JFrame
, at the push of a button. The layout of the button and JPanel
within JFrame
is exemplified in the image below:
Whenthebuttonispressedtheprogramshoulddrawalinefrompoint10.10topoint100,100ofJPanel
.I'vealreadyseenexampleslikethecodebelowtodrawline.
publicvoiddesenha(Graphicsg){g.setColor(red);g.drawLine(10,10,100,100);}
TheproblemisthatIdonotknowwheretousethismethodsothatthelineisdrawninJPanel
,andonlywhenthebuttonispressed.
Codes:MainClass:
publicclassTeste{publicstaticvoidmain(String[]args){Telat=newTela();t.setVisible(true);}}
ScreenClass:
publicclassTelaextendsjavax.swing.JFrame{publicTela(){initComponents();}@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
botao = new javax.swing.JButton();
viewport = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
botao.setText("desenha");
botao.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botaoActionPerformed(evt);
}
});
viewport.setBackground(new java.awt.Color(255, 255, 255));
viewport.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 3));
javax.swing.GroupLayout viewportLayout = new javax.swing.GroupLayout(viewport);
viewport.setLayout(viewportLayout);
viewportLayout.setHorizontalGroup(
viewportLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 361, Short.MAX_VALUE)
);
viewportLayout.setVerticalGroup(
viewportLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 231, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(142, 142, 142)
.addComponent(botao))
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(viewport, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(13, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(botao)
.addGap(18, 18, 18)
.addComponent(viewport, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void botaoActionPerformed(java.awt.event.ActionEvent evt) {
}
// Variables declaration - do not modify
public javax.swing.JButton botao;
public static javax.swing.JPanel viewport;
// End of variables declaration
}